repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/VisualBasic/Test/Emit/PDB/PDBEmbeddedSourceTests.vb | ' 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.
Imports System.IO
Imports System.Reflection.Metadata
Imports System.Reflection.PortableExecutable
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class PDBEmbeddedSourceTests
Inherits BasicTestBase
<Theory>
<InlineData(DebugInformationFormat.PortablePdb)>
<InlineData(DebugInformationFormat.Pdb)>
<WorkItem(28045, "https://github.com/dotnet/roslyn/issues/28045")>
Public Sub StandalonePdb(format As DebugInformationFormat)
Dim source1 = WithWindowsLineBreaks("
Imports System
Class C
Public Shared Sub Main()
Console.WriteLine()
End Sub
End Class
")
Dim source2 = WithWindowsLineBreaks("
' no code
")
Dim tree1 = Parse(source1, "f:/build/goo.vb")
Dim tree2 = Parse(source2, "f:/build/nocode.vb")
Dim c = CreateCompilationWithMscorlib40({tree1, tree2}, options:=TestOptions.DebugDll)
Dim embeddedTexts = {
EmbeddedText.FromSource(tree1.FilePath, tree1.GetText()),
EmbeddedText.FromSource(tree2.FilePath, tree2.GetText())
}
c.VerifyPdb(
<symbols>
<files>
<file id="1" name="f:/build/goo.vb" language="VB" checksumAlgorithm="SHA1" checksum="03-28-AD-AE-03-81-AD-8B-6E-C4-60-7B-13-4E-9C-4F-8E-D6-D5-65"><![CDATA[
Imports System
Class C
Public Shared Sub Main()
Console.WriteLine()
End Sub
End Class
]]></file>
<file id="2" name="f:/build/nocode.vb" language="VB" checksumAlgorithm="SHA1" checksum="40-43-2C-44-BA-1C-C7-1A-B3-F3-68-E5-96-7C-65-9D-61-85-D5-44"><![CDATA[
' no code
]]></file>
</files>
<methods>
<method containingType="C" name="Main">
<sequencePoints>
<entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="29" document="1"/>
<entry offset="0x1" startLine="6" startColumn="9" endLine="6" endColumn="28" document="1"/>
<entry offset="0x7" startLine="7" startColumn="5" endLine="7" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x8">
<namespace name="System" importlevel="file"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>,
embeddedTexts, format:=format)
End Sub
<Fact>
Public Sub EmbeddedPdb()
Const source = "
Imports System
Class C
Public Shared Sub Main()
Console.WriteLine()
End Sub
End Class
"
Dim tree = Parse(source, "f:/build/goo.cs")
Dim c = CreateCompilationWithMscorlib40(tree, options:=TestOptions.DebugDll)
Dim pdbStream = New MemoryStream()
Dim peBlob = c.EmitToArray(
EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded),
embeddedTexts:={EmbeddedText.FromSource(tree.FilePath, tree.GetText())})
pdbStream.Position = 0
Using peReader As New PEReader(peBlob)
Dim embeddedEntry = peReader.ReadDebugDirectory().Single(Function(e) e.Type = DebugDirectoryEntryType.EmbeddedPortablePdb)
Using embeddedMetadataProvider As MetadataReaderProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embeddedEntry)
Dim pdbReader = embeddedMetadataProvider.GetMetadataReader()
Dim embeddedSource =
(From documentHandle In pdbReader.Documents
Let document = pdbReader.GetDocument(documentHandle)
Select New With
{
.FilePath = pdbReader.GetString(document.Name),
.Text = pdbReader.GetEmbeddedSource(documentHandle)
}).Single()
Assert.Equal(embeddedSource.FilePath, "f:/build/goo.cs")
Assert.Equal(source, embeddedSource.Text.ToString())
End Using
End Using
End Sub
End Class
End Namespace
| ' 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.
Imports System.IO
Imports System.Reflection.Metadata
Imports System.Reflection.PortableExecutable
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class PDBEmbeddedSourceTests
Inherits BasicTestBase
<Theory>
<InlineData(DebugInformationFormat.PortablePdb)>
<InlineData(DebugInformationFormat.Pdb)>
<WorkItem(28045, "https://github.com/dotnet/roslyn/issues/28045")>
Public Sub StandalonePdb(format As DebugInformationFormat)
Dim source1 = WithWindowsLineBreaks("
Imports System
Class C
Public Shared Sub Main()
Console.WriteLine()
End Sub
End Class
")
Dim source2 = WithWindowsLineBreaks("
' no code
")
Dim tree1 = Parse(source1, "f:/build/goo.vb")
Dim tree2 = Parse(source2, "f:/build/nocode.vb")
Dim c = CreateCompilationWithMscorlib40({tree1, tree2}, options:=TestOptions.DebugDll)
Dim embeddedTexts = {
EmbeddedText.FromSource(tree1.FilePath, tree1.GetText()),
EmbeddedText.FromSource(tree2.FilePath, tree2.GetText())
}
c.VerifyPdb(
<symbols>
<files>
<file id="1" name="f:/build/goo.vb" language="VB" checksumAlgorithm="SHA1" checksum="03-28-AD-AE-03-81-AD-8B-6E-C4-60-7B-13-4E-9C-4F-8E-D6-D5-65"><![CDATA[
Imports System
Class C
Public Shared Sub Main()
Console.WriteLine()
End Sub
End Class
]]></file>
<file id="2" name="f:/build/nocode.vb" language="VB" checksumAlgorithm="SHA1" checksum="40-43-2C-44-BA-1C-C7-1A-B3-F3-68-E5-96-7C-65-9D-61-85-D5-44"><![CDATA[
' no code
]]></file>
</files>
<methods>
<method containingType="C" name="Main">
<sequencePoints>
<entry offset="0x0" startLine="5" startColumn="5" endLine="5" endColumn="29" document="1"/>
<entry offset="0x1" startLine="6" startColumn="9" endLine="6" endColumn="28" document="1"/>
<entry offset="0x7" startLine="7" startColumn="5" endLine="7" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x8">
<namespace name="System" importlevel="file"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>,
embeddedTexts, format:=format)
End Sub
<Fact>
Public Sub EmbeddedPdb()
Const source = "
Imports System
Class C
Public Shared Sub Main()
Console.WriteLine()
End Sub
End Class
"
Dim tree = Parse(source, "f:/build/goo.cs")
Dim c = CreateCompilationWithMscorlib40(tree, options:=TestOptions.DebugDll)
Dim pdbStream = New MemoryStream()
Dim peBlob = c.EmitToArray(
EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded),
embeddedTexts:={EmbeddedText.FromSource(tree.FilePath, tree.GetText())})
pdbStream.Position = 0
Using peReader As New PEReader(peBlob)
Dim embeddedEntry = peReader.ReadDebugDirectory().Single(Function(e) e.Type = DebugDirectoryEntryType.EmbeddedPortablePdb)
Using embeddedMetadataProvider As MetadataReaderProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embeddedEntry)
Dim pdbReader = embeddedMetadataProvider.GetMetadataReader()
Dim embeddedSource =
(From documentHandle In pdbReader.Documents
Let document = pdbReader.GetDocument(documentHandle)
Select New With
{
.FilePath = pdbReader.GetString(document.Name),
.Text = pdbReader.GetEmbeddedSource(documentHandle)
}).Single()
Assert.Equal(embeddedSource.FilePath, "f:/build/goo.cs")
Assert.Equal(source, embeddedSource.Text.ToString())
End Using
End Using
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/VisualStudio/Core/Def/Implementation/GenerateType/GenerateTypeDialog.xaml.cs | // 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.
#nullable disable
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.VisualStudio.PlatformUI;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType
{
/// <summary>
/// Interaction logic for GenerateTypeDialog.xaml
/// </summary>
internal partial class GenerateTypeDialog : DialogWindow
{
private readonly GenerateTypeDialogViewModel _viewModel;
// Expose localized strings for binding
public string GenerateTypeDialogTitle { get { return ServicesVSResources.Generate_Type; } }
public string TypeDetails { get { return ServicesVSResources.Type_Details_colon; } }
public string Access { get { return ServicesVSResources.Access_colon; } }
public string Kind { get { return ServicesVSResources.Kind_colon; } }
public string NameLabel { get { return ServicesVSResources.Name_colon1; } }
public string Location { get { return ServicesVSResources.Location_colon; } }
public string Project { get { return ServicesVSResources.Project_colon; } }
public string FileName { get { return ServicesVSResources.File_Name_colon; } }
public string CreateNewFile { get { return ServicesVSResources.Create_new_file; } }
public string AddToExistingFile { get { return ServicesVSResources.Add_to_existing_file; } }
public string OK { get { return ServicesVSResources.OK; } }
public string Cancel { get { return ServicesVSResources.Cancel; } }
public GenerateTypeDialog(GenerateTypeDialogViewModel viewModel)
: base("vsl.GenerateFromUsage")
{
_viewModel = viewModel;
SetCommandBindings();
InitializeComponent();
DataContext = viewModel;
}
private void SetCommandBindings()
{
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"SelectAccessKind",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.A, ModifierKeys.Alt) })),
Select_Access_Kind));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"SelectTypeKind",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.K, ModifierKeys.Alt) })),
Select_Type_Kind));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"SelectProject",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.P, ModifierKeys.Alt) })),
Select_Project));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"CreateNewFile",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.C, ModifierKeys.Alt) })),
Create_New_File));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"AddToExistingFile",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.X, ModifierKeys.Alt) })),
Add_To_Existing_File));
}
private void Select_Access_Kind(object sender, RoutedEventArgs e)
=> accessListComboBox.Focus();
private void Select_Type_Kind(object sender, RoutedEventArgs e)
=> kindListComboBox.Focus();
private void Select_Project(object sender, RoutedEventArgs e)
=> projectListComboBox.Focus();
private void Create_New_File(object sender, RoutedEventArgs e)
=> createNewFileRadioButton.Focus();
private void Add_To_Existing_File(object sender, RoutedEventArgs e)
=> addToExistingFileRadioButton.Focus();
private void FileNameTextBox_LostFocus(object sender, RoutedEventArgs e)
=> _viewModel.UpdateFileNameExtension();
private void OK_Click(object sender, RoutedEventArgs e)
{
_viewModel.UpdateFileNameExtension();
if (_viewModel.TrySubmit())
{
DialogResult = true;
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
=> DialogResult = false;
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly GenerateTypeDialog _dialog;
public TestAccessor(GenerateTypeDialog dialog)
=> _dialog = dialog;
public Button OKButton => _dialog.OKButton;
public Button CancelButton => _dialog.CancelButton;
public ComboBox AccessListComboBox => _dialog.accessListComboBox;
public ComboBox KindListComboBox => _dialog.kindListComboBox;
public TextBox TypeNameTextBox => _dialog.TypeNameTextBox;
public ComboBox ProjectListComboBox => _dialog.projectListComboBox;
public RadioButton AddToExistingFileRadioButton => _dialog.addToExistingFileRadioButton;
public ComboBox AddToExistingFileComboBox => _dialog.AddToExistingFileComboBox;
public RadioButton CreateNewFileRadioButton => _dialog.createNewFileRadioButton;
public ComboBox CreateNewFileComboBox => _dialog.CreateNewFileComboBox;
}
}
}
| // 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.
#nullable disable
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.VisualStudio.PlatformUI;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType
{
/// <summary>
/// Interaction logic for GenerateTypeDialog.xaml
/// </summary>
internal partial class GenerateTypeDialog : DialogWindow
{
private readonly GenerateTypeDialogViewModel _viewModel;
// Expose localized strings for binding
public string GenerateTypeDialogTitle { get { return ServicesVSResources.Generate_Type; } }
public string TypeDetails { get { return ServicesVSResources.Type_Details_colon; } }
public string Access { get { return ServicesVSResources.Access_colon; } }
public string Kind { get { return ServicesVSResources.Kind_colon; } }
public string NameLabel { get { return ServicesVSResources.Name_colon1; } }
public string Location { get { return ServicesVSResources.Location_colon; } }
public string Project { get { return ServicesVSResources.Project_colon; } }
public string FileName { get { return ServicesVSResources.File_Name_colon; } }
public string CreateNewFile { get { return ServicesVSResources.Create_new_file; } }
public string AddToExistingFile { get { return ServicesVSResources.Add_to_existing_file; } }
public string OK { get { return ServicesVSResources.OK; } }
public string Cancel { get { return ServicesVSResources.Cancel; } }
public GenerateTypeDialog(GenerateTypeDialogViewModel viewModel)
: base("vsl.GenerateFromUsage")
{
_viewModel = viewModel;
SetCommandBindings();
InitializeComponent();
DataContext = viewModel;
}
private void SetCommandBindings()
{
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"SelectAccessKind",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.A, ModifierKeys.Alt) })),
Select_Access_Kind));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"SelectTypeKind",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.K, ModifierKeys.Alt) })),
Select_Type_Kind));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"SelectProject",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.P, ModifierKeys.Alt) })),
Select_Project));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"CreateNewFile",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.C, ModifierKeys.Alt) })),
Create_New_File));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"AddToExistingFile",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.X, ModifierKeys.Alt) })),
Add_To_Existing_File));
}
private void Select_Access_Kind(object sender, RoutedEventArgs e)
=> accessListComboBox.Focus();
private void Select_Type_Kind(object sender, RoutedEventArgs e)
=> kindListComboBox.Focus();
private void Select_Project(object sender, RoutedEventArgs e)
=> projectListComboBox.Focus();
private void Create_New_File(object sender, RoutedEventArgs e)
=> createNewFileRadioButton.Focus();
private void Add_To_Existing_File(object sender, RoutedEventArgs e)
=> addToExistingFileRadioButton.Focus();
private void FileNameTextBox_LostFocus(object sender, RoutedEventArgs e)
=> _viewModel.UpdateFileNameExtension();
private void OK_Click(object sender, RoutedEventArgs e)
{
_viewModel.UpdateFileNameExtension();
if (_viewModel.TrySubmit())
{
DialogResult = true;
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
=> DialogResult = false;
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly GenerateTypeDialog _dialog;
public TestAccessor(GenerateTypeDialog dialog)
=> _dialog = dialog;
public Button OKButton => _dialog.OKButton;
public Button CancelButton => _dialog.CancelButton;
public ComboBox AccessListComboBox => _dialog.accessListComboBox;
public ComboBox KindListComboBox => _dialog.kindListComboBox;
public TextBox TypeNameTextBox => _dialog.TypeNameTextBox;
public ComboBox ProjectListComboBox => _dialog.projectListComboBox;
public RadioButton AddToExistingFileRadioButton => _dialog.addToExistingFileRadioButton;
public ComboBox AddToExistingFileComboBox => _dialog.AddToExistingFileComboBox;
public RadioButton CreateNewFileRadioButton => _dialog.createNewFileRadioButton;
public ComboBox CreateNewFileComboBox => _dialog.CreateNewFileComboBox;
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Workspaces/Core/Portable/ReassignedVariable/AbstractReassignedVariableService.cs | // 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.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ReassignedVariable
{
internal abstract class AbstractReassignedVariableService<
TParameterSyntax,
TVariableSyntax,
TSingleVariableDesignationSyntax,
TIdentifierNameSyntax>
: IReassignedVariableService
where TParameterSyntax : SyntaxNode
where TVariableSyntax : SyntaxNode
where TSingleVariableDesignationSyntax : SyntaxNode
where TIdentifierNameSyntax : SyntaxNode
{
protected abstract SyntaxNode GetParentScope(SyntaxNode localDeclaration);
protected abstract SyntaxNode GetMemberBlock(SyntaxNode methodOrPropertyDeclaration);
protected abstract bool HasInitializer(SyntaxNode variable);
protected abstract SyntaxToken GetIdentifierOfVariable(TVariableSyntax variable);
protected abstract SyntaxToken GetIdentifierOfSingleVariableDesignation(TSingleVariableDesignationSyntax variable);
public async Task<ImmutableArray<TextSpan>> GetLocationsAsync(
Document document, TextSpan span, CancellationToken cancellationToken)
{
var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>();
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
using var _1 = PooledDictionary<ISymbol, bool>.GetInstance(out var symbolToIsReassigned);
using var _2 = ArrayBuilder<TextSpan>.GetInstance(out var result);
using var _3 = ArrayBuilder<SyntaxNode>.GetInstance(out var stack);
// Walk through all the nodes in the provided span. Directly analyze local or parameter declaration. And
// also analyze any identifiers which might be reference to locals or parameters. Note that we might hit
// locals/parameters without any references in the span, or references that don't have the declarations in
// the span
stack.Add(root.FindNode(span));
// Use a stack so we don't blow out the stack with recursion.
while (stack.Count > 0)
{
var current = stack.Last();
stack.RemoveLast();
if (current.Span.IntersectsWith(span))
{
ProcessNode(current);
foreach (var child in current.ChildNodesAndTokens())
{
if (child.IsNode)
stack.Add(child.AsNode()!);
}
}
}
result.RemoveDuplicates();
return result.ToImmutable();
void ProcessNode(SyntaxNode node)
{
switch (node)
{
case TIdentifierNameSyntax identifier:
ProcessIdentifier(identifier);
break;
case TParameterSyntax parameter:
ProcessParameter(parameter);
break;
case TVariableSyntax variable:
ProcessVariable(variable);
break;
case TSingleVariableDesignationSyntax designation:
ProcessSingleVariableDesignation(designation);
break;
}
}
void ProcessIdentifier(TIdentifierNameSyntax identifier)
{
// Don't bother even looking at identifiers that aren't standalone (i.e. they're not on the left of some
// expression). These could not refer to locals or fields.
if (syntaxFacts.GetStandaloneExpression(identifier) != identifier)
return;
var symbol = semanticModel.GetSymbolInfo(identifier, cancellationToken).Symbol;
if (IsSymbolReassigned(symbol))
result.Add(identifier.Span);
}
void ProcessParameter(TParameterSyntax parameterSyntax)
{
var parameter = semanticModel.GetDeclaredSymbol(parameterSyntax, cancellationToken) as IParameterSymbol;
if (IsSymbolReassigned(parameter))
result.Add(syntaxFacts.GetIdentifierOfParameter(parameterSyntax).Span);
}
void ProcessVariable(TVariableSyntax variable)
{
var local = semanticModel.GetDeclaredSymbol(variable, cancellationToken) as ILocalSymbol;
if (IsSymbolReassigned(local))
result.Add(GetIdentifierOfVariable(variable).Span);
}
void ProcessSingleVariableDesignation(TSingleVariableDesignationSyntax designation)
{
var local = semanticModel.GetDeclaredSymbol(designation, cancellationToken) as ILocalSymbol;
if (IsSymbolReassigned(local))
result.Add(GetIdentifierOfSingleVariableDesignation(designation).Span);
}
bool IsSymbolReassigned([NotNullWhen(true)] ISymbol? symbol)
{
// Note: we don't need to test range variables, as they are never reassignable.
if (symbol is not IParameterSymbol and not ILocalSymbol)
return false;
if (!symbolToIsReassigned.TryGetValue(symbol, out var reassignedResult))
{
reassignedResult = symbol is IParameterSymbol parameter
? ComputeParameterIsAssigned(parameter)
: ComputeLocalIsAssigned((ILocalSymbol)symbol);
symbolToIsReassigned[symbol] = reassignedResult;
}
return reassignedResult;
}
bool ComputeParameterIsAssigned(IParameterSymbol parameter)
{
if (!TryGetParameterLocation(parameter, out var parameterLocation))
return false;
var methodOrProperty = parameter.ContainingSymbol;
// If we're on an accessor parameter. Map up to the matching parameter for the property/indexer.
if (methodOrProperty is IMethodSymbol { MethodKind: MethodKind.PropertyGet or MethodKind.PropertySet } method)
methodOrProperty = method.AssociatedSymbol as IPropertySymbol;
if (methodOrProperty is not IMethodSymbol and not IPropertySymbol)
return false;
if (methodOrProperty.DeclaringSyntaxReferences.Length == 0)
return false;
// Be resilient to cases where the parameter might have multiple locations. This
// should not normally happen, but we want to be resilient in case it occurs in
// error scenarios.
var methodOrPropertyDeclaration = methodOrProperty.DeclaringSyntaxReferences.First().GetSyntax(cancellationToken);
if (methodOrPropertyDeclaration.SyntaxTree != semanticModel.SyntaxTree)
return false;
// All parameters (except for 'out' parameters), come in definitely assigned.
return AnalyzePotentialMatches(
parameter,
parameterLocation,
symbolIsDefinitelyAssigned: parameter.RefKind != RefKind.Out,
GetMemberBlock(methodOrPropertyDeclaration));
}
bool TryGetParameterLocation(IParameterSymbol parameter, out TextSpan location)
{
// Be resilient to cases where the parameter might have multiple locations. This
// should not normally happen, but we want to be resilient in case it occurs in
// error scenarios.
if (parameter.Locations.Length > 0)
{
var parameterLocation = parameter.Locations[0];
if (parameterLocation.SourceTree == semanticModel.SyntaxTree)
{
location = parameterLocation.SourceSpan;
return true;
}
}
else if (parameter.ContainingSymbol.Name == WellKnownMemberNames.TopLevelStatementsEntryPointMethodName)
{
// If this is a parameter of the top-level-main function, then the entire span of the compilation
// unit is what we need to examine.
location = default;
return true;
}
location = default;
return false;
}
bool ComputeLocalIsAssigned(ILocalSymbol local)
{
if (local.DeclaringSyntaxReferences.Length == 0)
return false;
var localDeclaration = local.DeclaringSyntaxReferences.First().GetSyntax(cancellationToken);
if (localDeclaration.SyntaxTree != semanticModel.SyntaxTree)
{
Contract.Fail("Local did not come from same file that we were analyzing?");
return false;
}
// A local is definitely assigned during analysis if it had an initializer.
return AnalyzePotentialMatches(
local,
localDeclaration.Span,
symbolIsDefinitelyAssigned: HasInitializer(localDeclaration),
GetParentScope(localDeclaration));
}
bool AnalyzePotentialMatches(
ISymbol localOrParameter,
TextSpan localOrParameterDeclarationSpan,
bool symbolIsDefinitelyAssigned,
SyntaxNode parentScope)
{
// Now, walk the scope, looking for all usages of the local. See if any are a reassignment.
using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var stack);
stack.Push(parentScope);
while (stack.Count != 0)
{
var current = stack.Last();
stack.RemoveLast();
foreach (var child in current.ChildNodesAndTokens())
{
if (child.IsNode)
stack.Add(child.AsNode()!);
}
// Ignore any nodes before the decl.
if (current.SpanStart <= localOrParameterDeclarationSpan.Start)
continue;
// Only examine identifiers.
if (current is not TIdentifierNameSyntax id)
continue;
// Ignore identifiers that don't match the local name.
var idToken = syntaxFacts.GetIdentifierOfSimpleName(id);
if (!syntaxFacts.StringComparer.Equals(idToken.ValueText, localOrParameter.Name))
continue;
// Ignore identifiers that bind to another symbol.
var symbol = semanticModel.GetSymbolInfo(id, cancellationToken).Symbol;
if (!AreEquivalent(localOrParameter, symbol))
continue;
// Ok, we have a reference to the local. See if it was assigned on entry. If not, we don't care
// about this reference. As an assignment here doesn't mean it was reassigned.
//
// If we can statically tell it was definitely assigned, skip the more expensive dataflow check.
if (!symbolIsDefinitelyAssigned)
{
var dataFlow = semanticModel.AnalyzeDataFlow(id);
if (!DefinitelyAssignedOnEntry(dataFlow, localOrParameter))
continue;
}
// This was a variable that was already assigned prior to this location. See if this location is
// considered a write.
if (semanticFacts.IsWrittenTo(semanticModel, id, cancellationToken))
return true;
}
return false;
}
bool AreEquivalent(ISymbol localOrParameter, ISymbol? symbol)
{
if (symbol == null)
return false;
if (localOrParameter.Equals(symbol))
return true;
if (localOrParameter.Kind != symbol.Kind)
return false;
// Special case for property parameters. When we bind to references, we'll bind to the parameters on
// the accessor methods. We need to map these back to the property parameter to see if we have a hit.
if (localOrParameter is IParameterSymbol { ContainingSymbol: IPropertySymbol property } parameter)
{
var getParameter = property.GetMethod?.Parameters[parameter.Ordinal];
var setParameter = property.SetMethod?.Parameters[parameter.Ordinal];
return Equals(getParameter, symbol) || Equals(setParameter, symbol);
}
return false;
}
bool DefinitelyAssignedOnEntry(DataFlowAnalysis? analysis, ISymbol? localOrParameter)
{
if (analysis == null)
return false;
if (localOrParameter == null)
return false;
if (analysis.DefinitelyAssignedOnEntry.Contains(localOrParameter))
return true;
// Special case for property parameters. When we bind to references, we'll bind to the parameters on
// the accessor methods. We need to map these back to the property parameter to see if we have a hit.
if (localOrParameter is IParameterSymbol { ContainingSymbol: IPropertySymbol property } parameter)
{
var getParameter = property.GetMethod?.Parameters[parameter.Ordinal];
var setParameter = property.SetMethod?.Parameters[parameter.Ordinal];
return DefinitelyAssignedOnEntry(analysis, getParameter) ||
DefinitelyAssignedOnEntry(analysis, setParameter);
}
return false;
}
}
}
}
| // 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.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ReassignedVariable
{
internal abstract class AbstractReassignedVariableService<
TParameterSyntax,
TVariableSyntax,
TSingleVariableDesignationSyntax,
TIdentifierNameSyntax>
: IReassignedVariableService
where TParameterSyntax : SyntaxNode
where TVariableSyntax : SyntaxNode
where TSingleVariableDesignationSyntax : SyntaxNode
where TIdentifierNameSyntax : SyntaxNode
{
protected abstract SyntaxNode GetParentScope(SyntaxNode localDeclaration);
protected abstract SyntaxNode GetMemberBlock(SyntaxNode methodOrPropertyDeclaration);
protected abstract bool HasInitializer(SyntaxNode variable);
protected abstract SyntaxToken GetIdentifierOfVariable(TVariableSyntax variable);
protected abstract SyntaxToken GetIdentifierOfSingleVariableDesignation(TSingleVariableDesignationSyntax variable);
public async Task<ImmutableArray<TextSpan>> GetLocationsAsync(
Document document, TextSpan span, CancellationToken cancellationToken)
{
var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>();
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
using var _1 = PooledDictionary<ISymbol, bool>.GetInstance(out var symbolToIsReassigned);
using var _2 = ArrayBuilder<TextSpan>.GetInstance(out var result);
using var _3 = ArrayBuilder<SyntaxNode>.GetInstance(out var stack);
// Walk through all the nodes in the provided span. Directly analyze local or parameter declaration. And
// also analyze any identifiers which might be reference to locals or parameters. Note that we might hit
// locals/parameters without any references in the span, or references that don't have the declarations in
// the span
stack.Add(root.FindNode(span));
// Use a stack so we don't blow out the stack with recursion.
while (stack.Count > 0)
{
var current = stack.Last();
stack.RemoveLast();
if (current.Span.IntersectsWith(span))
{
ProcessNode(current);
foreach (var child in current.ChildNodesAndTokens())
{
if (child.IsNode)
stack.Add(child.AsNode()!);
}
}
}
result.RemoveDuplicates();
return result.ToImmutable();
void ProcessNode(SyntaxNode node)
{
switch (node)
{
case TIdentifierNameSyntax identifier:
ProcessIdentifier(identifier);
break;
case TParameterSyntax parameter:
ProcessParameter(parameter);
break;
case TVariableSyntax variable:
ProcessVariable(variable);
break;
case TSingleVariableDesignationSyntax designation:
ProcessSingleVariableDesignation(designation);
break;
}
}
void ProcessIdentifier(TIdentifierNameSyntax identifier)
{
// Don't bother even looking at identifiers that aren't standalone (i.e. they're not on the left of some
// expression). These could not refer to locals or fields.
if (syntaxFacts.GetStandaloneExpression(identifier) != identifier)
return;
var symbol = semanticModel.GetSymbolInfo(identifier, cancellationToken).Symbol;
if (IsSymbolReassigned(symbol))
result.Add(identifier.Span);
}
void ProcessParameter(TParameterSyntax parameterSyntax)
{
var parameter = semanticModel.GetDeclaredSymbol(parameterSyntax, cancellationToken) as IParameterSymbol;
if (IsSymbolReassigned(parameter))
result.Add(syntaxFacts.GetIdentifierOfParameter(parameterSyntax).Span);
}
void ProcessVariable(TVariableSyntax variable)
{
var local = semanticModel.GetDeclaredSymbol(variable, cancellationToken) as ILocalSymbol;
if (IsSymbolReassigned(local))
result.Add(GetIdentifierOfVariable(variable).Span);
}
void ProcessSingleVariableDesignation(TSingleVariableDesignationSyntax designation)
{
var local = semanticModel.GetDeclaredSymbol(designation, cancellationToken) as ILocalSymbol;
if (IsSymbolReassigned(local))
result.Add(GetIdentifierOfSingleVariableDesignation(designation).Span);
}
bool IsSymbolReassigned([NotNullWhen(true)] ISymbol? symbol)
{
// Note: we don't need to test range variables, as they are never reassignable.
if (symbol is not IParameterSymbol and not ILocalSymbol)
return false;
if (!symbolToIsReassigned.TryGetValue(symbol, out var reassignedResult))
{
reassignedResult = symbol is IParameterSymbol parameter
? ComputeParameterIsAssigned(parameter)
: ComputeLocalIsAssigned((ILocalSymbol)symbol);
symbolToIsReassigned[symbol] = reassignedResult;
}
return reassignedResult;
}
bool ComputeParameterIsAssigned(IParameterSymbol parameter)
{
if (!TryGetParameterLocation(parameter, out var parameterLocation))
return false;
var methodOrProperty = parameter.ContainingSymbol;
// If we're on an accessor parameter. Map up to the matching parameter for the property/indexer.
if (methodOrProperty is IMethodSymbol { MethodKind: MethodKind.PropertyGet or MethodKind.PropertySet } method)
methodOrProperty = method.AssociatedSymbol as IPropertySymbol;
if (methodOrProperty is not IMethodSymbol and not IPropertySymbol)
return false;
if (methodOrProperty.DeclaringSyntaxReferences.Length == 0)
return false;
// Be resilient to cases where the parameter might have multiple locations. This
// should not normally happen, but we want to be resilient in case it occurs in
// error scenarios.
var methodOrPropertyDeclaration = methodOrProperty.DeclaringSyntaxReferences.First().GetSyntax(cancellationToken);
if (methodOrPropertyDeclaration.SyntaxTree != semanticModel.SyntaxTree)
return false;
// All parameters (except for 'out' parameters), come in definitely assigned.
return AnalyzePotentialMatches(
parameter,
parameterLocation,
symbolIsDefinitelyAssigned: parameter.RefKind != RefKind.Out,
GetMemberBlock(methodOrPropertyDeclaration));
}
bool TryGetParameterLocation(IParameterSymbol parameter, out TextSpan location)
{
// Be resilient to cases where the parameter might have multiple locations. This
// should not normally happen, but we want to be resilient in case it occurs in
// error scenarios.
if (parameter.Locations.Length > 0)
{
var parameterLocation = parameter.Locations[0];
if (parameterLocation.SourceTree == semanticModel.SyntaxTree)
{
location = parameterLocation.SourceSpan;
return true;
}
}
else if (parameter.ContainingSymbol.Name == WellKnownMemberNames.TopLevelStatementsEntryPointMethodName)
{
// If this is a parameter of the top-level-main function, then the entire span of the compilation
// unit is what we need to examine.
location = default;
return true;
}
location = default;
return false;
}
bool ComputeLocalIsAssigned(ILocalSymbol local)
{
if (local.DeclaringSyntaxReferences.Length == 0)
return false;
var localDeclaration = local.DeclaringSyntaxReferences.First().GetSyntax(cancellationToken);
if (localDeclaration.SyntaxTree != semanticModel.SyntaxTree)
{
Contract.Fail("Local did not come from same file that we were analyzing?");
return false;
}
// A local is definitely assigned during analysis if it had an initializer.
return AnalyzePotentialMatches(
local,
localDeclaration.Span,
symbolIsDefinitelyAssigned: HasInitializer(localDeclaration),
GetParentScope(localDeclaration));
}
bool AnalyzePotentialMatches(
ISymbol localOrParameter,
TextSpan localOrParameterDeclarationSpan,
bool symbolIsDefinitelyAssigned,
SyntaxNode parentScope)
{
// Now, walk the scope, looking for all usages of the local. See if any are a reassignment.
using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var stack);
stack.Push(parentScope);
while (stack.Count != 0)
{
var current = stack.Last();
stack.RemoveLast();
foreach (var child in current.ChildNodesAndTokens())
{
if (child.IsNode)
stack.Add(child.AsNode()!);
}
// Ignore any nodes before the decl.
if (current.SpanStart <= localOrParameterDeclarationSpan.Start)
continue;
// Only examine identifiers.
if (current is not TIdentifierNameSyntax id)
continue;
// Ignore identifiers that don't match the local name.
var idToken = syntaxFacts.GetIdentifierOfSimpleName(id);
if (!syntaxFacts.StringComparer.Equals(idToken.ValueText, localOrParameter.Name))
continue;
// Ignore identifiers that bind to another symbol.
var symbol = semanticModel.GetSymbolInfo(id, cancellationToken).Symbol;
if (!AreEquivalent(localOrParameter, symbol))
continue;
// Ok, we have a reference to the local. See if it was assigned on entry. If not, we don't care
// about this reference. As an assignment here doesn't mean it was reassigned.
//
// If we can statically tell it was definitely assigned, skip the more expensive dataflow check.
if (!symbolIsDefinitelyAssigned)
{
var dataFlow = semanticModel.AnalyzeDataFlow(id);
if (!DefinitelyAssignedOnEntry(dataFlow, localOrParameter))
continue;
}
// This was a variable that was already assigned prior to this location. See if this location is
// considered a write.
if (semanticFacts.IsWrittenTo(semanticModel, id, cancellationToken))
return true;
}
return false;
}
bool AreEquivalent(ISymbol localOrParameter, ISymbol? symbol)
{
if (symbol == null)
return false;
if (localOrParameter.Equals(symbol))
return true;
if (localOrParameter.Kind != symbol.Kind)
return false;
// Special case for property parameters. When we bind to references, we'll bind to the parameters on
// the accessor methods. We need to map these back to the property parameter to see if we have a hit.
if (localOrParameter is IParameterSymbol { ContainingSymbol: IPropertySymbol property } parameter)
{
var getParameter = property.GetMethod?.Parameters[parameter.Ordinal];
var setParameter = property.SetMethod?.Parameters[parameter.Ordinal];
return Equals(getParameter, symbol) || Equals(setParameter, symbol);
}
return false;
}
bool DefinitelyAssignedOnEntry(DataFlowAnalysis? analysis, ISymbol? localOrParameter)
{
if (analysis == null)
return false;
if (localOrParameter == null)
return false;
if (analysis.DefinitelyAssignedOnEntry.Contains(localOrParameter))
return true;
// Special case for property parameters. When we bind to references, we'll bind to the parameters on
// the accessor methods. We need to map these back to the property parameter to see if we have a hit.
if (localOrParameter is IParameterSymbol { ContainingSymbol: IPropertySymbol property } parameter)
{
var getParameter = property.GetMethod?.Parameters[parameter.Ordinal];
var setParameter = property.SetMethod?.Parameters[parameter.Ordinal];
return DefinitelyAssignedOnEntry(analysis, getParameter) ||
DefinitelyAssignedOnEntry(analysis, setParameter);
}
return false;
}
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/VisualStudio/Core/Def/EditorConfigSettings/Whitespace/ViewModel/WhitespaceViewModel.SettingsEntriesSnapshot.cs | // 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.Immutable;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.ViewModel
{
internal partial class WhitespaceViewModel
{
internal sealed class SettingsEntriesSnapshot : SettingsEntriesSnapshotBase<WhitespaceSetting>
{
public SettingsEntriesSnapshot(ImmutableArray<WhitespaceSetting> data, int currentVersionNumber) : base(data, currentVersionNumber) { }
protected override bool TryGetValue(WhitespaceSetting result, string keyName, out object? content)
{
content = keyName switch
{
ColumnDefinitions.Whitespace.Description => result.Description,
ColumnDefinitions.Whitespace.Category => result.Category,
ColumnDefinitions.Whitespace.Value => result,
ColumnDefinitions.Whitespace.Location => GetLocationString(result.Location),
_ => null,
};
return content is not null;
}
private string? GetLocationString(SettingLocation location)
{
return location.LocationKind switch
{
LocationKind.EditorConfig or LocationKind.GlobalConfig => location.Path,
_ => ServicesVSResources.Visual_Studio_Settings
};
}
}
}
}
| // 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.Immutable;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.ViewModel
{
internal partial class WhitespaceViewModel
{
internal sealed class SettingsEntriesSnapshot : SettingsEntriesSnapshotBase<WhitespaceSetting>
{
public SettingsEntriesSnapshot(ImmutableArray<WhitespaceSetting> data, int currentVersionNumber) : base(data, currentVersionNumber) { }
protected override bool TryGetValue(WhitespaceSetting result, string keyName, out object? content)
{
content = keyName switch
{
ColumnDefinitions.Whitespace.Description => result.Description,
ColumnDefinitions.Whitespace.Category => result.Category,
ColumnDefinitions.Whitespace.Value => result,
ColumnDefinitions.Whitespace.Location => GetLocationString(result.Location),
_ => null,
};
return content is not null;
}
private string? GetLocationString(SettingLocation location)
{
return location.LocationKind switch
{
LocationKind.EditorConfig or LocationKind.GlobalConfig => location.Path,
_ => ServicesVSResources.Visual_Studio_Settings
};
}
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/VisualStudio/Core/Test/Snippets/SnippetTestState.vb | ' 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.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Editor.Implementation.Formatting
Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp
Imports Microsoft.CodeAnalysis.Editor.Shared.Options
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.VisualStudio.Editor
Imports Microsoft.VisualStudio.Language.Intellisense
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
Imports Microsoft.VisualStudio.Shell
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Editor.Commanding
Imports Microsoft.VisualStudio.TextManager.Interop
Imports Moq
Imports MSXML
Imports Roslyn.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Snippets
Friend NotInheritable Class SnippetTestState
Inherits TestState
Private Sub New(workspaceElement As XElement, languageName As String, startActiveSession As Boolean, extraParts As IEnumerable(Of Type), excludedTypes As IEnumerable(Of Type), Optional workspaceKind As String = Nothing)
' Remove the default completion presenters to prevent them from conflicting with the test one
' that we are adding.
MyBase.New(workspaceElement,
extraExportedTypes:={GetType(TestSignatureHelpPresenter), GetType(IntelliSenseTestState), GetType(MockCompletionPresenterProvider), GetType(StubVsEditorAdaptersFactoryService)}.Concat(If(extraParts, {})).ToList(),
workspaceKind:=workspaceKind,
excludedTypes:={GetType(IIntelliSensePresenter(Of ISignatureHelpPresenterSession, ISignatureHelpSession)), GetType(FormatCommandHandler)}.Concat(If(excludedTypes, {})).ToList(),
includeFormatCommandHandler:=False)
Workspace.TryApplyChanges(Workspace.CurrentSolution.WithOptions(Workspace.Options _
.WithChangedOption(InternalFeatureOnOffOptions.Snippets, True)))
Dim mockSVsServiceProvider = New Mock(Of SVsServiceProvider)(MockBehavior.Strict)
mockSVsServiceProvider.Setup(Function(s) s.GetService(GetType(SVsTextManager))).Returns(Nothing)
SnippetCommandHandler = If(languageName = LanguageNames.CSharp,
DirectCast(New CSharp.Snippets.SnippetCommandHandler(
Workspace.ExportProvider.GetExportedValue(Of IThreadingContext),
Workspace.ExportProvider.GetExportedValue(Of SignatureHelpControllerProvider)(),
Workspace.ExportProvider.GetExportedValue(Of IEditorCommandHandlerServiceFactory)(),
Workspace.ExportProvider.GetExportedValue(Of IVsEditorAdaptersFactoryService)(),
mockSVsServiceProvider.Object,
Workspace.ExportProvider.GetExports(Of ArgumentProvider, OrderableLanguageMetadata)()), AbstractSnippetCommandHandler),
New VisualBasic.Snippets.SnippetCommandHandler(
Workspace.ExportProvider.GetExportedValue(Of IThreadingContext),
Workspace.ExportProvider.GetExportedValue(Of SignatureHelpControllerProvider)(),
Workspace.ExportProvider.GetExportedValue(Of IEditorCommandHandlerServiceFactory)(),
Workspace.ExportProvider.GetExportedValue(Of IVsEditorAdaptersFactoryService)(),
mockSVsServiceProvider.Object,
Workspace.ExportProvider.GetExports(Of ArgumentProvider, OrderableLanguageMetadata)()))
SnippetExpansionClient = New MockSnippetExpansionClient(Workspace.ExportProvider.GetExportedValue(Of IThreadingContext), startActiveSession, If(languageName Is LanguageNames.CSharp, Guids.CSharpLanguageServiceId, Guids.VisualBasicLanguageServiceId), TextView, SubjectBuffer)
TextView.Properties.AddProperty(GetType(AbstractSnippetExpansionClient), SnippetExpansionClient)
End Sub
Public ReadOnly SnippetCommandHandler As AbstractSnippetCommandHandler
Public Property SnippetExpansionClient As MockSnippetExpansionClient
Public Shared Function CreateTestState(markup As String, languageName As String, Optional startActiveSession As Boolean = False, Optional extraParts As IEnumerable(Of Type) = Nothing) As SnippetTestState
extraParts = If(extraParts, Type.EmptyTypes)
Dim workspaceXml = <Workspace>
<Project Language=<%= languageName %> CommonReferences="true">
<Document><%= markup %></Document>
</Project>
</Workspace>
Return New SnippetTestState(workspaceXml, languageName, startActiveSession, extraParts, excludedTypes:=New List(Of Type) From {GetType(CommitConnectionListener)})
End Function
Public Shared Function CreateSubmissionTestState(markup As String, languageName As String, Optional startActiveSession As Boolean = False, Optional extraParts As IEnumerable(Of Type) = Nothing) As SnippetTestState
extraParts = If(extraParts, Type.EmptyTypes)
Dim workspaceXml = <Workspace>
<Submission Language=<%= languageName %> CommonReferences="true">
<%= markup %>
</Submission>
</Workspace>
Dim state = New SnippetTestState(workspaceXml, languageName, startActiveSession, extraParts, excludedTypes:=Enumerable.Empty(Of Type), WorkspaceKind.Interactive)
Dim workspace = state.Workspace
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _
.WithChangedOption(InternalFeatureOnOffOptions.Snippets, False)))
Return state
End Function
Friend Overloads Sub SendTabToCompletion()
MyBase.SendTab()
End Sub
Friend Overloads Sub SendTab()
If Not SendTab(AddressOf SnippetCommandHandler.ExecuteCommand) Then
EditorOperations.InsertText(" ")
End If
End Sub
Friend Overloads Sub SendBackSpace()
EditorOperations.Backspace()
End Sub
Friend Overloads Sub SendBackTab()
If Not SendBackTab(AddressOf SnippetCommandHandler.ExecuteCommand) Then
EditorOperations.Unindent()
End If
End Sub
Friend Overloads Sub SendReturn()
If Not SendReturn(AddressOf SnippetCommandHandler.ExecuteCommand) Then
EditorOperations.InsertNewLine()
End If
End Sub
Friend Overloads Sub SendEscape()
If Not SendEscape(AddressOf SnippetCommandHandler.ExecuteCommand) Then
EditorOperations.InsertText("EscapePassedThrough!")
End If
End Sub
Private Class MockOrderableContentTypeMetadata
Inherits OrderableContentTypeMetadata
Public Sub New(contentType As String)
MyBase.New(New Dictionary(Of String, Object) From {{"ContentTypes", New List(Of String) From {contentType}},
{"Name", String.Empty}})
End Sub
End Class
Friend Class MockSnippetExpansionClient
Inherits AbstractSnippetExpansionClient
Public Sub New(threadingContext As IThreadingContext, startActiveSession As Boolean, languageServiceGuid As Guid, textView As ITextView, subjectBuffer As ITextBuffer)
MyBase.New(threadingContext, languageServiceGuid, textView, subjectBuffer, signatureHelpControllerProvider:=Nothing, editorCommandHandlerServiceFactory:=Nothing, Nothing, ImmutableArray(Of Lazy(Of ArgumentProvider, OrderableLanguageMetadata)).Empty)
If startActiveSession Then
TryHandleTabReturnValue = True
TryHandleBackTabReturnValue = True
TryHandleEscapeReturnValue = True
TryHandleReturnReturnValue = True
End If
End Sub
Public Property TryHandleReturnCalled As Boolean
Public Property TryHandleReturnReturnValue As Boolean
Public Property TryHandleTabCalled As Boolean
Public Property TryHandleTabReturnValue As Boolean
Public Property TryHandleBackTabCalled As Boolean
Public Property TryHandleBackTabReturnValue As Boolean
Public Property TryHandleEscapeCalled As Boolean
Public Property TryHandleEscapeReturnValue As Boolean
Public Property TryInsertExpansionCalled As Boolean
Public Property TryInsertExpansionReturnValue As Boolean
Public Property InsertExpansionSpan As Span
Public Overrides Function TryHandleTab() As Boolean
TryHandleTabCalled = True
Return TryHandleTabReturnValue
End Function
Public Overrides Function TryHandleBackTab() As Boolean
TryHandleBackTabCalled = True
Return TryHandleBackTabReturnValue
End Function
Public Overrides Function TryHandleEscape() As Boolean
TryHandleEscapeCalled = True
Return TryHandleEscapeReturnValue
End Function
Public Overrides Function TryHandleReturn() As Boolean
TryHandleReturnCalled = True
Return TryHandleReturnReturnValue
End Function
Public Overrides Function TryInsertExpansion(startPosition As Integer, endPosition As Integer, cancellationToken As CancellationToken) As Boolean
TryInsertExpansionCalled = True
InsertExpansionSpan = New Span(startPosition, endPosition - startPosition)
Return TryInsertExpansionReturnValue
End Function
Public Overrides Function GetExpansionFunction(xmlFunctionNode As IXMLDOMNode, bstrFieldName As String, ByRef pFunc As IVsExpansionFunction) As Integer
Throw New NotImplementedException()
End Function
Protected Overrides Function InsertEmptyCommentAndGetEndPositionTrackingSpan() As ITrackingSpan
Throw New NotImplementedException()
End Function
Protected Overrides ReadOnly Property FallbackDefaultLiteral As String
Get
Throw New NotImplementedException()
End Get
End Property
Friend Overrides Function AddImports(document As Document, options As OptionSet, position As Integer, snippetNode As XElement, allowInHiddenRegions As Boolean, cancellationToken As CancellationToken) As Document
Return document
End Function
End Class
End Class
End Namespace
| ' 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.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Editor.Implementation.Formatting
Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp
Imports Microsoft.CodeAnalysis.Editor.Shared.Options
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.VisualStudio.Editor
Imports Microsoft.VisualStudio.Language.Intellisense
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
Imports Microsoft.VisualStudio.Shell
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Editor.Commanding
Imports Microsoft.VisualStudio.TextManager.Interop
Imports Moq
Imports MSXML
Imports Roslyn.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Snippets
Friend NotInheritable Class SnippetTestState
Inherits TestState
Private Sub New(workspaceElement As XElement, languageName As String, startActiveSession As Boolean, extraParts As IEnumerable(Of Type), excludedTypes As IEnumerable(Of Type), Optional workspaceKind As String = Nothing)
' Remove the default completion presenters to prevent them from conflicting with the test one
' that we are adding.
MyBase.New(workspaceElement,
extraExportedTypes:={GetType(TestSignatureHelpPresenter), GetType(IntelliSenseTestState), GetType(MockCompletionPresenterProvider), GetType(StubVsEditorAdaptersFactoryService)}.Concat(If(extraParts, {})).ToList(),
workspaceKind:=workspaceKind,
excludedTypes:={GetType(IIntelliSensePresenter(Of ISignatureHelpPresenterSession, ISignatureHelpSession)), GetType(FormatCommandHandler)}.Concat(If(excludedTypes, {})).ToList(),
includeFormatCommandHandler:=False)
Workspace.TryApplyChanges(Workspace.CurrentSolution.WithOptions(Workspace.Options _
.WithChangedOption(InternalFeatureOnOffOptions.Snippets, True)))
Dim mockSVsServiceProvider = New Mock(Of SVsServiceProvider)(MockBehavior.Strict)
mockSVsServiceProvider.Setup(Function(s) s.GetService(GetType(SVsTextManager))).Returns(Nothing)
SnippetCommandHandler = If(languageName = LanguageNames.CSharp,
DirectCast(New CSharp.Snippets.SnippetCommandHandler(
Workspace.ExportProvider.GetExportedValue(Of IThreadingContext),
Workspace.ExportProvider.GetExportedValue(Of SignatureHelpControllerProvider)(),
Workspace.ExportProvider.GetExportedValue(Of IEditorCommandHandlerServiceFactory)(),
Workspace.ExportProvider.GetExportedValue(Of IVsEditorAdaptersFactoryService)(),
mockSVsServiceProvider.Object,
Workspace.ExportProvider.GetExports(Of ArgumentProvider, OrderableLanguageMetadata)()), AbstractSnippetCommandHandler),
New VisualBasic.Snippets.SnippetCommandHandler(
Workspace.ExportProvider.GetExportedValue(Of IThreadingContext),
Workspace.ExportProvider.GetExportedValue(Of SignatureHelpControllerProvider)(),
Workspace.ExportProvider.GetExportedValue(Of IEditorCommandHandlerServiceFactory)(),
Workspace.ExportProvider.GetExportedValue(Of IVsEditorAdaptersFactoryService)(),
mockSVsServiceProvider.Object,
Workspace.ExportProvider.GetExports(Of ArgumentProvider, OrderableLanguageMetadata)()))
SnippetExpansionClient = New MockSnippetExpansionClient(Workspace.ExportProvider.GetExportedValue(Of IThreadingContext), startActiveSession, If(languageName Is LanguageNames.CSharp, Guids.CSharpLanguageServiceId, Guids.VisualBasicLanguageServiceId), TextView, SubjectBuffer)
TextView.Properties.AddProperty(GetType(AbstractSnippetExpansionClient), SnippetExpansionClient)
End Sub
Public ReadOnly SnippetCommandHandler As AbstractSnippetCommandHandler
Public Property SnippetExpansionClient As MockSnippetExpansionClient
Public Shared Function CreateTestState(markup As String, languageName As String, Optional startActiveSession As Boolean = False, Optional extraParts As IEnumerable(Of Type) = Nothing) As SnippetTestState
extraParts = If(extraParts, Type.EmptyTypes)
Dim workspaceXml = <Workspace>
<Project Language=<%= languageName %> CommonReferences="true">
<Document><%= markup %></Document>
</Project>
</Workspace>
Return New SnippetTestState(workspaceXml, languageName, startActiveSession, extraParts, excludedTypes:=New List(Of Type) From {GetType(CommitConnectionListener)})
End Function
Public Shared Function CreateSubmissionTestState(markup As String, languageName As String, Optional startActiveSession As Boolean = False, Optional extraParts As IEnumerable(Of Type) = Nothing) As SnippetTestState
extraParts = If(extraParts, Type.EmptyTypes)
Dim workspaceXml = <Workspace>
<Submission Language=<%= languageName %> CommonReferences="true">
<%= markup %>
</Submission>
</Workspace>
Dim state = New SnippetTestState(workspaceXml, languageName, startActiveSession, extraParts, excludedTypes:=Enumerable.Empty(Of Type), WorkspaceKind.Interactive)
Dim workspace = state.Workspace
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _
.WithChangedOption(InternalFeatureOnOffOptions.Snippets, False)))
Return state
End Function
Friend Overloads Sub SendTabToCompletion()
MyBase.SendTab()
End Sub
Friend Overloads Sub SendTab()
If Not SendTab(AddressOf SnippetCommandHandler.ExecuteCommand) Then
EditorOperations.InsertText(" ")
End If
End Sub
Friend Overloads Sub SendBackSpace()
EditorOperations.Backspace()
End Sub
Friend Overloads Sub SendBackTab()
If Not SendBackTab(AddressOf SnippetCommandHandler.ExecuteCommand) Then
EditorOperations.Unindent()
End If
End Sub
Friend Overloads Sub SendReturn()
If Not SendReturn(AddressOf SnippetCommandHandler.ExecuteCommand) Then
EditorOperations.InsertNewLine()
End If
End Sub
Friend Overloads Sub SendEscape()
If Not SendEscape(AddressOf SnippetCommandHandler.ExecuteCommand) Then
EditorOperations.InsertText("EscapePassedThrough!")
End If
End Sub
Private Class MockOrderableContentTypeMetadata
Inherits OrderableContentTypeMetadata
Public Sub New(contentType As String)
MyBase.New(New Dictionary(Of String, Object) From {{"ContentTypes", New List(Of String) From {contentType}},
{"Name", String.Empty}})
End Sub
End Class
Friend Class MockSnippetExpansionClient
Inherits AbstractSnippetExpansionClient
Public Sub New(threadingContext As IThreadingContext, startActiveSession As Boolean, languageServiceGuid As Guid, textView As ITextView, subjectBuffer As ITextBuffer)
MyBase.New(threadingContext, languageServiceGuid, textView, subjectBuffer, signatureHelpControllerProvider:=Nothing, editorCommandHandlerServiceFactory:=Nothing, Nothing, ImmutableArray(Of Lazy(Of ArgumentProvider, OrderableLanguageMetadata)).Empty)
If startActiveSession Then
TryHandleTabReturnValue = True
TryHandleBackTabReturnValue = True
TryHandleEscapeReturnValue = True
TryHandleReturnReturnValue = True
End If
End Sub
Public Property TryHandleReturnCalled As Boolean
Public Property TryHandleReturnReturnValue As Boolean
Public Property TryHandleTabCalled As Boolean
Public Property TryHandleTabReturnValue As Boolean
Public Property TryHandleBackTabCalled As Boolean
Public Property TryHandleBackTabReturnValue As Boolean
Public Property TryHandleEscapeCalled As Boolean
Public Property TryHandleEscapeReturnValue As Boolean
Public Property TryInsertExpansionCalled As Boolean
Public Property TryInsertExpansionReturnValue As Boolean
Public Property InsertExpansionSpan As Span
Public Overrides Function TryHandleTab() As Boolean
TryHandleTabCalled = True
Return TryHandleTabReturnValue
End Function
Public Overrides Function TryHandleBackTab() As Boolean
TryHandleBackTabCalled = True
Return TryHandleBackTabReturnValue
End Function
Public Overrides Function TryHandleEscape() As Boolean
TryHandleEscapeCalled = True
Return TryHandleEscapeReturnValue
End Function
Public Overrides Function TryHandleReturn() As Boolean
TryHandleReturnCalled = True
Return TryHandleReturnReturnValue
End Function
Public Overrides Function TryInsertExpansion(startPosition As Integer, endPosition As Integer, cancellationToken As CancellationToken) As Boolean
TryInsertExpansionCalled = True
InsertExpansionSpan = New Span(startPosition, endPosition - startPosition)
Return TryInsertExpansionReturnValue
End Function
Public Overrides Function GetExpansionFunction(xmlFunctionNode As IXMLDOMNode, bstrFieldName As String, ByRef pFunc As IVsExpansionFunction) As Integer
Throw New NotImplementedException()
End Function
Protected Overrides Function InsertEmptyCommentAndGetEndPositionTrackingSpan() As ITrackingSpan
Throw New NotImplementedException()
End Function
Protected Overrides ReadOnly Property FallbackDefaultLiteral As String
Get
Throw New NotImplementedException()
End Get
End Property
Friend Overrides Function AddImports(document As Document, options As OptionSet, position As Integer, snippetNode As XElement, allowInHiddenRegions As Boolean, cancellationToken As CancellationToken) As Document
Return document
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicEndConstruct.cs | // 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.
#nullable disable
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicEndConstruct : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicEndConstruct(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicEndConstruct))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)]
public void EndConstruct()
{
SetUpEditor(@"
Class Program
Sub Main()
If True Then $$
End Sub
End Class");
// Send a space to convert virtual whitespace into real whitespace
VisualStudio.Editor.SendKeys(VirtualKey.Enter, " ");
VisualStudio.Editor.Verify.TextContains(@"
Class Program
Sub Main()
If True Then
$$
End If
End Sub
End Class", assertCaretPosition: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)]
public void IntelliSenseCompletedWhile()
{
SetUpEditor(@"
Class Program
Sub Main()
$$
End Sub
End Class");
// Send a space to convert virtual whitespace into real whitespace
VisualStudio.Editor.SendKeys("While True", VirtualKey.Enter, " ");
VisualStudio.Editor.Verify.TextContains(@"
Class Program
Sub Main()
While True
$$
End While
End Sub
End Class", assertCaretPosition: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)]
public void InterfaceToClassFixup()
{
SetUpEditor(@"
Interface$$ C
End Interface");
VisualStudio.Editor.SendKeys(new KeyPress(VirtualKey.Backspace, ShiftState.Ctrl));
VisualStudio.Editor.SendKeys("Class", VirtualKey.Tab);
VisualStudio.Editor.Verify.TextContains(@"
Class C
End Class");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)]
public void CaseInsensitiveSubToFunction()
{
SetUpEditor(@"
Class C
Public Sub$$ Goo()
End Sub
End Class");
VisualStudio.Editor.SendKeys(new KeyPress(VirtualKey.Backspace, ShiftState.Ctrl));
VisualStudio.Editor.SendKeys("fu", VirtualKey.Tab);
VisualStudio.Editor.Verify.TextContains(@"
Class C
Public Function Goo()
End Function
End Class");
}
}
}
| // 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.
#nullable disable
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicEndConstruct : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicEndConstruct(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicEndConstruct))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)]
public void EndConstruct()
{
SetUpEditor(@"
Class Program
Sub Main()
If True Then $$
End Sub
End Class");
// Send a space to convert virtual whitespace into real whitespace
VisualStudio.Editor.SendKeys(VirtualKey.Enter, " ");
VisualStudio.Editor.Verify.TextContains(@"
Class Program
Sub Main()
If True Then
$$
End If
End Sub
End Class", assertCaretPosition: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)]
public void IntelliSenseCompletedWhile()
{
SetUpEditor(@"
Class Program
Sub Main()
$$
End Sub
End Class");
// Send a space to convert virtual whitespace into real whitespace
VisualStudio.Editor.SendKeys("While True", VirtualKey.Enter, " ");
VisualStudio.Editor.Verify.TextContains(@"
Class Program
Sub Main()
While True
$$
End While
End Sub
End Class", assertCaretPosition: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)]
public void InterfaceToClassFixup()
{
SetUpEditor(@"
Interface$$ C
End Interface");
VisualStudio.Editor.SendKeys(new KeyPress(VirtualKey.Backspace, ShiftState.Ctrl));
VisualStudio.Editor.SendKeys("Class", VirtualKey.Tab);
VisualStudio.Editor.Verify.TextContains(@"
Class C
End Class");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)]
public void CaseInsensitiveSubToFunction()
{
SetUpEditor(@"
Class C
Public Sub$$ Goo()
End Sub
End Class");
VisualStudio.Editor.SendKeys(new KeyPress(VirtualKey.Backspace, ShiftState.Ctrl));
VisualStudio.Editor.SendKeys("fu", VirtualKey.Tab);
VisualStudio.Editor.Verify.TextContains(@"
Class C
Public Function Goo()
End Function
End Class");
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Features/CSharp/Portable/SignatureHelp/InvocationExpressionSignatureHelpProviderBase_MethodGroup.cs | // 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.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp
{
internal partial class InvocationExpressionSignatureHelpProviderBase
{
internal virtual Task<(ImmutableArray<SignatureHelpItem> items, int? selectedItemIndex)> GetMethodGroupItemsAndSelectionAsync(
ImmutableArray<IMethodSymbol> accessibleMethods,
Document document,
InvocationExpressionSyntax invocationExpression,
SemanticModel semanticModel,
SymbolInfo currentSymbol,
CancellationToken cancellationToken)
{
return Task.FromResult(
(accessibleMethods.SelectAsArray(m => ConvertMethodGroupMethod(document, m, invocationExpression.SpanStart, semanticModel)),
TryGetSelectedIndex(accessibleMethods, currentSymbol.Symbol)));
}
private static ImmutableArray<IMethodSymbol> GetAccessibleMethods(
InvocationExpressionSyntax invocationExpression,
SemanticModel semanticModel,
ISymbol within,
IEnumerable<IMethodSymbol> methodGroup,
CancellationToken cancellationToken)
{
ITypeSymbol? throughType = null;
if (invocationExpression.Expression is MemberAccessExpressionSyntax memberAccess)
{
var throughExpression = memberAccess.Expression;
var throughSymbol = semanticModel.GetSymbolInfo(throughExpression, cancellationToken).GetAnySymbol();
// if it is via a base expression "base.", we know the "throughType" is the base class but
// we need to be able to tell between "base.M()" and "new Base().M()".
// currently, Access check methods do not differentiate between them.
// so handle "base." primary-expression here by nulling out "throughType"
if (!(throughExpression is BaseExpressionSyntax))
{
throughType = semanticModel.GetTypeInfo(throughExpression, cancellationToken).Type;
}
var includeInstance = !throughExpression.IsKind(SyntaxKind.IdentifierName) ||
semanticModel.LookupSymbols(throughExpression.SpanStart, name: throughSymbol?.Name).Any(s => !(s is INamedTypeSymbol)) ||
(!(throughSymbol is INamespaceOrTypeSymbol) && semanticModel.LookupSymbols(throughExpression.SpanStart, container: throughSymbol?.ContainingType).Any(s => !(s is INamedTypeSymbol)));
var includeStatic = throughSymbol is INamedTypeSymbol ||
(throughExpression.IsKind(SyntaxKind.IdentifierName) &&
semanticModel.LookupNamespacesAndTypes(throughExpression.SpanStart, name: throughSymbol?.Name).Any(t => Equals(t.GetSymbolType(), throughType)));
Contract.ThrowIfFalse(includeInstance || includeStatic);
methodGroup = methodGroup.Where(m => (m.IsStatic && includeStatic) || (!m.IsStatic && includeInstance));
}
else if (invocationExpression.Expression is SimpleNameSyntax &&
invocationExpression.IsInStaticContext())
{
// We always need to include local functions regardless of whether they are static.
methodGroup = methodGroup.Where(m => m.IsStatic || m is IMethodSymbol { MethodKind: MethodKind.LocalFunction });
}
var accessibleMethods = methodGroup.Where(m => m.IsAccessibleWithin(within, throughType: throughType)).ToImmutableArrayOrEmpty();
if (accessibleMethods.Length == 0)
{
return accessibleMethods;
}
var methodSet = accessibleMethods.ToSet();
return accessibleMethods.Where(m => !IsHiddenByOtherMethod(m, methodSet)).ToImmutableArrayOrEmpty();
}
private static bool IsHiddenByOtherMethod(IMethodSymbol method, ISet<IMethodSymbol> methodSet)
{
foreach (var m in methodSet)
{
if (!Equals(m, method))
{
if (IsHiddenBy(method, m))
{
return true;
}
}
}
return false;
}
private static bool IsHiddenBy(IMethodSymbol method1, IMethodSymbol method2)
{
// If they have the same parameter types and the same parameter names, then the
// constructed method is hidden by the unconstructed one.
return method2.IsMoreSpecificThan(method1) == true;
}
}
}
| // 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.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp
{
internal partial class InvocationExpressionSignatureHelpProviderBase
{
internal virtual Task<(ImmutableArray<SignatureHelpItem> items, int? selectedItemIndex)> GetMethodGroupItemsAndSelectionAsync(
ImmutableArray<IMethodSymbol> accessibleMethods,
Document document,
InvocationExpressionSyntax invocationExpression,
SemanticModel semanticModel,
SymbolInfo currentSymbol,
CancellationToken cancellationToken)
{
return Task.FromResult(
(accessibleMethods.SelectAsArray(m => ConvertMethodGroupMethod(document, m, invocationExpression.SpanStart, semanticModel)),
TryGetSelectedIndex(accessibleMethods, currentSymbol.Symbol)));
}
private static ImmutableArray<IMethodSymbol> GetAccessibleMethods(
InvocationExpressionSyntax invocationExpression,
SemanticModel semanticModel,
ISymbol within,
IEnumerable<IMethodSymbol> methodGroup,
CancellationToken cancellationToken)
{
ITypeSymbol? throughType = null;
if (invocationExpression.Expression is MemberAccessExpressionSyntax memberAccess)
{
var throughExpression = memberAccess.Expression;
var throughSymbol = semanticModel.GetSymbolInfo(throughExpression, cancellationToken).GetAnySymbol();
// if it is via a base expression "base.", we know the "throughType" is the base class but
// we need to be able to tell between "base.M()" and "new Base().M()".
// currently, Access check methods do not differentiate between them.
// so handle "base." primary-expression here by nulling out "throughType"
if (!(throughExpression is BaseExpressionSyntax))
{
throughType = semanticModel.GetTypeInfo(throughExpression, cancellationToken).Type;
}
var includeInstance = !throughExpression.IsKind(SyntaxKind.IdentifierName) ||
semanticModel.LookupSymbols(throughExpression.SpanStart, name: throughSymbol?.Name).Any(s => !(s is INamedTypeSymbol)) ||
(!(throughSymbol is INamespaceOrTypeSymbol) && semanticModel.LookupSymbols(throughExpression.SpanStart, container: throughSymbol?.ContainingType).Any(s => !(s is INamedTypeSymbol)));
var includeStatic = throughSymbol is INamedTypeSymbol ||
(throughExpression.IsKind(SyntaxKind.IdentifierName) &&
semanticModel.LookupNamespacesAndTypes(throughExpression.SpanStart, name: throughSymbol?.Name).Any(t => Equals(t.GetSymbolType(), throughType)));
Contract.ThrowIfFalse(includeInstance || includeStatic);
methodGroup = methodGroup.Where(m => (m.IsStatic && includeStatic) || (!m.IsStatic && includeInstance));
}
else if (invocationExpression.Expression is SimpleNameSyntax &&
invocationExpression.IsInStaticContext())
{
// We always need to include local functions regardless of whether they are static.
methodGroup = methodGroup.Where(m => m.IsStatic || m is IMethodSymbol { MethodKind: MethodKind.LocalFunction });
}
var accessibleMethods = methodGroup.Where(m => m.IsAccessibleWithin(within, throughType: throughType)).ToImmutableArrayOrEmpty();
if (accessibleMethods.Length == 0)
{
return accessibleMethods;
}
var methodSet = accessibleMethods.ToSet();
return accessibleMethods.Where(m => !IsHiddenByOtherMethod(m, methodSet)).ToImmutableArrayOrEmpty();
}
private static bool IsHiddenByOtherMethod(IMethodSymbol method, ISet<IMethodSymbol> methodSet)
{
foreach (var m in methodSet)
{
if (!Equals(m, method))
{
if (IsHiddenBy(method, m))
{
return true;
}
}
}
return false;
}
private static bool IsHiddenBy(IMethodSymbol method1, IMethodSymbol method2)
{
// If they have the same parameter types and the same parameter names, then the
// constructed method is hidden by the unconstructed one.
return method2.IsMoreSpecificThan(method1) == true;
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/ObjectIdLocalSymbol.cs | // 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.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class ObjectIdLocalSymbol : PlaceholderLocalSymbol
{
private readonly bool _isWritable;
internal ObjectIdLocalSymbol(MethodSymbol method, TypeSymbol type, string name, string displayName, bool isWritable) :
base(method, name, displayName, type)
{
_isWritable = isWritable;
}
internal override bool IsWritableVariable
{
get { return _isWritable; }
}
internal override BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, SyntaxNode syntax, DiagnosticBag diagnostics)
{
return RewriteLocalInternal(compilation, container, syntax, this);
}
internal static BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, SyntaxNode syntax, LocalSymbol local)
{
return RewriteLocalInternal(compilation, container, syntax, local);
}
private static BoundExpression RewriteLocalInternal(CSharpCompilation compilation, EENamedTypeSymbol container, SyntaxNode syntax, LocalSymbol local)
{
return new BoundPseudoVariable(
syntax,
local,
new ObjectIdExpressions(compilation),
local.Type);
}
private sealed class ObjectIdExpressions : PseudoVariableExpressions
{
private readonly CSharpCompilation _compilation;
internal ObjectIdExpressions(CSharpCompilation compilation)
{
_compilation = compilation;
}
internal override BoundExpression GetValue(BoundPseudoVariable variable, DiagnosticBag diagnostics)
{
var method = GetIntrinsicMethod(_compilation, ExpressionCompilerConstants.GetVariableValueMethodName);
var local = variable.LocalSymbol;
var expr = InvokeGetMethod(method, variable.Syntax, local.Name);
return ConvertToLocalType(_compilation, expr, local.Type, diagnostics);
}
internal override BoundExpression GetAddress(BoundPseudoVariable variable)
{
var method = GetIntrinsicMethod(_compilation, ExpressionCompilerConstants.GetVariableAddressMethodName);
// Currently the MetadataDecoder does not support byref return types
// so the return type of GetVariableAddress(Of T)(name As String)
// is an error type. Since the method is only used for emit, an
// updated placeholder method is used instead.
// TODO: refs are available
// Debug.Assert(method.ReturnType.TypeKind == TypeKind.Error); // If byref return types are supported in the future, use method as is.
method = new PlaceholderMethodSymbol(
method.ContainingType,
method.Name,
m => method.TypeParameters.SelectAsArray(t => (TypeParameterSymbol)new SimpleTypeParameterSymbol(m, t.Ordinal, t.Name)),
m => m.TypeParameters[0], // return type is <>T&
m => method.Parameters.SelectAsArray(p => (ParameterSymbol)SynthesizedParameterSymbol.Create(m, p.TypeWithAnnotations, p.Ordinal, p.RefKind, p.Name, p.RefCustomModifiers)));
var local = variable.LocalSymbol;
return InvokeGetMethod(method.Construct(local.Type), variable.Syntax, local.Name);
}
private static BoundExpression InvokeGetMethod(MethodSymbol method, SyntaxNode syntax, string name)
{
var argument = new BoundLiteral(
syntax,
Microsoft.CodeAnalysis.ConstantValue.Create(name),
method.Parameters[0].Type);
return BoundCall.Synthesized(
syntax,
receiverOpt: null,
method: method,
arguments: ImmutableArray.Create<BoundExpression>(argument));
}
}
}
}
| // 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.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class ObjectIdLocalSymbol : PlaceholderLocalSymbol
{
private readonly bool _isWritable;
internal ObjectIdLocalSymbol(MethodSymbol method, TypeSymbol type, string name, string displayName, bool isWritable) :
base(method, name, displayName, type)
{
_isWritable = isWritable;
}
internal override bool IsWritableVariable
{
get { return _isWritable; }
}
internal override BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, SyntaxNode syntax, DiagnosticBag diagnostics)
{
return RewriteLocalInternal(compilation, container, syntax, this);
}
internal static BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, SyntaxNode syntax, LocalSymbol local)
{
return RewriteLocalInternal(compilation, container, syntax, local);
}
private static BoundExpression RewriteLocalInternal(CSharpCompilation compilation, EENamedTypeSymbol container, SyntaxNode syntax, LocalSymbol local)
{
return new BoundPseudoVariable(
syntax,
local,
new ObjectIdExpressions(compilation),
local.Type);
}
private sealed class ObjectIdExpressions : PseudoVariableExpressions
{
private readonly CSharpCompilation _compilation;
internal ObjectIdExpressions(CSharpCompilation compilation)
{
_compilation = compilation;
}
internal override BoundExpression GetValue(BoundPseudoVariable variable, DiagnosticBag diagnostics)
{
var method = GetIntrinsicMethod(_compilation, ExpressionCompilerConstants.GetVariableValueMethodName);
var local = variable.LocalSymbol;
var expr = InvokeGetMethod(method, variable.Syntax, local.Name);
return ConvertToLocalType(_compilation, expr, local.Type, diagnostics);
}
internal override BoundExpression GetAddress(BoundPseudoVariable variable)
{
var method = GetIntrinsicMethod(_compilation, ExpressionCompilerConstants.GetVariableAddressMethodName);
// Currently the MetadataDecoder does not support byref return types
// so the return type of GetVariableAddress(Of T)(name As String)
// is an error type. Since the method is only used for emit, an
// updated placeholder method is used instead.
// TODO: refs are available
// Debug.Assert(method.ReturnType.TypeKind == TypeKind.Error); // If byref return types are supported in the future, use method as is.
method = new PlaceholderMethodSymbol(
method.ContainingType,
method.Name,
m => method.TypeParameters.SelectAsArray(t => (TypeParameterSymbol)new SimpleTypeParameterSymbol(m, t.Ordinal, t.Name)),
m => m.TypeParameters[0], // return type is <>T&
m => method.Parameters.SelectAsArray(p => (ParameterSymbol)SynthesizedParameterSymbol.Create(m, p.TypeWithAnnotations, p.Ordinal, p.RefKind, p.Name, p.RefCustomModifiers)));
var local = variable.LocalSymbol;
return InvokeGetMethod(method.Construct(local.Type), variable.Syntax, local.Name);
}
private static BoundExpression InvokeGetMethod(MethodSymbol method, SyntaxNode syntax, string name)
{
var argument = new BoundLiteral(
syntax,
Microsoft.CodeAnalysis.ConstantValue.Create(name),
method.Parameters[0].Type);
return BoundCall.Synthesized(
syntax,
receiverOpt: null,
method: method,
arguments: ImmutableArray.Create<BoundExpression>(argument));
}
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/EditorFeatures/CSharpTest/ChangeSignature/ChangeSignature_Delegates.cs | // 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.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature
{
public partial class ChangeSignatureTests : AbstractChangeSignatureTests
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new ChangeSignatureCodeRefactoringProvider();
protected internal override string GetLanguage()
=> LanguageNames.CSharp;
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_ImplicitInvokeCalls()
{
var markup = @"
delegate void MyDelegate($$int x, string y, bool z);
class C
{
void M()
{
MyDelegate d1 = null;
d1(1, ""Two"", true);
}
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = null;
d1(true, ""Two"");
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature,
expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_ExplicitInvokeCalls()
{
var markup = @"
delegate void MyDelegate(int x, string $$y, bool z);
class C
{
void M()
{
MyDelegate d1 = null;
d1.Invoke(1, ""Two"", true);
}
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = null;
d1.Invoke(true, ""Two"");
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature,
expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_BeginInvokeCalls()
{
var markup = @"
delegate void MyDelegate(int x, string y, bool z$$);
class C
{
void M()
{
MyDelegate d1 = null;
d1.BeginInvoke(1, ""Two"", true, null, null);
}
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = null;
d1.BeginInvoke(true, ""Two"", null, null);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature,
expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_AnonymousMethods()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
MyDelegate d1 = null;
d1 = delegate (int e, string f, bool g) { var x = f.Length + (g ? 0 : 1); };
d1 = delegate { };
}
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = null;
d1 = delegate (bool g, string f) { var x = f.Length + (g ? 0 : 1); };
d1 = delegate { };
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_Lambdas()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
MyDelegate d1 = null;
d1 = (r, s, t) => { var x = s.Length + (t ? 0 : 1); };
}
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = null;
d1 = (t, s) => { var x = s.Length + (t ? 0 : 1); };
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_Lambdas_RemovingOnlyParameterIntroducesParentheses()
{
var markup = @"
delegate void $$MyDelegate(int x);
class C
{
void M()
{
MyDelegate d1 = null;
d1 = (r) => { System.Console.WriteLine(""Test""); };
d1 = r => { System.Console.WriteLine(""Test""); };
d1 = r => { System.Console.WriteLine(""Test""); };
}
}";
var updatedSignature = Array.Empty<int>();
var expectedUpdatedCode = @"
delegate void MyDelegate();
class C
{
void M()
{
MyDelegate d1 = null;
d1 = () => { System.Console.WriteLine(""Test""); };
d1 = () => { System.Console.WriteLine(""Test""); };
d1 = () => { System.Console.WriteLine(""Test""); };
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_AssignedToVariable()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
MyDelegate d1 = null;
d1 = Goo;
Goo(1, ""Two"", true);
Goo(1, false, false);
}
void Goo(int a, string b, bool c) { }
void Goo(int a, object b, bool c) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = null;
d1 = Goo;
Goo(true, ""Two"");
Goo(1, false, false);
}
void Goo(bool c, string b) { }
void Goo(int a, object b, bool c) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_DelegateConstructor()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
MyDelegate d1 = new MyDelegate(Goo);
Goo(1, ""Two"", true);
Goo(1, false, false);
}
void Goo(int a, string b, bool c) { }
void Goo(int a, object b, bool c) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = new MyDelegate(Goo);
Goo(true, ""Two"");
Goo(1, false, false);
}
void Goo(bool c, string b) { }
void Goo(int a, object b, bool c) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_PassedAsArgument()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
Target(Goo);
Goo(1, ""Two"", true);
Goo(1, false, false);
}
void Target(MyDelegate d) { }
void Goo(int a, string b, bool c) { }
void Goo(int a, object b, bool c) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
Target(Goo);
Goo(true, ""Two"");
Goo(1, false, false);
}
void Target(MyDelegate d) { }
void Goo(bool c, string b) { }
void Goo(int a, object b, bool c) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_ReturnValue()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
MyDelegate d1 = Result();
Goo(1, ""Two"", true);
}
private MyDelegate Result()
{
return Goo;
}
void Goo(int a, string b, bool c) { }
void Goo(int a, object b, bool c) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = Result();
Goo(true, ""Two"");
}
private MyDelegate Result()
{
return Goo;
}
void Goo(bool c, string b) { }
void Goo(int a, object b, bool c) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_YieldReturnValue()
{
var markup = @"
using System.Collections.Generic;
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
Goo(1, ""Two"", true);
}
private IEnumerable<MyDelegate> Result()
{
yield return Goo;
}
void Goo(int a, string b, bool c) { }
void Goo(int a, object b, bool c) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
using System.Collections.Generic;
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
Goo(true, ""Two"");
}
private IEnumerable<MyDelegate> Result()
{
yield return Goo;
}
void Goo(bool c, string b) { }
void Goo(int a, object b, bool c) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_ReferencingLambdas_MethodArgument()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M6()
{
Target((m, n, o) => { var x = n.Length + (o ? 0 : 1); });
}
void Target(MyDelegate d) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M6()
{
Target((o, n) => { var x = n.Length + (o ? 0 : 1); });
}
void Target(MyDelegate d) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_ReferencingLambdas_YieldReturn()
{
var markup = @"
using System.Collections.Generic;
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
private IEnumerable<MyDelegate> Result3()
{
yield return (g, h, i) => { var x = h.Length + (i ? 0 : 1); };
}
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
using System.Collections.Generic;
delegate void MyDelegate(bool z, string y);
class C
{
private IEnumerable<MyDelegate> Result3()
{
yield return (i, h) => { var x = h.Length + (i ? 0 : 1); };
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_Recursive()
{
var markup = @"
delegate RecursiveDelegate $$RecursiveDelegate(int x, string y, bool z);
class C
{
void M()
{
RecursiveDelegate rd = null;
rd(1, ""Two"", true)(1, ""Two"", true)(1, ""Two"", true)(1, ""Two"", true)(1, ""Two"", true);
}
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate RecursiveDelegate RecursiveDelegate(bool z, string y);
class C
{
void M()
{
RecursiveDelegate rd = null;
rd(true, ""Two"")(true, ""Two"")(true, ""Two"")(true, ""Two"")(true, ""Two"");
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_DocComments()
{
var markup = @"
/// <summary>
/// This is <see cref=""MyDelegate""/>, which has these methods:
/// <see cref=""MyDelegate.MyDelegate(object, IntPtr)""/>
/// <see cref=""MyDelegate.Invoke(int, string, bool)""/>
/// <see cref=""MyDelegate.EndInvoke(IAsyncResult)""/>
/// <see cref=""MyDelegate.BeginInvoke(int, string, bool, AsyncCallback, object)""/>
/// </summary>
/// <param name=""x"">x!</param>
/// <param name=""y"">y!</param>
/// <param name=""z"">z!</param>
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
MyDelegate d1 = Goo;
Goo(1, ""Two"", true);
}
/// <param name=""a""></param>
/// <param name=""b""></param>
/// <param name=""c""></param>
void Goo(int a, string b, bool c) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
/// <summary>
/// This is <see cref=""MyDelegate""/>, which has these methods:
/// <see cref=""MyDelegate.MyDelegate(object, IntPtr)""/>
/// <see cref=""MyDelegate.Invoke(bool, string)""/>
/// <see cref=""MyDelegate.EndInvoke(IAsyncResult)""/>
/// <see cref=""MyDelegate.BeginInvoke(int, string, bool, AsyncCallback, object)""/>
/// </summary>
/// <param name=""z"">z!</param>
/// <param name=""y"">y!</param>
///
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = Goo;
Goo(true, ""Two"");
}
/// <param name=""c""></param>
/// <param name=""b""></param>
///
void Goo(bool c, string b) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_CascadeThroughEventAdd()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class Program
{
void M()
{
MyEvent += Program_MyEvent;
}
event MyDelegate MyEvent;
void Program_MyEvent(int a, string b, bool c) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class Program
{
void M()
{
MyEvent += Program_MyEvent;
}
event MyDelegate MyEvent;
void Program_MyEvent(bool c, string b) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_Generics1()
{
var markup = @"
public class DP16a
{
public delegate void D<T>($$T t);
public event D<int> E1;
public event D<int> E2;
public void M1(int i) { }
public void M2(int i) { }
public void M3(int i) { }
void B()
{
D<int> d = new D<int>(M1);
E1 += new D<int>(M2);
E2 -= new D<int>(M3);
}
}";
var updatedSignature = Array.Empty<int>();
var expectedUpdatedCode = @"
public class DP16a
{
public delegate void D<T>();
public event D<int> E1;
public event D<int> E2;
public void M1() { }
public void M2() { }
public void M3() { }
void B()
{
D<int> d = new D<int>(M1);
E1 += new D<int>(M2);
E2 -= new D<int>(M3);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_Generics2()
{
var markup = @"
public class D17<T>
{
public delegate void $$D(T t);
}
public class D17Test
{
void Test() { var x = new D17<string>.D(M17); }
internal void M17(string s) { }
}";
var updatedSignature = Array.Empty<int>();
var expectedUpdatedCode = @"
public class D17<T>
{
public delegate void D();
}
public class D17Test
{
void Test() { var x = new D17<string>.D(M17); }
internal void M17() { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_GenericParams()
{
var markup = @"
class DA
{
void M(params int[] i) { }
void B()
{
DP20<int>.D d = new DP20<int>.D(M);
d();
d(0);
d(0, 1);
}
}
public class DP20<T>
{
public delegate void $$D(params T[] t);
public void M1(params T[] t) { }
void B()
{
D d = new D(M1);
}
}";
var updatedSignature = Array.Empty<int>();
var expectedUpdatedCode = @"
class DA
{
void M() { }
void B()
{
DP20<int>.D d = new DP20<int>.D(M);
d();
d();
d();
}
}
public class DP20<T>
{
public delegate void D();
public void M1() { }
void B()
{
D d = new D(M1);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_Generic_RemoveArgumentAtReference()
{
var markup = @"public class CD<T>
{
public delegate void D(T t);
}
class Test
{
public void M()
{
var dele = new CD<int>.$$D((int x) => { });
}
}";
var updatedSignature = Array.Empty<int>();
var expectedUpdatedCode = @"public class CD<T>
{
public delegate void D();
}
class Test
{
public void M()
{
var dele = new CD<int>.D(() => { });
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature,
expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegate_Generics_RemoveStaticArgument()
{
var markup = @"
public class C2<T>
{
public delegate void D(T t);
}
public class D2
{
public static D2 Instance = null;
void M(D2 m) { }
void B()
{
C2<D2>.D d = new C2<D2>.D(M);
$$d(D2.Instance);
}
}";
var updatedSignature = Array.Empty<int>();
var expectedUpdatedCode = @"
public class C2<T>
{
public delegate void D();
}
public class D2
{
public static D2 Instance = null;
void M() { }
void B()
{
C2<D2>.D d = new C2<D2>.D(M);
d();
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
}
}
| // 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.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature
{
public partial class ChangeSignatureTests : AbstractChangeSignatureTests
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new ChangeSignatureCodeRefactoringProvider();
protected internal override string GetLanguage()
=> LanguageNames.CSharp;
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_ImplicitInvokeCalls()
{
var markup = @"
delegate void MyDelegate($$int x, string y, bool z);
class C
{
void M()
{
MyDelegate d1 = null;
d1(1, ""Two"", true);
}
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = null;
d1(true, ""Two"");
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature,
expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_ExplicitInvokeCalls()
{
var markup = @"
delegate void MyDelegate(int x, string $$y, bool z);
class C
{
void M()
{
MyDelegate d1 = null;
d1.Invoke(1, ""Two"", true);
}
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = null;
d1.Invoke(true, ""Two"");
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature,
expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_BeginInvokeCalls()
{
var markup = @"
delegate void MyDelegate(int x, string y, bool z$$);
class C
{
void M()
{
MyDelegate d1 = null;
d1.BeginInvoke(1, ""Two"", true, null, null);
}
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = null;
d1.BeginInvoke(true, ""Two"", null, null);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature,
expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_AnonymousMethods()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
MyDelegate d1 = null;
d1 = delegate (int e, string f, bool g) { var x = f.Length + (g ? 0 : 1); };
d1 = delegate { };
}
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = null;
d1 = delegate (bool g, string f) { var x = f.Length + (g ? 0 : 1); };
d1 = delegate { };
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_Lambdas()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
MyDelegate d1 = null;
d1 = (r, s, t) => { var x = s.Length + (t ? 0 : 1); };
}
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = null;
d1 = (t, s) => { var x = s.Length + (t ? 0 : 1); };
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_Lambdas_RemovingOnlyParameterIntroducesParentheses()
{
var markup = @"
delegate void $$MyDelegate(int x);
class C
{
void M()
{
MyDelegate d1 = null;
d1 = (r) => { System.Console.WriteLine(""Test""); };
d1 = r => { System.Console.WriteLine(""Test""); };
d1 = r => { System.Console.WriteLine(""Test""); };
}
}";
var updatedSignature = Array.Empty<int>();
var expectedUpdatedCode = @"
delegate void MyDelegate();
class C
{
void M()
{
MyDelegate d1 = null;
d1 = () => { System.Console.WriteLine(""Test""); };
d1 = () => { System.Console.WriteLine(""Test""); };
d1 = () => { System.Console.WriteLine(""Test""); };
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_AssignedToVariable()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
MyDelegate d1 = null;
d1 = Goo;
Goo(1, ""Two"", true);
Goo(1, false, false);
}
void Goo(int a, string b, bool c) { }
void Goo(int a, object b, bool c) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = null;
d1 = Goo;
Goo(true, ""Two"");
Goo(1, false, false);
}
void Goo(bool c, string b) { }
void Goo(int a, object b, bool c) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_DelegateConstructor()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
MyDelegate d1 = new MyDelegate(Goo);
Goo(1, ""Two"", true);
Goo(1, false, false);
}
void Goo(int a, string b, bool c) { }
void Goo(int a, object b, bool c) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = new MyDelegate(Goo);
Goo(true, ""Two"");
Goo(1, false, false);
}
void Goo(bool c, string b) { }
void Goo(int a, object b, bool c) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_PassedAsArgument()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
Target(Goo);
Goo(1, ""Two"", true);
Goo(1, false, false);
}
void Target(MyDelegate d) { }
void Goo(int a, string b, bool c) { }
void Goo(int a, object b, bool c) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
Target(Goo);
Goo(true, ""Two"");
Goo(1, false, false);
}
void Target(MyDelegate d) { }
void Goo(bool c, string b) { }
void Goo(int a, object b, bool c) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_ReturnValue()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
MyDelegate d1 = Result();
Goo(1, ""Two"", true);
}
private MyDelegate Result()
{
return Goo;
}
void Goo(int a, string b, bool c) { }
void Goo(int a, object b, bool c) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = Result();
Goo(true, ""Two"");
}
private MyDelegate Result()
{
return Goo;
}
void Goo(bool c, string b) { }
void Goo(int a, object b, bool c) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_CascadeThroughMethodGroups_YieldReturnValue()
{
var markup = @"
using System.Collections.Generic;
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
Goo(1, ""Two"", true);
}
private IEnumerable<MyDelegate> Result()
{
yield return Goo;
}
void Goo(int a, string b, bool c) { }
void Goo(int a, object b, bool c) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
using System.Collections.Generic;
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
Goo(true, ""Two"");
}
private IEnumerable<MyDelegate> Result()
{
yield return Goo;
}
void Goo(bool c, string b) { }
void Goo(int a, object b, bool c) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_ReferencingLambdas_MethodArgument()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M6()
{
Target((m, n, o) => { var x = n.Length + (o ? 0 : 1); });
}
void Target(MyDelegate d) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class C
{
void M6()
{
Target((o, n) => { var x = n.Length + (o ? 0 : 1); });
}
void Target(MyDelegate d) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_ReferencingLambdas_YieldReturn()
{
var markup = @"
using System.Collections.Generic;
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
private IEnumerable<MyDelegate> Result3()
{
yield return (g, h, i) => { var x = h.Length + (i ? 0 : 1); };
}
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
using System.Collections.Generic;
delegate void MyDelegate(bool z, string y);
class C
{
private IEnumerable<MyDelegate> Result3()
{
yield return (i, h) => { var x = h.Length + (i ? 0 : 1); };
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_Recursive()
{
var markup = @"
delegate RecursiveDelegate $$RecursiveDelegate(int x, string y, bool z);
class C
{
void M()
{
RecursiveDelegate rd = null;
rd(1, ""Two"", true)(1, ""Two"", true)(1, ""Two"", true)(1, ""Two"", true)(1, ""Two"", true);
}
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate RecursiveDelegate RecursiveDelegate(bool z, string y);
class C
{
void M()
{
RecursiveDelegate rd = null;
rd(true, ""Two"")(true, ""Two"")(true, ""Two"")(true, ""Two"")(true, ""Two"");
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_DocComments()
{
var markup = @"
/// <summary>
/// This is <see cref=""MyDelegate""/>, which has these methods:
/// <see cref=""MyDelegate.MyDelegate(object, IntPtr)""/>
/// <see cref=""MyDelegate.Invoke(int, string, bool)""/>
/// <see cref=""MyDelegate.EndInvoke(IAsyncResult)""/>
/// <see cref=""MyDelegate.BeginInvoke(int, string, bool, AsyncCallback, object)""/>
/// </summary>
/// <param name=""x"">x!</param>
/// <param name=""y"">y!</param>
/// <param name=""z"">z!</param>
delegate void $$MyDelegate(int x, string y, bool z);
class C
{
void M()
{
MyDelegate d1 = Goo;
Goo(1, ""Two"", true);
}
/// <param name=""a""></param>
/// <param name=""b""></param>
/// <param name=""c""></param>
void Goo(int a, string b, bool c) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
/// <summary>
/// This is <see cref=""MyDelegate""/>, which has these methods:
/// <see cref=""MyDelegate.MyDelegate(object, IntPtr)""/>
/// <see cref=""MyDelegate.Invoke(bool, string)""/>
/// <see cref=""MyDelegate.EndInvoke(IAsyncResult)""/>
/// <see cref=""MyDelegate.BeginInvoke(int, string, bool, AsyncCallback, object)""/>
/// </summary>
/// <param name=""z"">z!</param>
/// <param name=""y"">y!</param>
///
delegate void MyDelegate(bool z, string y);
class C
{
void M()
{
MyDelegate d1 = Goo;
Goo(true, ""Two"");
}
/// <param name=""c""></param>
/// <param name=""b""></param>
///
void Goo(bool c, string b) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_CascadeThroughEventAdd()
{
var markup = @"
delegate void $$MyDelegate(int x, string y, bool z);
class Program
{
void M()
{
MyEvent += Program_MyEvent;
}
event MyDelegate MyEvent;
void Program_MyEvent(int a, string b, bool c) { }
}";
var updatedSignature = new[] { 2, 1 };
var expectedUpdatedCode = @"
delegate void MyDelegate(bool z, string y);
class Program
{
void M()
{
MyEvent += Program_MyEvent;
}
event MyDelegate MyEvent;
void Program_MyEvent(bool c, string b) { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_Generics1()
{
var markup = @"
public class DP16a
{
public delegate void D<T>($$T t);
public event D<int> E1;
public event D<int> E2;
public void M1(int i) { }
public void M2(int i) { }
public void M3(int i) { }
void B()
{
D<int> d = new D<int>(M1);
E1 += new D<int>(M2);
E2 -= new D<int>(M3);
}
}";
var updatedSignature = Array.Empty<int>();
var expectedUpdatedCode = @"
public class DP16a
{
public delegate void D<T>();
public event D<int> E1;
public event D<int> E2;
public void M1() { }
public void M2() { }
public void M3() { }
void B()
{
D<int> d = new D<int>(M1);
E1 += new D<int>(M2);
E2 -= new D<int>(M3);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_Generics2()
{
var markup = @"
public class D17<T>
{
public delegate void $$D(T t);
}
public class D17Test
{
void Test() { var x = new D17<string>.D(M17); }
internal void M17(string s) { }
}";
var updatedSignature = Array.Empty<int>();
var expectedUpdatedCode = @"
public class D17<T>
{
public delegate void D();
}
public class D17Test
{
void Test() { var x = new D17<string>.D(M17); }
internal void M17() { }
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_GenericParams()
{
var markup = @"
class DA
{
void M(params int[] i) { }
void B()
{
DP20<int>.D d = new DP20<int>.D(M);
d();
d(0);
d(0, 1);
}
}
public class DP20<T>
{
public delegate void $$D(params T[] t);
public void M1(params T[] t) { }
void B()
{
D d = new D(M1);
}
}";
var updatedSignature = Array.Empty<int>();
var expectedUpdatedCode = @"
class DA
{
void M() { }
void B()
{
DP20<int>.D d = new DP20<int>.D(M);
d();
d();
d();
}
}
public class DP20<T>
{
public delegate void D();
public void M1() { }
void B()
{
D d = new D(M1);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegates_Generic_RemoveArgumentAtReference()
{
var markup = @"public class CD<T>
{
public delegate void D(T t);
}
class Test
{
public void M()
{
var dele = new CD<int>.$$D((int x) => { });
}
}";
var updatedSignature = Array.Empty<int>();
var expectedUpdatedCode = @"public class CD<T>
{
public delegate void D();
}
class Test
{
public void M()
{
var dele = new CD<int>.D(() => { });
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature,
expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, expectedSelectedIndex: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ChangeSignature_Delegate_Generics_RemoveStaticArgument()
{
var markup = @"
public class C2<T>
{
public delegate void D(T t);
}
public class D2
{
public static D2 Instance = null;
void M(D2 m) { }
void B()
{
C2<D2>.D d = new C2<D2>.D(M);
$$d(D2.Instance);
}
}";
var updatedSignature = Array.Empty<int>();
var expectedUpdatedCode = @"
public class C2<T>
{
public delegate void D();
}
public class D2
{
public static D2 Instance = null;
void M() { }
void B()
{
C2<D2>.D d = new C2<D2>.D(M);
d();
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode);
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/Core/Portable/CodeGen/SwitchIntegralJumpTableEmitter.cs | // 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.Reflection.Metadata;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeGen
{
/// <summary>
/// Class for emitting the switch jump table for switch statements with integral governing type
/// </summary>
internal partial struct SwitchIntegralJumpTableEmitter
{
private readonly ILBuilder _builder;
/// <summary>
/// Switch key for the jump table
/// </summary>
private readonly LocalOrParameter _key;
/// <summary>
/// Primitive type of the switch key
/// </summary>
private readonly Cci.PrimitiveTypeCode _keyTypeCode;
/// <summary>
/// Fall through label for the jump table
/// </summary>
private readonly object _fallThroughLabel;
/// <summary>
/// Integral case labels sorted and indexed by their ConstantValue
/// </summary>
private readonly ImmutableArray<KeyValuePair<ConstantValue, object>> _sortedCaseLabels;
// threshold at which binary search stops partitioning.
// if a search leaf has less than LinearSearchThreshold buckets
// we just go through buckets linearly.
// We chose 3 here because it is where number of branches to reach fall-through
// is the same for linear and binary search.
private const int LinearSearchThreshold = 3;
internal SwitchIntegralJumpTableEmitter(
ILBuilder builder,
KeyValuePair<ConstantValue, object>[] caseLabels,
object fallThroughLabel,
Cci.PrimitiveTypeCode keyTypeCode,
LocalOrParameter key)
{
_builder = builder;
_key = key;
_keyTypeCode = keyTypeCode;
_fallThroughLabel = fallThroughLabel;
// Sort the switch case labels, see comments below for more details.
Debug.Assert(caseLabels.Length > 0);
Array.Sort(caseLabels, CompareIntegralSwitchLabels);
_sortedCaseLabels = ImmutableArray.Create(caseLabels);
}
internal void EmitJumpTable()
{
// For emitting the switch statement (integral governing type) jump table with a non-constant
// switch expression, we can use a naive approach and generate a single big MSIL switch instruction
// with all the case labels and fall through label. However, this approach can be optimized
// to improve both the code size and speed using the following optimization steps:
// a) Sort the switch case labels based on their constant values.
// b) Divide the sorted switch labels into buckets with good enough density (>50%). For example:
// switch(..)
// {
// case 1:
// case 100:
// break;
// case 2:
// case 4:
// break;
// case 200:
// case 201:
// case 202:
// break;
// }
// can be divided into 3 buckets: (1, 2, 4) (100) (200, 201, 202).
// We do this bucketing so that we have reasonable size jump tables for generated switch instructions.
// c) After bucketing, generate code to perform a binary search on these buckets array,
// emitting conditional jumps if current bucket sub-array has more than one bucket and
// emitting the switch instruction when we are down to a single bucket in the sub-array.
// (a) Sort switch labels: This was done in the constructor
Debug.Assert(!_sortedCaseLabels.IsEmpty);
var sortedCaseLabels = _sortedCaseLabels;
int endLabelIndex = sortedCaseLabels.Length - 1;
int startLabelIndex;
// Check for a label with ConstantValue.Null.
// Sorting ensures that if we do have one, it will be
// the first label in the sorted list.
if (sortedCaseLabels[0].Key != ConstantValue.Null)
{
startLabelIndex = 0;
}
else
{
// Skip null label for emitting switch table header.
// We should have inserted a conditional branch to 'null' label during rewriting.
// See LocalRewriter.MakeSwitchStatementWithNullableExpression
startLabelIndex = 1;
}
if (startLabelIndex <= endLabelIndex)
{
// We have at least one non-null case label, emit jump table
// (b) Generate switch buckets
ImmutableArray<SwitchBucket> switchBuckets = this.GenerateSwitchBuckets(startLabelIndex, endLabelIndex);
// (c) Emit switch buckets
this.EmitSwitchBuckets(switchBuckets, 0, switchBuckets.Length - 1);
}
else
{
_builder.EmitBranch(ILOpCode.Br, _fallThroughLabel);
}
}
#region "Sorting switch labels"
private static int CompareIntegralSwitchLabels(KeyValuePair<ConstantValue, object> first, KeyValuePair<ConstantValue, object> second)
{
ConstantValue firstConstant = first.Key;
ConstantValue secondConstant = second.Key;
RoslynDebug.Assert(firstConstant != null);
Debug.Assert(SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(firstConstant)
&& !firstConstant.IsString);
RoslynDebug.Assert(secondConstant != null);
Debug.Assert(SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(secondConstant)
&& !secondConstant.IsString);
return SwitchConstantValueHelper.CompareSwitchCaseLabelConstants(firstConstant, secondConstant);
}
#endregion
#region "Switch bucketing methods"
// Bucketing algorithm:
// Start with empty stack of buckets.
// While there are still labels
// If bucket from remaining labels is dense
// Create a newBucket from remaining labels
// Else
// Create a singleton newBucket from the next label
// While the top bucket on stack can be merged with newBucket into a dense bucket
// merge top bucket on stack into newBucket, and pop bucket from stack
// End While
// Push newBucket on stack
// End While
private ImmutableArray<SwitchBucket> GenerateSwitchBuckets(int startLabelIndex, int endLabelIndex)
{
Debug.Assert(startLabelIndex >= 0 && startLabelIndex <= endLabelIndex);
Debug.Assert(_sortedCaseLabels.Length > endLabelIndex);
// Start with empty stack of buckets.
var switchBucketsStack = ArrayBuilder<SwitchBucket>.GetInstance();
int curStartLabelIndex = startLabelIndex;
// While there are still labels
while (curStartLabelIndex <= endLabelIndex)
{
SwitchBucket newBucket = CreateNextBucket(curStartLabelIndex, endLabelIndex);
// While the top bucket on stack can be merged with newBucket into a dense bucket
// merge top bucket on stack into newBucket, and pop bucket from stack
// End While
while (!switchBucketsStack.IsEmpty())
{
// get the bucket at top of the stack
SwitchBucket prevBucket = switchBucketsStack.Peek();
if (newBucket.TryMergeWith(prevBucket))
{
// pop the previous bucket from the stack
switchBucketsStack.Pop();
}
else
{
// merge failed
break;
}
}
// Push newBucket on stack
switchBucketsStack.Push(newBucket);
// update curStartLabelIndex
curStartLabelIndex++;
}
Debug.Assert(!switchBucketsStack.IsEmpty());
// crumble leaf buckets into degenerate buckets where possible
var crumbled = ArrayBuilder<SwitchBucket>.GetInstance();
foreach (var uncrumbled in switchBucketsStack)
{
var degenerateSplit = uncrumbled.DegenerateBucketSplit;
switch (degenerateSplit)
{
case -1:
// cannot be split
crumbled.Add(uncrumbled);
break;
case 0:
// already degenerate
crumbled.Add(new SwitchBucket(_sortedCaseLabels, uncrumbled.StartLabelIndex, uncrumbled.EndLabelIndex, isDegenerate: true));
break;
default:
// can split
crumbled.Add(new SwitchBucket(_sortedCaseLabels, uncrumbled.StartLabelIndex, degenerateSplit - 1, isDegenerate: true));
crumbled.Add(new SwitchBucket(_sortedCaseLabels, degenerateSplit, uncrumbled.EndLabelIndex, isDegenerate: true));
break;
}
}
switchBucketsStack.Free();
return crumbled.ToImmutableAndFree();
}
private SwitchBucket CreateNextBucket(int startLabelIndex, int endLabelIndex)
{
Debug.Assert(startLabelIndex >= 0 && startLabelIndex <= endLabelIndex);
return new SwitchBucket(_sortedCaseLabels, startLabelIndex);
}
#endregion
#region "Switch bucket emit methods"
private void EmitSwitchBucketsLinearLeaf(ImmutableArray<SwitchBucket> switchBuckets, int low, int high)
{
for (int i = low; i < high; i++)
{
var nextBucketLabel = new object();
this.EmitSwitchBucket(switchBuckets[i], nextBucketLabel);
// nextBucketLabel:
_builder.MarkLabel(nextBucketLabel);
}
this.EmitSwitchBucket(switchBuckets[high], _fallThroughLabel);
}
private void EmitSwitchBuckets(ImmutableArray<SwitchBucket> switchBuckets, int low, int high)
{
// if (high - low + 1 <= LinearSearchThreshold)
if (high - low < LinearSearchThreshold)
{
this.EmitSwitchBucketsLinearLeaf(switchBuckets, low, high);
return;
}
// This way (0 1 2 3) will produce a mid of 2 while
// (0 1 2) will produce a mid of 1
// Now, the first half is first to mid-1
// and the second half is mid to last.
int mid = (low + high + 1) / 2;
object secondHalfLabel = new object();
// Emit a conditional branch to the second half
// before emitting the first half buckets.
ConstantValue pivotConstant = switchBuckets[mid - 1].EndConstant;
// if(key > midLabelConstant)
// goto secondHalfLabel;
this.EmitCondBranchForSwitch(
_keyTypeCode.IsUnsigned() ? ILOpCode.Bgt_un : ILOpCode.Bgt,
pivotConstant,
secondHalfLabel);
// Emit first half
this.EmitSwitchBuckets(switchBuckets, low, mid - 1);
// NOTE: Typically marking a synthetic label needs a hidden sequence point.
// NOTE: Otherwise if you step (F11) to this label debugger may highlight previous (lexically) statement.
// NOTE: We do not need a hidden point in this implementation since we do not interleave jump table
// NOTE: and cases so the "previous" statement will always be "switch".
// secondHalfLabel:
_builder.MarkLabel(secondHalfLabel);
// Emit second half
this.EmitSwitchBuckets(switchBuckets, mid, high);
}
private void EmitSwitchBucket(SwitchBucket switchBucket, object bucketFallThroughLabel)
{
if (switchBucket.LabelsCount == 1)
{
var c = switchBucket[0];
// if(key == constant)
// goto caseLabel;
ConstantValue constant = c.Key;
object caseLabel = c.Value;
this.EmitEqBranchForSwitch(constant, caseLabel);
}
else
{
if (switchBucket.IsDegenerate)
{
EmitRangeCheckedBranch(switchBucket.StartConstant, switchBucket.EndConstant, switchBucket[0].Value);
}
else
{
// Emit key normalized to startConstant (i.e. key - startConstant)
this.EmitNormalizedSwitchKey(switchBucket.StartConstant, switchBucket.EndConstant, bucketFallThroughLabel);
// Create the labels array for emitting a switch instruction for the bucket
object[] labels = this.CreateBucketLabels(switchBucket);
// switch (N, label1, label2... labelN)
// Emit the switch instruction
_builder.EmitSwitch(labels);
}
}
// goto fallThroughLabel;
_builder.EmitBranch(ILOpCode.Br, bucketFallThroughLabel);
}
private object[] CreateBucketLabels(SwitchBucket switchBucket)
{
// switch (N, t1, t2... tN)
// IL ==> ILOpCode.Switch < unsigned int32 > < int32 >... < int32 >
// For example: given a switch bucket [1, 3, 5] and FallThrough Label,
// we create the following labels array:
// { CaseLabel1, FallThrough, CaseLabel3, FallThrough, CaseLabel5 }
ConstantValue startConstant = switchBucket.StartConstant;
bool hasNegativeCaseLabels = startConstant.IsNegativeNumeric;
int nextCaseIndex = 0;
ulong nextCaseLabelNormalizedValue = 0;
ulong bucketSize = switchBucket.BucketSize;
object[] labels = new object[bucketSize];
for (ulong i = 0; i < bucketSize; ++i)
{
if (i == nextCaseLabelNormalizedValue)
{
labels[i] = switchBucket[nextCaseIndex].Value;
nextCaseIndex++;
if (nextCaseIndex >= switchBucket.LabelsCount)
{
Debug.Assert(i == bucketSize - 1);
break;
}
ConstantValue caseLabelConstant = switchBucket[nextCaseIndex].Key;
if (hasNegativeCaseLabels)
{
var nextCaseLabelValue = caseLabelConstant.Int64Value;
Debug.Assert(nextCaseLabelValue > startConstant.Int64Value);
nextCaseLabelNormalizedValue = (ulong)(nextCaseLabelValue - startConstant.Int64Value);
}
else
{
var nextCaseLabelValue = caseLabelConstant.UInt64Value;
Debug.Assert(nextCaseLabelValue > startConstant.UInt64Value);
nextCaseLabelNormalizedValue = nextCaseLabelValue - startConstant.UInt64Value;
}
continue;
}
labels[i] = _fallThroughLabel;
}
Debug.Assert(nextCaseIndex >= switchBucket.LabelsCount);
return labels;
}
#endregion
#region "Helper emit methods"
private void EmitCondBranchForSwitch(ILOpCode branchCode, ConstantValue constant, object targetLabel)
{
Debug.Assert(branchCode.IsBranch());
RoslynDebug.Assert(constant != null &&
SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(constant));
RoslynDebug.Assert(targetLabel != null);
// ldloc key
// ldc constant
// branch branchCode targetLabel
_builder.EmitLoad(_key);
_builder.EmitConstantValue(constant);
_builder.EmitBranch(branchCode, targetLabel, GetReverseBranchCode(branchCode));
}
private void EmitEqBranchForSwitch(ConstantValue constant, object targetLabel)
{
RoslynDebug.Assert(constant != null &&
SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(constant));
RoslynDebug.Assert(targetLabel != null);
_builder.EmitLoad(_key);
if (constant.IsDefaultValue)
{
// ldloc key
// brfalse targetLabel
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel);
}
else
{
_builder.EmitConstantValue(constant);
_builder.EmitBranch(ILOpCode.Beq, targetLabel);
}
}
private void EmitRangeCheckedBranch(ConstantValue startConstant, ConstantValue endConstant, object targetLabel)
{
_builder.EmitLoad(_key);
// Normalize the key to 0 if needed
// Emit: ldc constant
// sub
if (!startConstant.IsDefaultValue)
{
_builder.EmitConstantValue(startConstant);
_builder.EmitOpCode(ILOpCode.Sub);
}
if (_keyTypeCode.Is64BitIntegral())
{
_builder.EmitLongConstant(endConstant.Int64Value - startConstant.Int64Value);
}
else
{
int Int32Value(ConstantValue value)
{
// ConstantValue does not correctly convert byte and ushort values to int.
// It sign extends them rather than padding them. We compensate for that here.
// See also https://github.com/dotnet/roslyn/issues/18579
switch (value.Discriminator)
{
case ConstantValueTypeDiscriminator.Byte: return value.ByteValue;
case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value;
default: return value.Int32Value;
}
}
_builder.EmitIntConstant(Int32Value(endConstant) - Int32Value(startConstant));
}
_builder.EmitBranch(ILOpCode.Ble_un, targetLabel, ILOpCode.Bgt_un);
}
private static ILOpCode GetReverseBranchCode(ILOpCode branchCode)
{
switch (branchCode)
{
case ILOpCode.Beq:
return ILOpCode.Bne_un;
case ILOpCode.Blt:
return ILOpCode.Bge;
case ILOpCode.Blt_un:
return ILOpCode.Bge_un;
case ILOpCode.Bgt:
return ILOpCode.Ble;
case ILOpCode.Bgt_un:
return ILOpCode.Ble_un;
default:
throw ExceptionUtilities.UnexpectedValue(branchCode);
}
}
private void EmitNormalizedSwitchKey(ConstantValue startConstant, ConstantValue endConstant, object bucketFallThroughLabel)
{
_builder.EmitLoad(_key);
// Normalize the key to 0 if needed
// Emit: ldc constant
// sub
if (!startConstant.IsDefaultValue)
{
_builder.EmitConstantValue(startConstant);
_builder.EmitOpCode(ILOpCode.Sub);
}
// range-check normalized value if needed
EmitRangeCheckIfNeeded(startConstant, endConstant, bucketFallThroughLabel);
// truncate key to 32bit
_builder.EmitNumericConversion(_keyTypeCode, Microsoft.Cci.PrimitiveTypeCode.UInt32, false);
}
private void EmitRangeCheckIfNeeded(ConstantValue startConstant, ConstantValue endConstant, object bucketFallThroughLabel)
{
// switch treats key as an unsigned int.
// this ensures that normalization does not introduce [over|under]flows issues with 32bit or shorter keys.
// 64bit values, however must be checked before 32bit truncation happens.
if (_keyTypeCode.Is64BitIntegral())
{
// Dup(normalized);
// if ((ulong)(normalized) > (ulong)(endConstant - startConstant))
// {
// // not going to use it in the switch
// Pop(normalized);
// goto bucketFallThroughLabel;
// }
var inRangeLabel = new object();
_builder.EmitOpCode(ILOpCode.Dup);
_builder.EmitLongConstant(endConstant.Int64Value - startConstant.Int64Value);
_builder.EmitBranch(ILOpCode.Ble_un, inRangeLabel, ILOpCode.Bgt_un);
_builder.EmitOpCode(ILOpCode.Pop);
_builder.EmitBranch(ILOpCode.Br, bucketFallThroughLabel);
// If we get to inRangeLabel, we should have key on stack, adjust for that.
// builder cannot infer this since it has not seen all branches,
// but it will verify that our Adjustment is valid when more branches are known.
_builder.AdjustStack(+1);
_builder.MarkLabel(inRangeLabel);
}
}
#endregion
}
}
| // 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.Reflection.Metadata;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeGen
{
/// <summary>
/// Class for emitting the switch jump table for switch statements with integral governing type
/// </summary>
internal partial struct SwitchIntegralJumpTableEmitter
{
private readonly ILBuilder _builder;
/// <summary>
/// Switch key for the jump table
/// </summary>
private readonly LocalOrParameter _key;
/// <summary>
/// Primitive type of the switch key
/// </summary>
private readonly Cci.PrimitiveTypeCode _keyTypeCode;
/// <summary>
/// Fall through label for the jump table
/// </summary>
private readonly object _fallThroughLabel;
/// <summary>
/// Integral case labels sorted and indexed by their ConstantValue
/// </summary>
private readonly ImmutableArray<KeyValuePair<ConstantValue, object>> _sortedCaseLabels;
// threshold at which binary search stops partitioning.
// if a search leaf has less than LinearSearchThreshold buckets
// we just go through buckets linearly.
// We chose 3 here because it is where number of branches to reach fall-through
// is the same for linear and binary search.
private const int LinearSearchThreshold = 3;
internal SwitchIntegralJumpTableEmitter(
ILBuilder builder,
KeyValuePair<ConstantValue, object>[] caseLabels,
object fallThroughLabel,
Cci.PrimitiveTypeCode keyTypeCode,
LocalOrParameter key)
{
_builder = builder;
_key = key;
_keyTypeCode = keyTypeCode;
_fallThroughLabel = fallThroughLabel;
// Sort the switch case labels, see comments below for more details.
Debug.Assert(caseLabels.Length > 0);
Array.Sort(caseLabels, CompareIntegralSwitchLabels);
_sortedCaseLabels = ImmutableArray.Create(caseLabels);
}
internal void EmitJumpTable()
{
// For emitting the switch statement (integral governing type) jump table with a non-constant
// switch expression, we can use a naive approach and generate a single big MSIL switch instruction
// with all the case labels and fall through label. However, this approach can be optimized
// to improve both the code size and speed using the following optimization steps:
// a) Sort the switch case labels based on their constant values.
// b) Divide the sorted switch labels into buckets with good enough density (>50%). For example:
// switch(..)
// {
// case 1:
// case 100:
// break;
// case 2:
// case 4:
// break;
// case 200:
// case 201:
// case 202:
// break;
// }
// can be divided into 3 buckets: (1, 2, 4) (100) (200, 201, 202).
// We do this bucketing so that we have reasonable size jump tables for generated switch instructions.
// c) After bucketing, generate code to perform a binary search on these buckets array,
// emitting conditional jumps if current bucket sub-array has more than one bucket and
// emitting the switch instruction when we are down to a single bucket in the sub-array.
// (a) Sort switch labels: This was done in the constructor
Debug.Assert(!_sortedCaseLabels.IsEmpty);
var sortedCaseLabels = _sortedCaseLabels;
int endLabelIndex = sortedCaseLabels.Length - 1;
int startLabelIndex;
// Check for a label with ConstantValue.Null.
// Sorting ensures that if we do have one, it will be
// the first label in the sorted list.
if (sortedCaseLabels[0].Key != ConstantValue.Null)
{
startLabelIndex = 0;
}
else
{
// Skip null label for emitting switch table header.
// We should have inserted a conditional branch to 'null' label during rewriting.
// See LocalRewriter.MakeSwitchStatementWithNullableExpression
startLabelIndex = 1;
}
if (startLabelIndex <= endLabelIndex)
{
// We have at least one non-null case label, emit jump table
// (b) Generate switch buckets
ImmutableArray<SwitchBucket> switchBuckets = this.GenerateSwitchBuckets(startLabelIndex, endLabelIndex);
// (c) Emit switch buckets
this.EmitSwitchBuckets(switchBuckets, 0, switchBuckets.Length - 1);
}
else
{
_builder.EmitBranch(ILOpCode.Br, _fallThroughLabel);
}
}
#region "Sorting switch labels"
private static int CompareIntegralSwitchLabels(KeyValuePair<ConstantValue, object> first, KeyValuePair<ConstantValue, object> second)
{
ConstantValue firstConstant = first.Key;
ConstantValue secondConstant = second.Key;
RoslynDebug.Assert(firstConstant != null);
Debug.Assert(SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(firstConstant)
&& !firstConstant.IsString);
RoslynDebug.Assert(secondConstant != null);
Debug.Assert(SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(secondConstant)
&& !secondConstant.IsString);
return SwitchConstantValueHelper.CompareSwitchCaseLabelConstants(firstConstant, secondConstant);
}
#endregion
#region "Switch bucketing methods"
// Bucketing algorithm:
// Start with empty stack of buckets.
// While there are still labels
// If bucket from remaining labels is dense
// Create a newBucket from remaining labels
// Else
// Create a singleton newBucket from the next label
// While the top bucket on stack can be merged with newBucket into a dense bucket
// merge top bucket on stack into newBucket, and pop bucket from stack
// End While
// Push newBucket on stack
// End While
private ImmutableArray<SwitchBucket> GenerateSwitchBuckets(int startLabelIndex, int endLabelIndex)
{
Debug.Assert(startLabelIndex >= 0 && startLabelIndex <= endLabelIndex);
Debug.Assert(_sortedCaseLabels.Length > endLabelIndex);
// Start with empty stack of buckets.
var switchBucketsStack = ArrayBuilder<SwitchBucket>.GetInstance();
int curStartLabelIndex = startLabelIndex;
// While there are still labels
while (curStartLabelIndex <= endLabelIndex)
{
SwitchBucket newBucket = CreateNextBucket(curStartLabelIndex, endLabelIndex);
// While the top bucket on stack can be merged with newBucket into a dense bucket
// merge top bucket on stack into newBucket, and pop bucket from stack
// End While
while (!switchBucketsStack.IsEmpty())
{
// get the bucket at top of the stack
SwitchBucket prevBucket = switchBucketsStack.Peek();
if (newBucket.TryMergeWith(prevBucket))
{
// pop the previous bucket from the stack
switchBucketsStack.Pop();
}
else
{
// merge failed
break;
}
}
// Push newBucket on stack
switchBucketsStack.Push(newBucket);
// update curStartLabelIndex
curStartLabelIndex++;
}
Debug.Assert(!switchBucketsStack.IsEmpty());
// crumble leaf buckets into degenerate buckets where possible
var crumbled = ArrayBuilder<SwitchBucket>.GetInstance();
foreach (var uncrumbled in switchBucketsStack)
{
var degenerateSplit = uncrumbled.DegenerateBucketSplit;
switch (degenerateSplit)
{
case -1:
// cannot be split
crumbled.Add(uncrumbled);
break;
case 0:
// already degenerate
crumbled.Add(new SwitchBucket(_sortedCaseLabels, uncrumbled.StartLabelIndex, uncrumbled.EndLabelIndex, isDegenerate: true));
break;
default:
// can split
crumbled.Add(new SwitchBucket(_sortedCaseLabels, uncrumbled.StartLabelIndex, degenerateSplit - 1, isDegenerate: true));
crumbled.Add(new SwitchBucket(_sortedCaseLabels, degenerateSplit, uncrumbled.EndLabelIndex, isDegenerate: true));
break;
}
}
switchBucketsStack.Free();
return crumbled.ToImmutableAndFree();
}
private SwitchBucket CreateNextBucket(int startLabelIndex, int endLabelIndex)
{
Debug.Assert(startLabelIndex >= 0 && startLabelIndex <= endLabelIndex);
return new SwitchBucket(_sortedCaseLabels, startLabelIndex);
}
#endregion
#region "Switch bucket emit methods"
private void EmitSwitchBucketsLinearLeaf(ImmutableArray<SwitchBucket> switchBuckets, int low, int high)
{
for (int i = low; i < high; i++)
{
var nextBucketLabel = new object();
this.EmitSwitchBucket(switchBuckets[i], nextBucketLabel);
// nextBucketLabel:
_builder.MarkLabel(nextBucketLabel);
}
this.EmitSwitchBucket(switchBuckets[high], _fallThroughLabel);
}
private void EmitSwitchBuckets(ImmutableArray<SwitchBucket> switchBuckets, int low, int high)
{
// if (high - low + 1 <= LinearSearchThreshold)
if (high - low < LinearSearchThreshold)
{
this.EmitSwitchBucketsLinearLeaf(switchBuckets, low, high);
return;
}
// This way (0 1 2 3) will produce a mid of 2 while
// (0 1 2) will produce a mid of 1
// Now, the first half is first to mid-1
// and the second half is mid to last.
int mid = (low + high + 1) / 2;
object secondHalfLabel = new object();
// Emit a conditional branch to the second half
// before emitting the first half buckets.
ConstantValue pivotConstant = switchBuckets[mid - 1].EndConstant;
// if(key > midLabelConstant)
// goto secondHalfLabel;
this.EmitCondBranchForSwitch(
_keyTypeCode.IsUnsigned() ? ILOpCode.Bgt_un : ILOpCode.Bgt,
pivotConstant,
secondHalfLabel);
// Emit first half
this.EmitSwitchBuckets(switchBuckets, low, mid - 1);
// NOTE: Typically marking a synthetic label needs a hidden sequence point.
// NOTE: Otherwise if you step (F11) to this label debugger may highlight previous (lexically) statement.
// NOTE: We do not need a hidden point in this implementation since we do not interleave jump table
// NOTE: and cases so the "previous" statement will always be "switch".
// secondHalfLabel:
_builder.MarkLabel(secondHalfLabel);
// Emit second half
this.EmitSwitchBuckets(switchBuckets, mid, high);
}
private void EmitSwitchBucket(SwitchBucket switchBucket, object bucketFallThroughLabel)
{
if (switchBucket.LabelsCount == 1)
{
var c = switchBucket[0];
// if(key == constant)
// goto caseLabel;
ConstantValue constant = c.Key;
object caseLabel = c.Value;
this.EmitEqBranchForSwitch(constant, caseLabel);
}
else
{
if (switchBucket.IsDegenerate)
{
EmitRangeCheckedBranch(switchBucket.StartConstant, switchBucket.EndConstant, switchBucket[0].Value);
}
else
{
// Emit key normalized to startConstant (i.e. key - startConstant)
this.EmitNormalizedSwitchKey(switchBucket.StartConstant, switchBucket.EndConstant, bucketFallThroughLabel);
// Create the labels array for emitting a switch instruction for the bucket
object[] labels = this.CreateBucketLabels(switchBucket);
// switch (N, label1, label2... labelN)
// Emit the switch instruction
_builder.EmitSwitch(labels);
}
}
// goto fallThroughLabel;
_builder.EmitBranch(ILOpCode.Br, bucketFallThroughLabel);
}
private object[] CreateBucketLabels(SwitchBucket switchBucket)
{
// switch (N, t1, t2... tN)
// IL ==> ILOpCode.Switch < unsigned int32 > < int32 >... < int32 >
// For example: given a switch bucket [1, 3, 5] and FallThrough Label,
// we create the following labels array:
// { CaseLabel1, FallThrough, CaseLabel3, FallThrough, CaseLabel5 }
ConstantValue startConstant = switchBucket.StartConstant;
bool hasNegativeCaseLabels = startConstant.IsNegativeNumeric;
int nextCaseIndex = 0;
ulong nextCaseLabelNormalizedValue = 0;
ulong bucketSize = switchBucket.BucketSize;
object[] labels = new object[bucketSize];
for (ulong i = 0; i < bucketSize; ++i)
{
if (i == nextCaseLabelNormalizedValue)
{
labels[i] = switchBucket[nextCaseIndex].Value;
nextCaseIndex++;
if (nextCaseIndex >= switchBucket.LabelsCount)
{
Debug.Assert(i == bucketSize - 1);
break;
}
ConstantValue caseLabelConstant = switchBucket[nextCaseIndex].Key;
if (hasNegativeCaseLabels)
{
var nextCaseLabelValue = caseLabelConstant.Int64Value;
Debug.Assert(nextCaseLabelValue > startConstant.Int64Value);
nextCaseLabelNormalizedValue = (ulong)(nextCaseLabelValue - startConstant.Int64Value);
}
else
{
var nextCaseLabelValue = caseLabelConstant.UInt64Value;
Debug.Assert(nextCaseLabelValue > startConstant.UInt64Value);
nextCaseLabelNormalizedValue = nextCaseLabelValue - startConstant.UInt64Value;
}
continue;
}
labels[i] = _fallThroughLabel;
}
Debug.Assert(nextCaseIndex >= switchBucket.LabelsCount);
return labels;
}
#endregion
#region "Helper emit methods"
private void EmitCondBranchForSwitch(ILOpCode branchCode, ConstantValue constant, object targetLabel)
{
Debug.Assert(branchCode.IsBranch());
RoslynDebug.Assert(constant != null &&
SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(constant));
RoslynDebug.Assert(targetLabel != null);
// ldloc key
// ldc constant
// branch branchCode targetLabel
_builder.EmitLoad(_key);
_builder.EmitConstantValue(constant);
_builder.EmitBranch(branchCode, targetLabel, GetReverseBranchCode(branchCode));
}
private void EmitEqBranchForSwitch(ConstantValue constant, object targetLabel)
{
RoslynDebug.Assert(constant != null &&
SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(constant));
RoslynDebug.Assert(targetLabel != null);
_builder.EmitLoad(_key);
if (constant.IsDefaultValue)
{
// ldloc key
// brfalse targetLabel
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel);
}
else
{
_builder.EmitConstantValue(constant);
_builder.EmitBranch(ILOpCode.Beq, targetLabel);
}
}
private void EmitRangeCheckedBranch(ConstantValue startConstant, ConstantValue endConstant, object targetLabel)
{
_builder.EmitLoad(_key);
// Normalize the key to 0 if needed
// Emit: ldc constant
// sub
if (!startConstant.IsDefaultValue)
{
_builder.EmitConstantValue(startConstant);
_builder.EmitOpCode(ILOpCode.Sub);
}
if (_keyTypeCode.Is64BitIntegral())
{
_builder.EmitLongConstant(endConstant.Int64Value - startConstant.Int64Value);
}
else
{
int Int32Value(ConstantValue value)
{
// ConstantValue does not correctly convert byte and ushort values to int.
// It sign extends them rather than padding them. We compensate for that here.
// See also https://github.com/dotnet/roslyn/issues/18579
switch (value.Discriminator)
{
case ConstantValueTypeDiscriminator.Byte: return value.ByteValue;
case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value;
default: return value.Int32Value;
}
}
_builder.EmitIntConstant(Int32Value(endConstant) - Int32Value(startConstant));
}
_builder.EmitBranch(ILOpCode.Ble_un, targetLabel, ILOpCode.Bgt_un);
}
private static ILOpCode GetReverseBranchCode(ILOpCode branchCode)
{
switch (branchCode)
{
case ILOpCode.Beq:
return ILOpCode.Bne_un;
case ILOpCode.Blt:
return ILOpCode.Bge;
case ILOpCode.Blt_un:
return ILOpCode.Bge_un;
case ILOpCode.Bgt:
return ILOpCode.Ble;
case ILOpCode.Bgt_un:
return ILOpCode.Ble_un;
default:
throw ExceptionUtilities.UnexpectedValue(branchCode);
}
}
private void EmitNormalizedSwitchKey(ConstantValue startConstant, ConstantValue endConstant, object bucketFallThroughLabel)
{
_builder.EmitLoad(_key);
// Normalize the key to 0 if needed
// Emit: ldc constant
// sub
if (!startConstant.IsDefaultValue)
{
_builder.EmitConstantValue(startConstant);
_builder.EmitOpCode(ILOpCode.Sub);
}
// range-check normalized value if needed
EmitRangeCheckIfNeeded(startConstant, endConstant, bucketFallThroughLabel);
// truncate key to 32bit
_builder.EmitNumericConversion(_keyTypeCode, Microsoft.Cci.PrimitiveTypeCode.UInt32, false);
}
private void EmitRangeCheckIfNeeded(ConstantValue startConstant, ConstantValue endConstant, object bucketFallThroughLabel)
{
// switch treats key as an unsigned int.
// this ensures that normalization does not introduce [over|under]flows issues with 32bit or shorter keys.
// 64bit values, however must be checked before 32bit truncation happens.
if (_keyTypeCode.Is64BitIntegral())
{
// Dup(normalized);
// if ((ulong)(normalized) > (ulong)(endConstant - startConstant))
// {
// // not going to use it in the switch
// Pop(normalized);
// goto bucketFallThroughLabel;
// }
var inRangeLabel = new object();
_builder.EmitOpCode(ILOpCode.Dup);
_builder.EmitLongConstant(endConstant.Int64Value - startConstant.Int64Value);
_builder.EmitBranch(ILOpCode.Ble_un, inRangeLabel, ILOpCode.Bgt_un);
_builder.EmitOpCode(ILOpCode.Pop);
_builder.EmitBranch(ILOpCode.Br, bucketFallThroughLabel);
// If we get to inRangeLabel, we should have key on stack, adjust for that.
// builder cannot infer this since it has not seen all branches,
// but it will verify that our Adjustment is valid when more branches are known.
_builder.AdjustStack(+1);
_builder.MarkLabel(inRangeLabel);
}
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/DecimalKeywordRecommender.cs | // 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.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class DecimalKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public DecimalKeywordRecommender()
: base(SyntaxKind.DecimalKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsAnyExpressionContext ||
context.IsDefiniteCastTypeContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsObjectCreationTypeContext ||
(context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) ||
context.IsFunctionPointerTypeArgumentContext ||
context.IsIsOrAsTypeContext ||
context.IsLocalVariableDeclarationContext ||
context.IsFixedVariableDeclarationContext ||
context.IsParameterTypeContext ||
context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
context.IsLocalFunctionDeclarationContext ||
context.IsImplicitOrExplicitOperatorTypeContext ||
context.IsPrimaryFunctionExpressionContext ||
context.IsCrefContext ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
context.IsDelegateReturnTypeContext ||
syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsPossibleTupleContext ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
protected override SpecialType SpecialType => SpecialType.System_Decimal;
}
}
| // 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.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class DecimalKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public DecimalKeywordRecommender()
: base(SyntaxKind.DecimalKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsAnyExpressionContext ||
context.IsDefiniteCastTypeContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsObjectCreationTypeContext ||
(context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) ||
context.IsFunctionPointerTypeArgumentContext ||
context.IsIsOrAsTypeContext ||
context.IsLocalVariableDeclarationContext ||
context.IsFixedVariableDeclarationContext ||
context.IsParameterTypeContext ||
context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
context.IsLocalFunctionDeclarationContext ||
context.IsImplicitOrExplicitOperatorTypeContext ||
context.IsPrimaryFunctionExpressionContext ||
context.IsCrefContext ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
context.IsDelegateReturnTypeContext ||
syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsPossibleTupleContext ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
protected override SpecialType SpecialType => SpecialType.System_Decimal;
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/EditorFeatures/VisualBasic/Utilities/NamedTypeSymbolExtensions.vb | ' 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.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities
Friend Module NamedTypeSymbolExtensions
''' <summary>
''' Determines if the default constructor emitted by the compiler would contain an InitializeComponent() call.
''' </summary>
<Extension>
Public Function IsDesignerGeneratedTypeWithInitializeComponent(type As INamedTypeSymbol, compilation As Compilation) As Boolean
Dim designerGeneratedAttribute = compilation.DesignerGeneratedAttributeType()
If designerGeneratedAttribute Is Nothing Then
Return False
End If
If Not type.GetAttributes().Where(Function(a) Equals(a.AttributeClass, designerGeneratedAttribute)).Any() Then
Return False
End If
' We now need to see if we have an InitializeComponent that matches the pattern. This is
' the same check as in Semantics::IsInitializeComponent in the old compiler.
For Each baseType In type.GetBaseTypesAndThis()
Dim possibleInitializeComponent = baseType.GetMembers("InitializeComponent").OfType(Of IMethodSymbol).FirstOrDefault()
If possibleInitializeComponent IsNot Nothing AndAlso
possibleInitializeComponent.IsAccessibleWithin(type) AndAlso
Not possibleInitializeComponent.Parameters.Any() AndAlso
possibleInitializeComponent.ReturnsVoid AndAlso
Not possibleInitializeComponent.IsStatic Then
Return True
End If
Next
Return False
End Function
End Module
End Namespace
| ' 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.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities
Friend Module NamedTypeSymbolExtensions
''' <summary>
''' Determines if the default constructor emitted by the compiler would contain an InitializeComponent() call.
''' </summary>
<Extension>
Public Function IsDesignerGeneratedTypeWithInitializeComponent(type As INamedTypeSymbol, compilation As Compilation) As Boolean
Dim designerGeneratedAttribute = compilation.DesignerGeneratedAttributeType()
If designerGeneratedAttribute Is Nothing Then
Return False
End If
If Not type.GetAttributes().Where(Function(a) Equals(a.AttributeClass, designerGeneratedAttribute)).Any() Then
Return False
End If
' We now need to see if we have an InitializeComponent that matches the pattern. This is
' the same check as in Semantics::IsInitializeComponent in the old compiler.
For Each baseType In type.GetBaseTypesAndThis()
Dim possibleInitializeComponent = baseType.GetMembers("InitializeComponent").OfType(Of IMethodSymbol).FirstOrDefault()
If possibleInitializeComponent IsNot Nothing AndAlso
possibleInitializeComponent.IsAccessibleWithin(type) AndAlso
Not possibleInitializeComponent.Parameters.Any() AndAlso
possibleInitializeComponent.ReturnsVoid AndAlso
Not possibleInitializeComponent.IsStatic Then
Return True
End If
Next
Return False
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/VisualStudio/Core/Impl/Options/Style/AbstractCodeStyleOptionViewModel.cs | // 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.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options
{
/// <summary>
/// This class acts as a base for any view model that binds to the codestyle options UI.
/// </summary>
/// <remarks>
/// This supports databinding of:
/// Description
/// list of CodeStyle preferences
/// list of Notification preferences
/// selected code style preference
/// selected notification preference
/// plus, styling for visual elements.
/// </remarks>
internal abstract class AbstractCodeStyleOptionViewModel : AbstractNotifyPropertyChanged
{
protected AbstractOptionPreviewViewModel Info { get; }
public IOption Option { get; }
public string Description { get; set; }
public double DescriptionMargin { get; set; } = 12d;
public string GroupName { get; set; }
public string GroupNameAndDescription { get; set; }
public List<CodeStylePreference> Preferences { get; set; }
public List<NotificationOptionViewModel> NotificationPreferences { get; set; }
public abstract CodeStylePreference SelectedPreference { get; set; }
public abstract string GetPreview();
public virtual NotificationOptionViewModel SelectedNotificationPreference
{
get { return NotificationPreferences.First(); }
set { }
}
public AbstractCodeStyleOptionViewModel(
IOption option,
string description,
AbstractOptionPreviewViewModel info,
string groupName,
List<CodeStylePreference> preferences = null,
List<NotificationOptionViewModel> notificationPreferences = null)
{
Info = info;
Option = option;
Description = description;
Preferences = preferences ?? GetDefaultPreferences();
NotificationPreferences = notificationPreferences ?? GetDefaultNotifications();
GroupName = groupName;
GroupNameAndDescription = $"{groupName}, {description}";
}
private static List<NotificationOptionViewModel> GetDefaultNotifications()
{
return new List<NotificationOptionViewModel>
{
new NotificationOptionViewModel(NotificationOption.Silent, KnownMonikers.None),
new NotificationOptionViewModel(NotificationOption.Suggestion, KnownMonikers.StatusInformation),
new NotificationOptionViewModel(NotificationOption.Warning, KnownMonikers.StatusWarning),
new NotificationOptionViewModel(NotificationOption.Error, KnownMonikers.StatusError)
};
}
private static List<CodeStylePreference> GetDefaultPreferences()
{
return new List<CodeStylePreference>
{
new CodeStylePreference(ServicesVSResources.Yes, isChecked: true),
new CodeStylePreference(ServicesVSResources.No, isChecked: false),
};
}
}
}
| // 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.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options
{
/// <summary>
/// This class acts as a base for any view model that binds to the codestyle options UI.
/// </summary>
/// <remarks>
/// This supports databinding of:
/// Description
/// list of CodeStyle preferences
/// list of Notification preferences
/// selected code style preference
/// selected notification preference
/// plus, styling for visual elements.
/// </remarks>
internal abstract class AbstractCodeStyleOptionViewModel : AbstractNotifyPropertyChanged
{
protected AbstractOptionPreviewViewModel Info { get; }
public IOption Option { get; }
public string Description { get; set; }
public double DescriptionMargin { get; set; } = 12d;
public string GroupName { get; set; }
public string GroupNameAndDescription { get; set; }
public List<CodeStylePreference> Preferences { get; set; }
public List<NotificationOptionViewModel> NotificationPreferences { get; set; }
public abstract CodeStylePreference SelectedPreference { get; set; }
public abstract string GetPreview();
public virtual NotificationOptionViewModel SelectedNotificationPreference
{
get { return NotificationPreferences.First(); }
set { }
}
public AbstractCodeStyleOptionViewModel(
IOption option,
string description,
AbstractOptionPreviewViewModel info,
string groupName,
List<CodeStylePreference> preferences = null,
List<NotificationOptionViewModel> notificationPreferences = null)
{
Info = info;
Option = option;
Description = description;
Preferences = preferences ?? GetDefaultPreferences();
NotificationPreferences = notificationPreferences ?? GetDefaultNotifications();
GroupName = groupName;
GroupNameAndDescription = $"{groupName}, {description}";
}
private static List<NotificationOptionViewModel> GetDefaultNotifications()
{
return new List<NotificationOptionViewModel>
{
new NotificationOptionViewModel(NotificationOption.Silent, KnownMonikers.None),
new NotificationOptionViewModel(NotificationOption.Suggestion, KnownMonikers.StatusInformation),
new NotificationOptionViewModel(NotificationOption.Warning, KnownMonikers.StatusWarning),
new NotificationOptionViewModel(NotificationOption.Error, KnownMonikers.StatusError)
};
}
private static List<CodeStylePreference> GetDefaultPreferences()
{
return new List<CodeStylePreference>
{
new CodeStylePreference(ServicesVSResources.Yes, isChecked: true),
new CodeStylePreference(ServicesVSResources.No, isChecked: false),
};
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Workspaces/Core/Portable/FindSymbols/SymbolFinder_Helpers.cs | // 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
public static partial class SymbolFinder
{
private static bool IsAccessible(ISymbol symbol)
{
if (symbol.Locations.Any(l => l.IsInMetadata))
{
var accessibility = symbol.DeclaredAccessibility;
return accessibility == Accessibility.Public ||
accessibility == Accessibility.Protected ||
accessibility == Accessibility.ProtectedOrInternal;
}
return true;
}
internal static async Task<bool> OriginalSymbolsMatchAsync(
Solution solution,
ISymbol searchSymbol,
ISymbol? symbolToMatch,
CancellationToken cancellationToken)
{
if (ReferenceEquals(searchSymbol, symbolToMatch))
return true;
if (searchSymbol == null || symbolToMatch == null)
return false;
// Avoid the expensive checks if we can fast path when the compiler just says these are equal. Also, for the
// purposes of symbol finding nullability of symbols doesn't affect things, so just use the default
// comparison.
if (searchSymbol.Equals(symbolToMatch))
return true;
if (await OriginalSymbolsMatchCoreAsync(solution, searchSymbol, symbolToMatch, cancellationToken).ConfigureAwait(false))
return true;
if (searchSymbol.Kind == SymbolKind.Namespace && symbolToMatch.Kind == SymbolKind.Namespace)
{
// if one of them is a merged namespace symbol and other one is its constituent namespace symbol, they are equivalent.
var namespace1 = (INamespaceSymbol)searchSymbol;
var namespace2 = (INamespaceSymbol)symbolToMatch;
var namespace1Count = namespace1.ConstituentNamespaces.Length;
var namespace2Count = namespace2.ConstituentNamespaces.Length;
if (namespace1Count != namespace2Count)
{
if ((namespace1Count > 1 && await namespace1.ConstituentNamespaces.AnyAsync(static (n, arg) => NamespaceSymbolsMatchAsync(arg.solution, n, arg.namespace2, arg.cancellationToken), (solution, namespace2, cancellationToken)).ConfigureAwait(false)) ||
(namespace2Count > 1 && await namespace2.ConstituentNamespaces.AnyAsync(static (n2, arg) => NamespaceSymbolsMatchAsync(arg.solution, arg.namespace1, n2, arg.cancellationToken), (solution, namespace1, cancellationToken)).ConfigureAwait(false)))
{
return true;
}
}
}
return false;
}
private static async Task<bool> OriginalSymbolsMatchCoreAsync(
Solution solution,
ISymbol searchSymbol,
ISymbol symbolToMatch,
CancellationToken cancellationToken)
{
if (searchSymbol == null || symbolToMatch == null)
return false;
searchSymbol = searchSymbol.GetOriginalUnreducedDefinition();
symbolToMatch = symbolToMatch.GetOriginalUnreducedDefinition();
// Avoid the expensive checks if we can fast path when the compiler just says these are equal. Also, for the
// purposes of symbol finding nullability of symbols doesn't affect things, so just use the default
// comparison.
if (searchSymbol.Equals(symbolToMatch, SymbolEqualityComparer.Default))
return true;
// We compare the given searchSymbol and symbolToMatch for equivalence using SymbolEquivalenceComparer
// as follows:
// 1) We compare the given symbols using the SymbolEquivalenceComparer.IgnoreAssembliesInstance,
// which ignores the containing assemblies for named types equivalence checks. This is required
// to handle equivalent named types which are forwarded to completely different assemblies.
// 2) If the symbols are NOT equivalent ignoring assemblies, then they cannot be equivalent.
// 3) Otherwise, if the symbols ARE equivalent ignoring assemblies, they may or may not be equivalent
// if containing assemblies are NOT ignored. We need to perform additional checks to ensure they
// are indeed equivalent:
//
// (a) If IgnoreAssembliesInstance.Equals equivalence visitor encountered any pair of non-nested
// named types which were equivalent in all aspects, except that they resided in different
// assemblies, we need to ensure that all such pairs are indeed equivalent types. Such a pair
// of named types is equivalent if and only if one of them is a type defined in either
// searchSymbolCompilation(C1) or symbolToMatchCompilation(C2), say defined in reference assembly
// A (version v1) in compilation C1, and the other type is a forwarded type, such that it is
// forwarded from reference assembly A (version v2) to assembly B in compilation C2.
// (b) Otherwise, if no such named type pairs were encountered, symbols ARE equivalent.
using var _ = PooledDictionary<INamedTypeSymbol, INamedTypeSymbol>.GetInstance(out var equivalentTypesWithDifferingAssemblies);
// 1) Compare searchSymbol and symbolToMatch using SymbolEquivalenceComparer.IgnoreAssembliesInstance
if (!SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(searchSymbol, symbolToMatch, equivalentTypesWithDifferingAssemblies))
{
// 2) If the symbols are NOT equivalent ignoring assemblies, then they cannot be equivalent.
return false;
}
// 3) If the symbols ARE equivalent ignoring assemblies, they may or may not be equivalent if containing assemblies are NOT ignored.
if (equivalentTypesWithDifferingAssemblies.Count > 0)
{
// Step 3a) Ensure that all pairs of named types in equivalentTypesWithDifferingAssemblies are indeed equivalent types.
return await VerifyForwardedTypesAsync(solution, equivalentTypesWithDifferingAssemblies, cancellationToken).ConfigureAwait(false);
}
// 3b) If no such named type pairs were encountered, symbols ARE equivalent.
return true;
}
private static Task<bool> NamespaceSymbolsMatchAsync(
Solution solution,
INamespaceSymbol namespace1,
INamespaceSymbol namespace2,
CancellationToken cancellationToken)
{
return OriginalSymbolsMatchAsync(solution, namespace1, namespace2, cancellationToken);
}
/// <summary>
/// Verifies that all pairs of named types in equivalentTypesWithDifferingAssemblies are equivalent forwarded types.
/// </summary>
private static async Task<bool> VerifyForwardedTypesAsync(
Solution solution,
Dictionary<INamedTypeSymbol, INamedTypeSymbol> equivalentTypesWithDifferingAssemblies,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(equivalentTypesWithDifferingAssemblies);
Contract.ThrowIfTrue(!equivalentTypesWithDifferingAssemblies.Any());
// Must contain equivalents named types residing in different assemblies.
Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => !SymbolEquivalenceComparer.Instance.Equals(kvp.Key.ContainingAssembly, kvp.Value.ContainingAssembly)));
// Must contain non-nested named types.
Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Key.ContainingType == null));
Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Value.ContainingType == null));
// Cache compilations so we avoid recreating any as we walk the pairs of types.
using var _ = PooledHashSet<Compilation>.GetInstance(out var compilationSet);
foreach (var (type1, type2) in equivalentTypesWithDifferingAssemblies)
{
// Check if type1 was forwarded to type2 in type2's compilation, or if type2 was forwarded to type1 in
// type1's compilation. We check both direction as this API is called from higher level comparison APIs
// that are unordered.
if (!await VerifyForwardedTypeAsync(solution, candidate: type1, forwardedTo: type2, compilationSet, cancellationToken).ConfigureAwait(false) &&
!await VerifyForwardedTypeAsync(solution, candidate: type2, forwardedTo: type1, compilationSet, cancellationToken).ConfigureAwait(false))
{
return false;
}
}
return true;
}
/// <summary>
/// Returns <see langword="true"/> if <paramref name="candidate"/> was forwarded to <paramref name="forwardedTo"/> in
/// <paramref name="forwardedTo"/>'s <see cref="Compilation"/>.
/// </summary>
private static async Task<bool> VerifyForwardedTypeAsync(
Solution solution,
INamedTypeSymbol candidate,
INamedTypeSymbol forwardedTo,
HashSet<Compilation> compilationSet,
CancellationToken cancellationToken)
{
// Only need to operate on original definitions. i.e. List<T> is the type that is forwarded,
// not List<string>.
candidate = GetOridinalUnderlyingType(candidate);
forwardedTo = GetOridinalUnderlyingType(forwardedTo);
var forwardedToOriginatingProject = solution.GetOriginatingProject(forwardedTo);
if (forwardedToOriginatingProject == null)
return false;
var forwardedToCompilation = await forwardedToOriginatingProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false);
if (forwardedToCompilation == null)
return false;
// Cache the compilation so that if we need it while checking another set of forwarded types, we don't
// expensively throw it away and recreate it.
compilationSet.Add(forwardedToCompilation);
var candidateFullMetadataName = candidate.ContainingNamespace?.IsGlobalNamespace != false
? candidate.MetadataName
: $"{candidate.ContainingNamespace.ToDisplayString(SymbolDisplayFormats.SignatureFormat)}.{candidate.MetadataName}";
// Now, find the corresponding reference to type1's assembly in type2's compilation and see if that assembly
// contains a forward that matches type2. If so, type1 was forwarded to type2.
var candidateAssemblyName = candidate.ContainingAssembly.Name;
foreach (var assembly in forwardedToCompilation.GetReferencedAssemblySymbols())
{
if (assembly.Name == candidateAssemblyName)
{
var resolvedType = assembly.ResolveForwardedType(candidateFullMetadataName);
if (Equals(resolvedType, forwardedTo))
return true;
}
}
return false;
}
private static INamedTypeSymbol GetOridinalUnderlyingType(INamedTypeSymbol type)
=> (type.NativeIntegerUnderlyingType ?? type).OriginalDefinition;
}
}
| // 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
public static partial class SymbolFinder
{
private static bool IsAccessible(ISymbol symbol)
{
if (symbol.Locations.Any(l => l.IsInMetadata))
{
var accessibility = symbol.DeclaredAccessibility;
return accessibility == Accessibility.Public ||
accessibility == Accessibility.Protected ||
accessibility == Accessibility.ProtectedOrInternal;
}
return true;
}
internal static async Task<bool> OriginalSymbolsMatchAsync(
Solution solution,
ISymbol searchSymbol,
ISymbol? symbolToMatch,
CancellationToken cancellationToken)
{
if (ReferenceEquals(searchSymbol, symbolToMatch))
return true;
if (searchSymbol == null || symbolToMatch == null)
return false;
// Avoid the expensive checks if we can fast path when the compiler just says these are equal. Also, for the
// purposes of symbol finding nullability of symbols doesn't affect things, so just use the default
// comparison.
if (searchSymbol.Equals(symbolToMatch))
return true;
if (await OriginalSymbolsMatchCoreAsync(solution, searchSymbol, symbolToMatch, cancellationToken).ConfigureAwait(false))
return true;
if (searchSymbol.Kind == SymbolKind.Namespace && symbolToMatch.Kind == SymbolKind.Namespace)
{
// if one of them is a merged namespace symbol and other one is its constituent namespace symbol, they are equivalent.
var namespace1 = (INamespaceSymbol)searchSymbol;
var namespace2 = (INamespaceSymbol)symbolToMatch;
var namespace1Count = namespace1.ConstituentNamespaces.Length;
var namespace2Count = namespace2.ConstituentNamespaces.Length;
if (namespace1Count != namespace2Count)
{
if ((namespace1Count > 1 && await namespace1.ConstituentNamespaces.AnyAsync(static (n, arg) => NamespaceSymbolsMatchAsync(arg.solution, n, arg.namespace2, arg.cancellationToken), (solution, namespace2, cancellationToken)).ConfigureAwait(false)) ||
(namespace2Count > 1 && await namespace2.ConstituentNamespaces.AnyAsync(static (n2, arg) => NamespaceSymbolsMatchAsync(arg.solution, arg.namespace1, n2, arg.cancellationToken), (solution, namespace1, cancellationToken)).ConfigureAwait(false)))
{
return true;
}
}
}
return false;
}
private static async Task<bool> OriginalSymbolsMatchCoreAsync(
Solution solution,
ISymbol searchSymbol,
ISymbol symbolToMatch,
CancellationToken cancellationToken)
{
if (searchSymbol == null || symbolToMatch == null)
return false;
searchSymbol = searchSymbol.GetOriginalUnreducedDefinition();
symbolToMatch = symbolToMatch.GetOriginalUnreducedDefinition();
// Avoid the expensive checks if we can fast path when the compiler just says these are equal. Also, for the
// purposes of symbol finding nullability of symbols doesn't affect things, so just use the default
// comparison.
if (searchSymbol.Equals(symbolToMatch, SymbolEqualityComparer.Default))
return true;
// We compare the given searchSymbol and symbolToMatch for equivalence using SymbolEquivalenceComparer
// as follows:
// 1) We compare the given symbols using the SymbolEquivalenceComparer.IgnoreAssembliesInstance,
// which ignores the containing assemblies for named types equivalence checks. This is required
// to handle equivalent named types which are forwarded to completely different assemblies.
// 2) If the symbols are NOT equivalent ignoring assemblies, then they cannot be equivalent.
// 3) Otherwise, if the symbols ARE equivalent ignoring assemblies, they may or may not be equivalent
// if containing assemblies are NOT ignored. We need to perform additional checks to ensure they
// are indeed equivalent:
//
// (a) If IgnoreAssembliesInstance.Equals equivalence visitor encountered any pair of non-nested
// named types which were equivalent in all aspects, except that they resided in different
// assemblies, we need to ensure that all such pairs are indeed equivalent types. Such a pair
// of named types is equivalent if and only if one of them is a type defined in either
// searchSymbolCompilation(C1) or symbolToMatchCompilation(C2), say defined in reference assembly
// A (version v1) in compilation C1, and the other type is a forwarded type, such that it is
// forwarded from reference assembly A (version v2) to assembly B in compilation C2.
// (b) Otherwise, if no such named type pairs were encountered, symbols ARE equivalent.
using var _ = PooledDictionary<INamedTypeSymbol, INamedTypeSymbol>.GetInstance(out var equivalentTypesWithDifferingAssemblies);
// 1) Compare searchSymbol and symbolToMatch using SymbolEquivalenceComparer.IgnoreAssembliesInstance
if (!SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(searchSymbol, symbolToMatch, equivalentTypesWithDifferingAssemblies))
{
// 2) If the symbols are NOT equivalent ignoring assemblies, then they cannot be equivalent.
return false;
}
// 3) If the symbols ARE equivalent ignoring assemblies, they may or may not be equivalent if containing assemblies are NOT ignored.
if (equivalentTypesWithDifferingAssemblies.Count > 0)
{
// Step 3a) Ensure that all pairs of named types in equivalentTypesWithDifferingAssemblies are indeed equivalent types.
return await VerifyForwardedTypesAsync(solution, equivalentTypesWithDifferingAssemblies, cancellationToken).ConfigureAwait(false);
}
// 3b) If no such named type pairs were encountered, symbols ARE equivalent.
return true;
}
private static Task<bool> NamespaceSymbolsMatchAsync(
Solution solution,
INamespaceSymbol namespace1,
INamespaceSymbol namespace2,
CancellationToken cancellationToken)
{
return OriginalSymbolsMatchAsync(solution, namespace1, namespace2, cancellationToken);
}
/// <summary>
/// Verifies that all pairs of named types in equivalentTypesWithDifferingAssemblies are equivalent forwarded types.
/// </summary>
private static async Task<bool> VerifyForwardedTypesAsync(
Solution solution,
Dictionary<INamedTypeSymbol, INamedTypeSymbol> equivalentTypesWithDifferingAssemblies,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(equivalentTypesWithDifferingAssemblies);
Contract.ThrowIfTrue(!equivalentTypesWithDifferingAssemblies.Any());
// Must contain equivalents named types residing in different assemblies.
Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => !SymbolEquivalenceComparer.Instance.Equals(kvp.Key.ContainingAssembly, kvp.Value.ContainingAssembly)));
// Must contain non-nested named types.
Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Key.ContainingType == null));
Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Value.ContainingType == null));
// Cache compilations so we avoid recreating any as we walk the pairs of types.
using var _ = PooledHashSet<Compilation>.GetInstance(out var compilationSet);
foreach (var (type1, type2) in equivalentTypesWithDifferingAssemblies)
{
// Check if type1 was forwarded to type2 in type2's compilation, or if type2 was forwarded to type1 in
// type1's compilation. We check both direction as this API is called from higher level comparison APIs
// that are unordered.
if (!await VerifyForwardedTypeAsync(solution, candidate: type1, forwardedTo: type2, compilationSet, cancellationToken).ConfigureAwait(false) &&
!await VerifyForwardedTypeAsync(solution, candidate: type2, forwardedTo: type1, compilationSet, cancellationToken).ConfigureAwait(false))
{
return false;
}
}
return true;
}
/// <summary>
/// Returns <see langword="true"/> if <paramref name="candidate"/> was forwarded to <paramref name="forwardedTo"/> in
/// <paramref name="forwardedTo"/>'s <see cref="Compilation"/>.
/// </summary>
private static async Task<bool> VerifyForwardedTypeAsync(
Solution solution,
INamedTypeSymbol candidate,
INamedTypeSymbol forwardedTo,
HashSet<Compilation> compilationSet,
CancellationToken cancellationToken)
{
// Only need to operate on original definitions. i.e. List<T> is the type that is forwarded,
// not List<string>.
candidate = GetOridinalUnderlyingType(candidate);
forwardedTo = GetOridinalUnderlyingType(forwardedTo);
var forwardedToOriginatingProject = solution.GetOriginatingProject(forwardedTo);
if (forwardedToOriginatingProject == null)
return false;
var forwardedToCompilation = await forwardedToOriginatingProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false);
if (forwardedToCompilation == null)
return false;
// Cache the compilation so that if we need it while checking another set of forwarded types, we don't
// expensively throw it away and recreate it.
compilationSet.Add(forwardedToCompilation);
var candidateFullMetadataName = candidate.ContainingNamespace?.IsGlobalNamespace != false
? candidate.MetadataName
: $"{candidate.ContainingNamespace.ToDisplayString(SymbolDisplayFormats.SignatureFormat)}.{candidate.MetadataName}";
// Now, find the corresponding reference to type1's assembly in type2's compilation and see if that assembly
// contains a forward that matches type2. If so, type1 was forwarded to type2.
var candidateAssemblyName = candidate.ContainingAssembly.Name;
foreach (var assembly in forwardedToCompilation.GetReferencedAssemblySymbols())
{
if (assembly.Name == candidateAssemblyName)
{
var resolvedType = assembly.ResolveForwardedType(candidateFullMetadataName);
if (Equals(resolvedType, forwardedTo))
return true;
}
}
return false;
}
private static INamedTypeSymbol GetOridinalUnderlyingType(INamedTypeSymbol type)
=> (type.NativeIntegerUnderlyingType ?? type).OriginalDefinition;
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/CSharp/Portable/Symbols/AliasSymbol.cs | // 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.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Symbol representing a using alias appearing in a compilation unit or within a namespace
/// declaration. Generally speaking, these symbols do not appear in the set of symbols reachable
/// from the unnamed namespace declaration. In other words, when a using alias is used in a
/// program, it acts as a transparent alias, and the symbol to which it is an alias is used in
/// the symbol table. For example, in the source code
/// <pre>
/// namespace NS
/// {
/// using o = System.Object;
/// partial class C : o {}
/// partial class C : object {}
/// partial class C : System.Object {}
/// }
/// </pre>
/// all three declarations for class C are equivalent and result in the same symbol table object
/// for C. However, these using alias symbols do appear in the results of certain SemanticModel
/// APIs. Specifically, for the base clause of the first of C's class declarations, the
/// following APIs may produce a result that contains an AliasSymbol:
/// <pre>
/// SemanticInfo SemanticModel.GetSemanticInfo(ExpressionSyntax expression);
/// SemanticInfo SemanticModel.BindExpression(CSharpSyntaxNode location, ExpressionSyntax expression);
/// SemanticInfo SemanticModel.BindType(CSharpSyntaxNode location, ExpressionSyntax type);
/// SemanticInfo SemanticModel.BindNamespaceOrType(CSharpSyntaxNode location, ExpressionSyntax type);
/// </pre>
/// Also, the following are affected if container==null (and, for the latter, when arity==null
/// or arity==0):
/// <pre>
/// IList<string> SemanticModel.LookupNames(CSharpSyntaxNode location, NamespaceOrTypeSymbol container = null, LookupOptions options = LookupOptions.Default, List<string> result = null);
/// IList<Symbol> SemanticModel.LookupSymbols(CSharpSyntaxNode location, NamespaceOrTypeSymbol container = null, string name = null, int? arity = null, LookupOptions options = LookupOptions.Default, List<Symbol> results = null);
/// </pre>
/// </summary>
internal abstract class AliasSymbol : Symbol
{
private readonly ImmutableArray<Location> _locations; // NOTE: can be empty for the "global" alias.
private readonly string _aliasName;
private readonly bool _isExtern;
private readonly Symbol? _containingSymbol;
protected AliasSymbol(string aliasName, Symbol? containingSymbol, ImmutableArray<Location> locations, bool isExtern)
{
Debug.Assert(locations.Length == 1 || (locations.IsEmpty && aliasName == "global")); // It looks like equality implementation depends on this condition.
_locations = locations;
_aliasName = aliasName;
_isExtern = isExtern;
_containingSymbol = containingSymbol;
}
// For the purposes of SemanticModel, it is convenient to have an AliasSymbol for the "global" namespace that "global::" binds
// to. This alias symbol is returned only when binding "global::" (special case code).
internal static AliasSymbol CreateGlobalNamespaceAlias(NamespaceSymbol globalNamespace)
{
return new AliasSymbolFromResolvedTarget(globalNamespace, "global", globalNamespace, ImmutableArray<Location>.Empty, isExtern: false);
}
internal static AliasSymbol CreateCustomDebugInfoAlias(NamespaceOrTypeSymbol targetSymbol, SyntaxToken aliasToken, Symbol? containingSymbol, bool isExtern)
{
return new AliasSymbolFromResolvedTarget(targetSymbol, aliasToken.ValueText, containingSymbol, ImmutableArray.Create(aliasToken.GetLocation()), isExtern);
}
internal AliasSymbol ToNewSubmission(CSharpCompilation compilation)
{
// We can pass basesBeingResolved: null because base type cycles can't cross
// submission boundaries - there's no way to depend on a subsequent submission.
var previousTarget = Target;
if (previousTarget.Kind != SymbolKind.Namespace)
{
return this;
}
var expandedGlobalNamespace = compilation.GlobalNamespace;
var expandedNamespace = Imports.ExpandPreviousSubmissionNamespace((NamespaceSymbol)previousTarget, expandedGlobalNamespace);
return new AliasSymbolFromResolvedTarget(expandedNamespace, Name, ContainingSymbol, _locations, _isExtern);
}
public sealed override string Name
{
get
{
return _aliasName;
}
}
public override SymbolKind Kind
{
get
{
return SymbolKind.Alias;
}
}
/// <summary>
/// Gets the <see cref="NamespaceOrTypeSymbol"/> for the
/// namespace or type referenced by the alias.
/// </summary>
public abstract NamespaceOrTypeSymbol Target
{
get;
}
public override ImmutableArray<Location> Locations
{
get
{
return _locations;
}
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return GetDeclaringSyntaxReferenceHelper<UsingDirectiveSyntax>(_locations);
}
}
public sealed override bool IsExtern
{
get
{
return _isExtern;
}
}
public override bool IsSealed
{
get
{
return false;
}
}
public override bool IsAbstract
{
get
{
return false;
}
}
public override bool IsOverride
{
get
{
return false;
}
}
public override bool IsVirtual
{
get
{
return false;
}
}
public override bool IsStatic
{
get
{
return false;
}
}
/// <summary>
/// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute.
/// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet.
/// </summary>
internal sealed override ObsoleteAttributeData? ObsoleteAttributeData
{
get { return null; }
}
public override Accessibility DeclaredAccessibility
{
get
{
return Accessibility.NotApplicable;
}
}
/// <summary>
/// Using aliases in C# are always contained within a namespace declaration, or at the top
/// level within a compilation unit, within the implicit unnamed namespace declaration. We
/// return that as the "containing" symbol, even though the alias isn't a member of the
/// namespace as such.
/// </summary>
public sealed override Symbol? ContainingSymbol
{
get
{
return _containingSymbol;
}
}
internal override TResult Accept<TArg, TResult>(CSharpSymbolVisitor<TArg, TResult> visitor, TArg a)
{
return visitor.VisitAlias(this, a);
}
public override void Accept(CSharpSymbolVisitor visitor)
{
visitor.VisitAlias(this);
}
public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor)
{
return visitor.VisitAlias(this);
}
// basesBeingResolved is only used to break circular references.
internal abstract NamespaceOrTypeSymbol GetAliasTarget(ConsList<TypeSymbol>? basesBeingResolved);
internal void CheckConstraints(BindingDiagnosticBag diagnostics)
{
var target = this.Target as TypeSymbol;
if ((object?)target != null && Locations.Length > 0)
{
var corLibrary = this.ContainingAssembly.CorLibrary;
var conversions = new TypeConversions(corLibrary);
target.CheckAllConstraints(DeclaringCompilation, conversions, Locations[0], diagnostics);
}
}
public override bool Equals(Symbol? obj, TypeCompareKind compareKind)
{
if (ReferenceEquals(this, obj))
{
return true;
}
if (ReferenceEquals(obj, null))
{
return false;
}
AliasSymbol? other = obj as AliasSymbol;
return (object?)other != null &&
Equals(this.Locations.FirstOrDefault(), other.Locations.FirstOrDefault()) &&
this.ContainingAssembly.Equals(other.ContainingAssembly, compareKind);
}
public override int GetHashCode()
{
if (this.Locations.Length > 0)
return this.Locations.First().GetHashCode();
else
return Name.GetHashCode();
}
internal abstract override bool RequiresCompletion
{
get;
}
protected override ISymbol CreateISymbol()
{
return new PublicModel.AliasSymbol(this);
}
}
internal sealed class AliasSymbolFromSyntax : AliasSymbol
{
private readonly SyntaxReference _directive;
private SymbolCompletionState _state;
private NamespaceOrTypeSymbol? _aliasTarget;
// lazy binding
private BindingDiagnosticBag? _aliasTargetDiagnostics;
internal AliasSymbolFromSyntax(SourceNamespaceSymbol containingSymbol, UsingDirectiveSyntax syntax)
: base(syntax.Alias!.Name.Identifier.ValueText, containingSymbol, ImmutableArray.Create(syntax.Alias!.Name.Identifier.GetLocation()), isExtern: false)
{
Debug.Assert(syntax.Alias is object);
_directive = syntax.GetReference();
}
internal AliasSymbolFromSyntax(SourceNamespaceSymbol containingSymbol, ExternAliasDirectiveSyntax syntax)
: base(syntax.Identifier.ValueText, containingSymbol, ImmutableArray.Create(syntax.Identifier.GetLocation()), isExtern: true)
{
_directive = syntax.GetReference();
}
/// <summary>
/// Gets the <see cref="NamespaceOrTypeSymbol"/> for the
/// namespace or type referenced by the alias.
/// </summary>
public override NamespaceOrTypeSymbol Target
{
get
{
return GetAliasTarget(basesBeingResolved: null);
}
}
// basesBeingResolved is only used to break circular references.
internal override NamespaceOrTypeSymbol GetAliasTarget(ConsList<TypeSymbol>? basesBeingResolved)
{
if (!_state.HasComplete(CompletionPart.AliasTarget))
{
// the target is not yet bound. If it is an ordinary alias, bind the target
// symbol. If it is an extern alias then find the target in the list of metadata references.
var newDiagnostics = BindingDiagnosticBag.GetInstance();
NamespaceOrTypeSymbol symbol = this.IsExtern ?
ResolveExternAliasTarget(newDiagnostics) :
ResolveAliasTarget(((UsingDirectiveSyntax)_directive.GetSyntax()).Name, newDiagnostics, basesBeingResolved);
if ((object?)Interlocked.CompareExchange(ref _aliasTarget, symbol, null) == null)
{
// Note: It's important that we don't call newDiagnosticsToReadOnlyAndFree here. That call
// can force the prompt evaluation of lazy initialized diagnostics. That in turn can
// call back into GetAliasTarget on the same thread resulting in a dead lock scenario.
bool won = Interlocked.Exchange(ref _aliasTargetDiagnostics, newDiagnostics) == null;
Debug.Assert(won, "Only one thread can win the alias target CompareExchange");
_state.NotePartComplete(CompletionPart.AliasTarget);
// we do not clear this.aliasTargetName, as another thread might be about to use it for ResolveAliasTarget(...)
}
else
{
newDiagnostics.Free();
// Wait for diagnostics to have been reported if another thread resolves the alias
_state.SpinWaitComplete(CompletionPart.AliasTarget, default(CancellationToken));
}
}
return _aliasTarget!;
}
internal BindingDiagnosticBag AliasTargetDiagnostics
{
get
{
GetAliasTarget(null);
RoslynDebug.Assert(_aliasTargetDiagnostics != null);
return _aliasTargetDiagnostics;
}
}
private NamespaceSymbol ResolveExternAliasTarget(BindingDiagnosticBag diagnostics)
{
NamespaceSymbol? target;
if (!ContainingSymbol!.DeclaringCompilation.GetExternAliasTarget(Name, out target))
{
diagnostics.Add(ErrorCode.ERR_BadExternAlias, Locations[0], Name);
}
RoslynDebug.Assert(target is object);
RoslynDebug.Assert(target.IsGlobalNamespace);
return target;
}
private NamespaceOrTypeSymbol ResolveAliasTarget(NameSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol>? basesBeingResolved)
{
var declarationBinder = ContainingSymbol!.DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder(syntax).WithAdditionalFlags(BinderFlags.SuppressConstraintChecks | BinderFlags.SuppressObsoleteChecks);
return declarationBinder.BindNamespaceOrTypeSymbol(syntax, diagnostics, basesBeingResolved).NamespaceOrTypeSymbol;
}
internal override bool RequiresCompletion
{
get { return true; }
}
}
internal sealed class AliasSymbolFromResolvedTarget : AliasSymbol
{
private readonly NamespaceOrTypeSymbol _aliasTarget;
internal AliasSymbolFromResolvedTarget(NamespaceOrTypeSymbol target, string aliasName, Symbol? containingSymbol, ImmutableArray<Location> locations, bool isExtern)
: base(aliasName, containingSymbol, locations, isExtern)
{
_aliasTarget = target;
}
/// <summary>
/// Gets the <see cref="NamespaceOrTypeSymbol"/> for the
/// namespace or type referenced by the alias.
/// </summary>
public override NamespaceOrTypeSymbol Target
{
get
{
return _aliasTarget;
}
}
internal override NamespaceOrTypeSymbol GetAliasTarget(ConsList<TypeSymbol>? basesBeingResolved)
{
return _aliasTarget;
}
internal override bool RequiresCompletion
{
get { return false; }
}
}
}
| // 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.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Symbol representing a using alias appearing in a compilation unit or within a namespace
/// declaration. Generally speaking, these symbols do not appear in the set of symbols reachable
/// from the unnamed namespace declaration. In other words, when a using alias is used in a
/// program, it acts as a transparent alias, and the symbol to which it is an alias is used in
/// the symbol table. For example, in the source code
/// <pre>
/// namespace NS
/// {
/// using o = System.Object;
/// partial class C : o {}
/// partial class C : object {}
/// partial class C : System.Object {}
/// }
/// </pre>
/// all three declarations for class C are equivalent and result in the same symbol table object
/// for C. However, these using alias symbols do appear in the results of certain SemanticModel
/// APIs. Specifically, for the base clause of the first of C's class declarations, the
/// following APIs may produce a result that contains an AliasSymbol:
/// <pre>
/// SemanticInfo SemanticModel.GetSemanticInfo(ExpressionSyntax expression);
/// SemanticInfo SemanticModel.BindExpression(CSharpSyntaxNode location, ExpressionSyntax expression);
/// SemanticInfo SemanticModel.BindType(CSharpSyntaxNode location, ExpressionSyntax type);
/// SemanticInfo SemanticModel.BindNamespaceOrType(CSharpSyntaxNode location, ExpressionSyntax type);
/// </pre>
/// Also, the following are affected if container==null (and, for the latter, when arity==null
/// or arity==0):
/// <pre>
/// IList<string> SemanticModel.LookupNames(CSharpSyntaxNode location, NamespaceOrTypeSymbol container = null, LookupOptions options = LookupOptions.Default, List<string> result = null);
/// IList<Symbol> SemanticModel.LookupSymbols(CSharpSyntaxNode location, NamespaceOrTypeSymbol container = null, string name = null, int? arity = null, LookupOptions options = LookupOptions.Default, List<Symbol> results = null);
/// </pre>
/// </summary>
internal abstract class AliasSymbol : Symbol
{
private readonly ImmutableArray<Location> _locations; // NOTE: can be empty for the "global" alias.
private readonly string _aliasName;
private readonly bool _isExtern;
private readonly Symbol? _containingSymbol;
protected AliasSymbol(string aliasName, Symbol? containingSymbol, ImmutableArray<Location> locations, bool isExtern)
{
Debug.Assert(locations.Length == 1 || (locations.IsEmpty && aliasName == "global")); // It looks like equality implementation depends on this condition.
_locations = locations;
_aliasName = aliasName;
_isExtern = isExtern;
_containingSymbol = containingSymbol;
}
// For the purposes of SemanticModel, it is convenient to have an AliasSymbol for the "global" namespace that "global::" binds
// to. This alias symbol is returned only when binding "global::" (special case code).
internal static AliasSymbol CreateGlobalNamespaceAlias(NamespaceSymbol globalNamespace)
{
return new AliasSymbolFromResolvedTarget(globalNamespace, "global", globalNamespace, ImmutableArray<Location>.Empty, isExtern: false);
}
internal static AliasSymbol CreateCustomDebugInfoAlias(NamespaceOrTypeSymbol targetSymbol, SyntaxToken aliasToken, Symbol? containingSymbol, bool isExtern)
{
return new AliasSymbolFromResolvedTarget(targetSymbol, aliasToken.ValueText, containingSymbol, ImmutableArray.Create(aliasToken.GetLocation()), isExtern);
}
internal AliasSymbol ToNewSubmission(CSharpCompilation compilation)
{
// We can pass basesBeingResolved: null because base type cycles can't cross
// submission boundaries - there's no way to depend on a subsequent submission.
var previousTarget = Target;
if (previousTarget.Kind != SymbolKind.Namespace)
{
return this;
}
var expandedGlobalNamespace = compilation.GlobalNamespace;
var expandedNamespace = Imports.ExpandPreviousSubmissionNamespace((NamespaceSymbol)previousTarget, expandedGlobalNamespace);
return new AliasSymbolFromResolvedTarget(expandedNamespace, Name, ContainingSymbol, _locations, _isExtern);
}
public sealed override string Name
{
get
{
return _aliasName;
}
}
public override SymbolKind Kind
{
get
{
return SymbolKind.Alias;
}
}
/// <summary>
/// Gets the <see cref="NamespaceOrTypeSymbol"/> for the
/// namespace or type referenced by the alias.
/// </summary>
public abstract NamespaceOrTypeSymbol Target
{
get;
}
public override ImmutableArray<Location> Locations
{
get
{
return _locations;
}
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return GetDeclaringSyntaxReferenceHelper<UsingDirectiveSyntax>(_locations);
}
}
public sealed override bool IsExtern
{
get
{
return _isExtern;
}
}
public override bool IsSealed
{
get
{
return false;
}
}
public override bool IsAbstract
{
get
{
return false;
}
}
public override bool IsOverride
{
get
{
return false;
}
}
public override bool IsVirtual
{
get
{
return false;
}
}
public override bool IsStatic
{
get
{
return false;
}
}
/// <summary>
/// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute.
/// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet.
/// </summary>
internal sealed override ObsoleteAttributeData? ObsoleteAttributeData
{
get { return null; }
}
public override Accessibility DeclaredAccessibility
{
get
{
return Accessibility.NotApplicable;
}
}
/// <summary>
/// Using aliases in C# are always contained within a namespace declaration, or at the top
/// level within a compilation unit, within the implicit unnamed namespace declaration. We
/// return that as the "containing" symbol, even though the alias isn't a member of the
/// namespace as such.
/// </summary>
public sealed override Symbol? ContainingSymbol
{
get
{
return _containingSymbol;
}
}
internal override TResult Accept<TArg, TResult>(CSharpSymbolVisitor<TArg, TResult> visitor, TArg a)
{
return visitor.VisitAlias(this, a);
}
public override void Accept(CSharpSymbolVisitor visitor)
{
visitor.VisitAlias(this);
}
public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor)
{
return visitor.VisitAlias(this);
}
// basesBeingResolved is only used to break circular references.
internal abstract NamespaceOrTypeSymbol GetAliasTarget(ConsList<TypeSymbol>? basesBeingResolved);
internal void CheckConstraints(BindingDiagnosticBag diagnostics)
{
var target = this.Target as TypeSymbol;
if ((object?)target != null && Locations.Length > 0)
{
var corLibrary = this.ContainingAssembly.CorLibrary;
var conversions = new TypeConversions(corLibrary);
target.CheckAllConstraints(DeclaringCompilation, conversions, Locations[0], diagnostics);
}
}
public override bool Equals(Symbol? obj, TypeCompareKind compareKind)
{
if (ReferenceEquals(this, obj))
{
return true;
}
if (ReferenceEquals(obj, null))
{
return false;
}
AliasSymbol? other = obj as AliasSymbol;
return (object?)other != null &&
Equals(this.Locations.FirstOrDefault(), other.Locations.FirstOrDefault()) &&
this.ContainingAssembly.Equals(other.ContainingAssembly, compareKind);
}
public override int GetHashCode()
{
if (this.Locations.Length > 0)
return this.Locations.First().GetHashCode();
else
return Name.GetHashCode();
}
internal abstract override bool RequiresCompletion
{
get;
}
protected override ISymbol CreateISymbol()
{
return new PublicModel.AliasSymbol(this);
}
}
internal sealed class AliasSymbolFromSyntax : AliasSymbol
{
private readonly SyntaxReference _directive;
private SymbolCompletionState _state;
private NamespaceOrTypeSymbol? _aliasTarget;
// lazy binding
private BindingDiagnosticBag? _aliasTargetDiagnostics;
internal AliasSymbolFromSyntax(SourceNamespaceSymbol containingSymbol, UsingDirectiveSyntax syntax)
: base(syntax.Alias!.Name.Identifier.ValueText, containingSymbol, ImmutableArray.Create(syntax.Alias!.Name.Identifier.GetLocation()), isExtern: false)
{
Debug.Assert(syntax.Alias is object);
_directive = syntax.GetReference();
}
internal AliasSymbolFromSyntax(SourceNamespaceSymbol containingSymbol, ExternAliasDirectiveSyntax syntax)
: base(syntax.Identifier.ValueText, containingSymbol, ImmutableArray.Create(syntax.Identifier.GetLocation()), isExtern: true)
{
_directive = syntax.GetReference();
}
/// <summary>
/// Gets the <see cref="NamespaceOrTypeSymbol"/> for the
/// namespace or type referenced by the alias.
/// </summary>
public override NamespaceOrTypeSymbol Target
{
get
{
return GetAliasTarget(basesBeingResolved: null);
}
}
// basesBeingResolved is only used to break circular references.
internal override NamespaceOrTypeSymbol GetAliasTarget(ConsList<TypeSymbol>? basesBeingResolved)
{
if (!_state.HasComplete(CompletionPart.AliasTarget))
{
// the target is not yet bound. If it is an ordinary alias, bind the target
// symbol. If it is an extern alias then find the target in the list of metadata references.
var newDiagnostics = BindingDiagnosticBag.GetInstance();
NamespaceOrTypeSymbol symbol = this.IsExtern ?
ResolveExternAliasTarget(newDiagnostics) :
ResolveAliasTarget(((UsingDirectiveSyntax)_directive.GetSyntax()).Name, newDiagnostics, basesBeingResolved);
if ((object?)Interlocked.CompareExchange(ref _aliasTarget, symbol, null) == null)
{
// Note: It's important that we don't call newDiagnosticsToReadOnlyAndFree here. That call
// can force the prompt evaluation of lazy initialized diagnostics. That in turn can
// call back into GetAliasTarget on the same thread resulting in a dead lock scenario.
bool won = Interlocked.Exchange(ref _aliasTargetDiagnostics, newDiagnostics) == null;
Debug.Assert(won, "Only one thread can win the alias target CompareExchange");
_state.NotePartComplete(CompletionPart.AliasTarget);
// we do not clear this.aliasTargetName, as another thread might be about to use it for ResolveAliasTarget(...)
}
else
{
newDiagnostics.Free();
// Wait for diagnostics to have been reported if another thread resolves the alias
_state.SpinWaitComplete(CompletionPart.AliasTarget, default(CancellationToken));
}
}
return _aliasTarget!;
}
internal BindingDiagnosticBag AliasTargetDiagnostics
{
get
{
GetAliasTarget(null);
RoslynDebug.Assert(_aliasTargetDiagnostics != null);
return _aliasTargetDiagnostics;
}
}
private NamespaceSymbol ResolveExternAliasTarget(BindingDiagnosticBag diagnostics)
{
NamespaceSymbol? target;
if (!ContainingSymbol!.DeclaringCompilation.GetExternAliasTarget(Name, out target))
{
diagnostics.Add(ErrorCode.ERR_BadExternAlias, Locations[0], Name);
}
RoslynDebug.Assert(target is object);
RoslynDebug.Assert(target.IsGlobalNamespace);
return target;
}
private NamespaceOrTypeSymbol ResolveAliasTarget(NameSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol>? basesBeingResolved)
{
var declarationBinder = ContainingSymbol!.DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder(syntax).WithAdditionalFlags(BinderFlags.SuppressConstraintChecks | BinderFlags.SuppressObsoleteChecks);
return declarationBinder.BindNamespaceOrTypeSymbol(syntax, diagnostics, basesBeingResolved).NamespaceOrTypeSymbol;
}
internal override bool RequiresCompletion
{
get { return true; }
}
}
internal sealed class AliasSymbolFromResolvedTarget : AliasSymbol
{
private readonly NamespaceOrTypeSymbol _aliasTarget;
internal AliasSymbolFromResolvedTarget(NamespaceOrTypeSymbol target, string aliasName, Symbol? containingSymbol, ImmutableArray<Location> locations, bool isExtern)
: base(aliasName, containingSymbol, locations, isExtern)
{
_aliasTarget = target;
}
/// <summary>
/// Gets the <see cref="NamespaceOrTypeSymbol"/> for the
/// namespace or type referenced by the alias.
/// </summary>
public override NamespaceOrTypeSymbol Target
{
get
{
return _aliasTarget;
}
}
internal override NamespaceOrTypeSymbol GetAliasTarget(ConsList<TypeSymbol>? basesBeingResolved)
{
return _aliasTarget;
}
internal override bool RequiresCompletion
{
get { return false; }
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/EditorFeatures/Core/Implementation/InlineRename/AbstractEditorInlineRenameService.InlineRenameReplacementInfo.cs | // 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.Linq;
using Microsoft.CodeAnalysis.Rename;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal abstract partial class AbstractEditorInlineRenameService : IEditorInlineRenameService
{
private class InlineRenameReplacementInfo : IInlineRenameReplacementInfo
{
private readonly ConflictResolution _conflicts;
public InlineRenameReplacementInfo(ConflictResolution conflicts)
=> _conflicts = conflicts;
public IEnumerable<DocumentId> DocumentIds => _conflicts.DocumentIds;
public Solution NewSolution => _conflicts.NewSolution;
public bool ReplacementTextValid => _conflicts.ReplacementTextValid;
public IEnumerable<InlineRenameReplacement> GetReplacements(DocumentId documentId)
{
var nonComplexifiedSpans = GetNonComplexifiedReplacements(documentId);
var complexifiedSpans = GetComplexifiedReplacements(documentId);
return nonComplexifiedSpans.Concat(complexifiedSpans);
}
private IEnumerable<InlineRenameReplacement> GetNonComplexifiedReplacements(DocumentId documentId)
{
var modifiedSpans = _conflicts.GetModifiedSpanMap(documentId);
var locationsForDocument = _conflicts.GetRelatedLocationsForDocument(documentId);
// The RenamedSpansTracker doesn't currently track unresolved conflicts for
// unmodified locations. If the document wasn't modified, we can just use the
// original span as the new span, but otherwise we need to filter out
// locations that aren't in modifiedSpans.
if (modifiedSpans.Any())
{
return locationsForDocument.Where(loc => modifiedSpans.ContainsKey(loc.ConflictCheckSpan))
.Select(loc => new InlineRenameReplacement(loc, modifiedSpans[loc.ConflictCheckSpan]));
}
else
{
return locationsForDocument.Select(loc => new InlineRenameReplacement(loc, loc.ConflictCheckSpan));
}
}
private IEnumerable<InlineRenameReplacement> GetComplexifiedReplacements(DocumentId documentId)
{
return _conflicts.GetComplexifiedSpans(documentId)
.Select(s => new InlineRenameReplacement(InlineRenameReplacementKind.Complexified, s.oldSpan, s.newSpan));
}
}
}
}
| // 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.Linq;
using Microsoft.CodeAnalysis.Rename;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal abstract partial class AbstractEditorInlineRenameService : IEditorInlineRenameService
{
private class InlineRenameReplacementInfo : IInlineRenameReplacementInfo
{
private readonly ConflictResolution _conflicts;
public InlineRenameReplacementInfo(ConflictResolution conflicts)
=> _conflicts = conflicts;
public IEnumerable<DocumentId> DocumentIds => _conflicts.DocumentIds;
public Solution NewSolution => _conflicts.NewSolution;
public bool ReplacementTextValid => _conflicts.ReplacementTextValid;
public IEnumerable<InlineRenameReplacement> GetReplacements(DocumentId documentId)
{
var nonComplexifiedSpans = GetNonComplexifiedReplacements(documentId);
var complexifiedSpans = GetComplexifiedReplacements(documentId);
return nonComplexifiedSpans.Concat(complexifiedSpans);
}
private IEnumerable<InlineRenameReplacement> GetNonComplexifiedReplacements(DocumentId documentId)
{
var modifiedSpans = _conflicts.GetModifiedSpanMap(documentId);
var locationsForDocument = _conflicts.GetRelatedLocationsForDocument(documentId);
// The RenamedSpansTracker doesn't currently track unresolved conflicts for
// unmodified locations. If the document wasn't modified, we can just use the
// original span as the new span, but otherwise we need to filter out
// locations that aren't in modifiedSpans.
if (modifiedSpans.Any())
{
return locationsForDocument.Where(loc => modifiedSpans.ContainsKey(loc.ConflictCheckSpan))
.Select(loc => new InlineRenameReplacement(loc, modifiedSpans[loc.ConflictCheckSpan]));
}
else
{
return locationsForDocument.Select(loc => new InlineRenameReplacement(loc, loc.ConflictCheckSpan));
}
}
private IEnumerable<InlineRenameReplacement> GetComplexifiedReplacements(DocumentId documentId)
{
return _conflicts.GetComplexifiedSpans(documentId)
.Select(s => new InlineRenameReplacement(InlineRenameReplacementKind.Complexified, s.oldSpan, s.newSpan));
}
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs | // 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.Xml.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal interface ICodeStyleOption : IObjectWritable
{
XElement ToXElement();
object? Value { get; }
NotificationOption2 Notification { get; }
ICodeStyleOption WithValue(object value);
ICodeStyleOption WithNotification(NotificationOption2 notification);
ICodeStyleOption AsCodeStyleOption<TCodeStyleOption>();
#if !CODE_STYLE
ICodeStyleOption AsPublicCodeStyleOption();
#endif
}
/// <summary>
/// Represents a code style option and an associated notification option. Supports
/// being instantiated with T as a <see cref="bool"/> or an <c>enum type</c>.
///
/// CodeStyleOption also has some basic support for migration a <see cref="bool"/> option
/// forward to an <c>enum type</c> option. Specifically, if a previously serialized
/// bool-CodeStyleOption is then deserialized into an enum-CodeStyleOption then 'false'
/// values will be migrated to have the 0-value of the enum, and 'true' values will be
/// migrated to have the 1-value of the enum.
///
/// Similarly, enum-type code options will serialize out in a way that is compatible with
/// hosts that expect the value to be a boolean. Specifically, if the enum value is 0 or 1
/// then those values will write back as false/true.
/// </summary>
internal sealed partial class CodeStyleOption2<T> : ICodeStyleOption, IEquatable<CodeStyleOption2<T>?>
{
static CodeStyleOption2()
{
ObjectBinder.RegisterTypeReader(typeof(CodeStyleOption2<T>), ReadFrom);
}
public static CodeStyleOption2<T> Default => new(default!, NotificationOption2.Silent);
private const int SerializationVersion = 1;
private readonly NotificationOption2 _notification;
public CodeStyleOption2(T value, NotificationOption2 notification)
{
Value = value;
_notification = notification ?? throw new ArgumentNullException(nameof(notification));
}
public T Value { get; }
object? ICodeStyleOption.Value => this.Value;
ICodeStyleOption ICodeStyleOption.WithValue(object value) => new CodeStyleOption2<T>((T)value, Notification);
ICodeStyleOption ICodeStyleOption.WithNotification(NotificationOption2 notification) => new CodeStyleOption2<T>(Value, notification);
#if CODE_STYLE
ICodeStyleOption ICodeStyleOption.AsCodeStyleOption<TCodeStyleOption>() => this;
#else
ICodeStyleOption ICodeStyleOption.AsCodeStyleOption<TCodeStyleOption>()
=> this is TCodeStyleOption ? this : (ICodeStyleOption)new CodeStyleOption<T>(this);
ICodeStyleOption ICodeStyleOption.AsPublicCodeStyleOption() => new CodeStyleOption<T>(this);
#endif
private int EnumValueAsInt32 => (int)(object)Value!;
public NotificationOption2 Notification
{
get => _notification;
}
public XElement ToXElement() =>
new("CodeStyleOption", // Ensure that we use "CodeStyleOption" as the name for back compat.
new XAttribute(nameof(SerializationVersion), SerializationVersion),
new XAttribute("Type", GetTypeNameForSerialization()),
new XAttribute(nameof(Value), GetValueForSerialization()),
new XAttribute(nameof(DiagnosticSeverity), Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden));
private object GetValueForSerialization()
{
if (typeof(T) == typeof(string))
{
return Value!;
}
else if (typeof(T) == typeof(bool))
{
return Value!;
}
else if (IsZeroOrOneValueOfEnum())
{
return EnumValueAsInt32 == 1;
}
else
{
return EnumValueAsInt32;
}
}
private string GetTypeNameForSerialization()
{
if (typeof(T) == typeof(string))
{
return nameof(String);
}
if (typeof(T) == typeof(bool) || IsZeroOrOneValueOfEnum())
{
return nameof(Boolean);
}
else
{
return nameof(Int32);
}
}
private bool IsZeroOrOneValueOfEnum()
{
var intVal = EnumValueAsInt32;
return intVal == 0 || intVal == 1;
}
public static CodeStyleOption2<T> FromXElement(XElement element)
{
var typeAttribute = element.Attribute("Type");
var valueAttribute = element.Attribute(nameof(Value));
var severityAttribute = element.Attribute(nameof(DiagnosticSeverity));
var version = (int?)element.Attribute(nameof(SerializationVersion));
if (typeAttribute == null || valueAttribute == null || severityAttribute == null)
{
// data from storage is corrupt, or nothing has been stored yet.
return Default;
}
if (version != SerializationVersion)
{
return Default;
}
var parser = GetParser(typeAttribute.Value);
var value = parser(valueAttribute.Value);
var severity = (DiagnosticSeverity)Enum.Parse(typeof(DiagnosticSeverity), severityAttribute.Value);
return new CodeStyleOption2<T>(value, severity switch
{
DiagnosticSeverity.Hidden => NotificationOption2.Silent,
DiagnosticSeverity.Info => NotificationOption2.Suggestion,
DiagnosticSeverity.Warning => NotificationOption2.Warning,
DiagnosticSeverity.Error => NotificationOption2.Error,
_ => throw new ArgumentException(nameof(element)),
});
}
public bool ShouldReuseInSerialization => false;
public void WriteTo(ObjectWriter writer)
{
writer.WriteValue(GetValueForSerialization());
writer.WriteInt32((int)(Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden));
}
public static CodeStyleOption2<object> ReadFrom(ObjectReader reader)
{
return new CodeStyleOption2<object>(
reader.ReadValue(),
(DiagnosticSeverity)reader.ReadInt32() switch
{
DiagnosticSeverity.Hidden => NotificationOption2.Silent,
DiagnosticSeverity.Info => NotificationOption2.Suggestion,
DiagnosticSeverity.Warning => NotificationOption2.Warning,
DiagnosticSeverity.Error => NotificationOption2.Error,
var v => throw ExceptionUtilities.UnexpectedValue(v),
});
}
private static Func<string, T> GetParser(string type)
=> type switch
{
nameof(Boolean) =>
// Try to map a boolean value. Either map it to true/false if we're a
// CodeStyleOption<bool> or map it to the 0 or 1 value for an enum if we're
// a CodeStyleOption<SomeEnumType>.
(Func<string, T>)(v => Convert(bool.Parse(v))),
nameof(Int32) => v => Convert(int.Parse(v)),
nameof(String) => v => (T)(object)v,
_ => throw new ArgumentException(nameof(type)),
};
private static T Convert(bool b)
{
// If we had a bool and we wanted a bool, then just return this value.
if (typeof(T) == typeof(bool))
{
return (T)(object)b;
}
// Map booleans to the 1/0 value of the enum.
return b ? (T)(object)1 : (T)(object)0;
}
private static T Convert(int i)
{
// We got an int, but we wanted a bool. Map 0 to false, 1 to true, and anything else to default.
if (typeof(T) == typeof(bool))
{
return (T)(object)(i == 1);
}
// If had an int and we wanted an enum, then just return this value.
return (T)(object)(i);
}
public bool Equals(CodeStyleOption2<T>? other)
{
return other is not null
&& EqualityComparer<T>.Default.Equals(Value, other.Value)
&& Notification == other.Notification;
}
public override bool Equals(object? obj)
=> obj is CodeStyleOption2<T> option &&
Equals(option);
public override int GetHashCode()
=> unchecked((Notification.GetHashCode() * (int)0xA5555529) + EqualityComparer<T>.Default.GetHashCode(Value!));
}
}
| // 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.Xml.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal interface ICodeStyleOption : IObjectWritable
{
XElement ToXElement();
object? Value { get; }
NotificationOption2 Notification { get; }
ICodeStyleOption WithValue(object value);
ICodeStyleOption WithNotification(NotificationOption2 notification);
ICodeStyleOption AsCodeStyleOption<TCodeStyleOption>();
#if !CODE_STYLE
ICodeStyleOption AsPublicCodeStyleOption();
#endif
}
/// <summary>
/// Represents a code style option and an associated notification option. Supports
/// being instantiated with T as a <see cref="bool"/> or an <c>enum type</c>.
///
/// CodeStyleOption also has some basic support for migration a <see cref="bool"/> option
/// forward to an <c>enum type</c> option. Specifically, if a previously serialized
/// bool-CodeStyleOption is then deserialized into an enum-CodeStyleOption then 'false'
/// values will be migrated to have the 0-value of the enum, and 'true' values will be
/// migrated to have the 1-value of the enum.
///
/// Similarly, enum-type code options will serialize out in a way that is compatible with
/// hosts that expect the value to be a boolean. Specifically, if the enum value is 0 or 1
/// then those values will write back as false/true.
/// </summary>
internal sealed partial class CodeStyleOption2<T> : ICodeStyleOption, IEquatable<CodeStyleOption2<T>?>
{
static CodeStyleOption2()
{
ObjectBinder.RegisterTypeReader(typeof(CodeStyleOption2<T>), ReadFrom);
}
public static CodeStyleOption2<T> Default => new(default!, NotificationOption2.Silent);
private const int SerializationVersion = 1;
private readonly NotificationOption2 _notification;
public CodeStyleOption2(T value, NotificationOption2 notification)
{
Value = value;
_notification = notification ?? throw new ArgumentNullException(nameof(notification));
}
public T Value { get; }
object? ICodeStyleOption.Value => this.Value;
ICodeStyleOption ICodeStyleOption.WithValue(object value) => new CodeStyleOption2<T>((T)value, Notification);
ICodeStyleOption ICodeStyleOption.WithNotification(NotificationOption2 notification) => new CodeStyleOption2<T>(Value, notification);
#if CODE_STYLE
ICodeStyleOption ICodeStyleOption.AsCodeStyleOption<TCodeStyleOption>() => this;
#else
ICodeStyleOption ICodeStyleOption.AsCodeStyleOption<TCodeStyleOption>()
=> this is TCodeStyleOption ? this : (ICodeStyleOption)new CodeStyleOption<T>(this);
ICodeStyleOption ICodeStyleOption.AsPublicCodeStyleOption() => new CodeStyleOption<T>(this);
#endif
private int EnumValueAsInt32 => (int)(object)Value!;
public NotificationOption2 Notification
{
get => _notification;
}
public XElement ToXElement() =>
new("CodeStyleOption", // Ensure that we use "CodeStyleOption" as the name for back compat.
new XAttribute(nameof(SerializationVersion), SerializationVersion),
new XAttribute("Type", GetTypeNameForSerialization()),
new XAttribute(nameof(Value), GetValueForSerialization()),
new XAttribute(nameof(DiagnosticSeverity), Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden));
private object GetValueForSerialization()
{
if (typeof(T) == typeof(string))
{
return Value!;
}
else if (typeof(T) == typeof(bool))
{
return Value!;
}
else if (IsZeroOrOneValueOfEnum())
{
return EnumValueAsInt32 == 1;
}
else
{
return EnumValueAsInt32;
}
}
private string GetTypeNameForSerialization()
{
if (typeof(T) == typeof(string))
{
return nameof(String);
}
if (typeof(T) == typeof(bool) || IsZeroOrOneValueOfEnum())
{
return nameof(Boolean);
}
else
{
return nameof(Int32);
}
}
private bool IsZeroOrOneValueOfEnum()
{
var intVal = EnumValueAsInt32;
return intVal == 0 || intVal == 1;
}
public static CodeStyleOption2<T> FromXElement(XElement element)
{
var typeAttribute = element.Attribute("Type");
var valueAttribute = element.Attribute(nameof(Value));
var severityAttribute = element.Attribute(nameof(DiagnosticSeverity));
var version = (int?)element.Attribute(nameof(SerializationVersion));
if (typeAttribute == null || valueAttribute == null || severityAttribute == null)
{
// data from storage is corrupt, or nothing has been stored yet.
return Default;
}
if (version != SerializationVersion)
{
return Default;
}
var parser = GetParser(typeAttribute.Value);
var value = parser(valueAttribute.Value);
var severity = (DiagnosticSeverity)Enum.Parse(typeof(DiagnosticSeverity), severityAttribute.Value);
return new CodeStyleOption2<T>(value, severity switch
{
DiagnosticSeverity.Hidden => NotificationOption2.Silent,
DiagnosticSeverity.Info => NotificationOption2.Suggestion,
DiagnosticSeverity.Warning => NotificationOption2.Warning,
DiagnosticSeverity.Error => NotificationOption2.Error,
_ => throw new ArgumentException(nameof(element)),
});
}
public bool ShouldReuseInSerialization => false;
public void WriteTo(ObjectWriter writer)
{
writer.WriteValue(GetValueForSerialization());
writer.WriteInt32((int)(Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden));
}
public static CodeStyleOption2<object> ReadFrom(ObjectReader reader)
{
return new CodeStyleOption2<object>(
reader.ReadValue(),
(DiagnosticSeverity)reader.ReadInt32() switch
{
DiagnosticSeverity.Hidden => NotificationOption2.Silent,
DiagnosticSeverity.Info => NotificationOption2.Suggestion,
DiagnosticSeverity.Warning => NotificationOption2.Warning,
DiagnosticSeverity.Error => NotificationOption2.Error,
var v => throw ExceptionUtilities.UnexpectedValue(v),
});
}
private static Func<string, T> GetParser(string type)
=> type switch
{
nameof(Boolean) =>
// Try to map a boolean value. Either map it to true/false if we're a
// CodeStyleOption<bool> or map it to the 0 or 1 value for an enum if we're
// a CodeStyleOption<SomeEnumType>.
(Func<string, T>)(v => Convert(bool.Parse(v))),
nameof(Int32) => v => Convert(int.Parse(v)),
nameof(String) => v => (T)(object)v,
_ => throw new ArgumentException(nameof(type)),
};
private static T Convert(bool b)
{
// If we had a bool and we wanted a bool, then just return this value.
if (typeof(T) == typeof(bool))
{
return (T)(object)b;
}
// Map booleans to the 1/0 value of the enum.
return b ? (T)(object)1 : (T)(object)0;
}
private static T Convert(int i)
{
// We got an int, but we wanted a bool. Map 0 to false, 1 to true, and anything else to default.
if (typeof(T) == typeof(bool))
{
return (T)(object)(i == 1);
}
// If had an int and we wanted an enum, then just return this value.
return (T)(object)(i);
}
public bool Equals(CodeStyleOption2<T>? other)
{
return other is not null
&& EqualityComparer<T>.Default.Equals(Value, other.Value)
&& Notification == other.Notification;
}
public override bool Equals(object? obj)
=> obj is CodeStyleOption2<T> option &&
Equals(option);
public override int GetHashCode()
=> unchecked((Notification.GetHashCode() * (int)0xA5555529) + EqualityComparer<T>.Default.GetHashCode(Value!));
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/VisualStudio/Core/Test/CodeModel/AbstractCodeEventTests.vb | ' 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.
Imports System.Threading.Tasks
Imports EnvDTE80
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel
Public MustInherit Class AbstractCodeEventTests
Inherits AbstractCodeElementTests(Of EnvDTE80.CodeEvent)
Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE80.CodeEvent) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint)
Return Function(part) codeElement.GetStartPoint(part)
End Function
Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE80.CodeEvent) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint)
Return Function(part) codeElement.GetEndPoint(part)
End Function
Protected Overrides Function GetAccess(codeElement As EnvDTE80.CodeEvent) As EnvDTE.vsCMAccess
Return codeElement.Access
End Function
Protected Overrides Function GetAttributes(codeElement As EnvDTE80.CodeEvent) As EnvDTE.CodeElements
Return codeElement.Attributes
End Function
Protected Overrides Function GetComment(codeElement As EnvDTE80.CodeEvent) As String
Return codeElement.Comment
End Function
Protected Overrides Function GetDocComment(codeElement As EnvDTE80.CodeEvent) As String
Return codeElement.DocComment
End Function
Protected Overrides Function GetFullName(codeElement As EnvDTE80.CodeEvent) As String
Return codeElement.FullName
End Function
Protected Overrides Function GetIsShared(codeElement As EnvDTE80.CodeEvent) As Boolean
Return codeElement.IsShared
End Function
Protected Overrides Function GetIsSharedSetter(codeElement As EnvDTE80.CodeEvent) As Action(Of Boolean)
Return Sub(value) codeElement.IsShared = value
End Function
Protected Overrides Function GetKind(codeElement As EnvDTE80.CodeEvent) As EnvDTE.vsCMElement
Return codeElement.Kind
End Function
Protected Overrides Function GetName(codeElement As EnvDTE80.CodeEvent) As String
Return codeElement.Name
End Function
Protected Overrides Function GetNameSetter(codeElement As EnvDTE80.CodeEvent) As Action(Of String)
Return Sub(name) codeElement.Name = name
End Function
Protected Overrides Function GetOverrideKind(codeElement As CodeEvent) As vsCMOverrideKind
Return codeElement.OverrideKind
End Function
Protected Overrides Function GetParent(codeElement As EnvDTE80.CodeEvent) As Object
Return codeElement.Parent
End Function
Protected Overrides Function GetPrototype(codeElement As EnvDTE80.CodeEvent, flags As EnvDTE.vsCMPrototype) As String
Return codeElement.Prototype(flags)
End Function
Protected Overrides Function GetTypeProp(codeElement As EnvDTE80.CodeEvent) As EnvDTE.CodeTypeRef
Return codeElement.Type
End Function
Protected Overrides Function GetTypePropSetter(codeElement As EnvDTE80.CodeEvent) As Action(Of EnvDTE.CodeTypeRef)
Return Sub(value) codeElement.Type = value
End Function
Protected Overrides Function AddAttribute(codeElement As EnvDTE80.CodeEvent, data As AttributeData) As EnvDTE.CodeAttribute
Return codeElement.AddAttribute(data.Name, data.Value, data.Position)
End Function
Protected Sub TestIsPropertyStyleEvent(code As XElement, expected As Boolean)
TestElement(code,
Sub(codeElement)
Assert.Equal(expected, codeElement.IsPropertyStyleEvent)
End Sub)
End Sub
End Class
End Namespace
| ' 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.
Imports System.Threading.Tasks
Imports EnvDTE80
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel
Public MustInherit Class AbstractCodeEventTests
Inherits AbstractCodeElementTests(Of EnvDTE80.CodeEvent)
Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE80.CodeEvent) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint)
Return Function(part) codeElement.GetStartPoint(part)
End Function
Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE80.CodeEvent) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint)
Return Function(part) codeElement.GetEndPoint(part)
End Function
Protected Overrides Function GetAccess(codeElement As EnvDTE80.CodeEvent) As EnvDTE.vsCMAccess
Return codeElement.Access
End Function
Protected Overrides Function GetAttributes(codeElement As EnvDTE80.CodeEvent) As EnvDTE.CodeElements
Return codeElement.Attributes
End Function
Protected Overrides Function GetComment(codeElement As EnvDTE80.CodeEvent) As String
Return codeElement.Comment
End Function
Protected Overrides Function GetDocComment(codeElement As EnvDTE80.CodeEvent) As String
Return codeElement.DocComment
End Function
Protected Overrides Function GetFullName(codeElement As EnvDTE80.CodeEvent) As String
Return codeElement.FullName
End Function
Protected Overrides Function GetIsShared(codeElement As EnvDTE80.CodeEvent) As Boolean
Return codeElement.IsShared
End Function
Protected Overrides Function GetIsSharedSetter(codeElement As EnvDTE80.CodeEvent) As Action(Of Boolean)
Return Sub(value) codeElement.IsShared = value
End Function
Protected Overrides Function GetKind(codeElement As EnvDTE80.CodeEvent) As EnvDTE.vsCMElement
Return codeElement.Kind
End Function
Protected Overrides Function GetName(codeElement As EnvDTE80.CodeEvent) As String
Return codeElement.Name
End Function
Protected Overrides Function GetNameSetter(codeElement As EnvDTE80.CodeEvent) As Action(Of String)
Return Sub(name) codeElement.Name = name
End Function
Protected Overrides Function GetOverrideKind(codeElement As CodeEvent) As vsCMOverrideKind
Return codeElement.OverrideKind
End Function
Protected Overrides Function GetParent(codeElement As EnvDTE80.CodeEvent) As Object
Return codeElement.Parent
End Function
Protected Overrides Function GetPrototype(codeElement As EnvDTE80.CodeEvent, flags As EnvDTE.vsCMPrototype) As String
Return codeElement.Prototype(flags)
End Function
Protected Overrides Function GetTypeProp(codeElement As EnvDTE80.CodeEvent) As EnvDTE.CodeTypeRef
Return codeElement.Type
End Function
Protected Overrides Function GetTypePropSetter(codeElement As EnvDTE80.CodeEvent) As Action(Of EnvDTE.CodeTypeRef)
Return Sub(value) codeElement.Type = value
End Function
Protected Overrides Function AddAttribute(codeElement As EnvDTE80.CodeEvent, data As AttributeData) As EnvDTE.CodeAttribute
Return codeElement.AddAttribute(data.Name, data.Value, data.Position)
End Function
Protected Sub TestIsPropertyStyleEvent(code As XElement, expected As Boolean)
TestElement(code,
Sub(codeElement)
Assert.Equal(expected, codeElement.IsPropertyStyleEvent)
End Sub)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Workspaces/Core/Portable/Utilities/FlowControlHelper.cs | // 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.Threading;
namespace Roslyn.Utilities
{
internal static class FlowControlHelper
{
public static AsyncFlowControlHelper TrySuppressFlow()
=> new(ExecutionContext.IsFlowSuppressed() ? default : ExecutionContext.SuppressFlow());
public struct AsyncFlowControlHelper : IDisposable
{
private readonly AsyncFlowControl _asyncFlowControl;
public AsyncFlowControlHelper(AsyncFlowControl asyncFlowControl)
{
_asyncFlowControl = asyncFlowControl;
}
public void Dispose()
{
if (_asyncFlowControl != default)
{
_asyncFlowControl.Dispose();
}
}
}
}
}
| // 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.Threading;
namespace Roslyn.Utilities
{
internal static class FlowControlHelper
{
public static AsyncFlowControlHelper TrySuppressFlow()
=> new(ExecutionContext.IsFlowSuppressed() ? default : ExecutionContext.SuppressFlow());
public struct AsyncFlowControlHelper : IDisposable
{
private readonly AsyncFlowControl _asyncFlowControl;
public AsyncFlowControlHelper(AsyncFlowControl asyncFlowControl)
{
_asyncFlowControl = asyncFlowControl;
}
public void Dispose()
{
if (_asyncFlowControl != default)
{
_asyncFlowControl.Dispose();
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/EditorFeatures/Core.Wpf/Suggestions/PreviewChanges/PreviewChangesCodeAction.cs | // 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.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
internal partial class SuggestedActionWithNestedFlavors
{
private partial class PreviewChangesSuggestedAction
{
private sealed class PreviewChangesCodeAction : CodeAction
{
private readonly Workspace _workspace;
private readonly CodeAction _originalCodeAction;
private readonly SolutionChangeSummary _changeSummary;
public PreviewChangesCodeAction(Workspace workspace, CodeAction originalCodeAction, SolutionChangeSummary changeSummary)
{
_workspace = workspace;
_originalCodeAction = originalCodeAction;
_changeSummary = changeSummary;
}
public override string Title => EditorFeaturesResources.Preview_changes2;
internal override async Task<ImmutableArray<CodeActionOperation>> GetOperationsCoreAsync(IProgressTracker progressTracker, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var previewDialogService = _workspace.Services.GetService<IPreviewDialogService>();
if (previewDialogService == null)
{
return ImmutableArray<CodeActionOperation>.Empty;
}
var changedSolution = previewDialogService.PreviewChanges(
EditorFeaturesResources.Preview_Changes,
"vs.codefix.previewchanges",
_originalCodeAction.Title,
EditorFeaturesResources.Changes,
CodeAnalysis.Glyph.OpenFolder,
_changeSummary.NewSolution,
_changeSummary.OldSolution,
showCheckBoxes: false);
if (changedSolution == null)
{
// User pressed the cancel button.
return ImmutableArray<CodeActionOperation>.Empty;
}
cancellationToken.ThrowIfCancellationRequested();
return await _originalCodeAction.GetOperationsAsync(cancellationToken).ConfigureAwait(false);
}
}
}
}
}
| // 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.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
internal partial class SuggestedActionWithNestedFlavors
{
private partial class PreviewChangesSuggestedAction
{
private sealed class PreviewChangesCodeAction : CodeAction
{
private readonly Workspace _workspace;
private readonly CodeAction _originalCodeAction;
private readonly SolutionChangeSummary _changeSummary;
public PreviewChangesCodeAction(Workspace workspace, CodeAction originalCodeAction, SolutionChangeSummary changeSummary)
{
_workspace = workspace;
_originalCodeAction = originalCodeAction;
_changeSummary = changeSummary;
}
public override string Title => EditorFeaturesResources.Preview_changes2;
internal override async Task<ImmutableArray<CodeActionOperation>> GetOperationsCoreAsync(IProgressTracker progressTracker, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var previewDialogService = _workspace.Services.GetService<IPreviewDialogService>();
if (previewDialogService == null)
{
return ImmutableArray<CodeActionOperation>.Empty;
}
var changedSolution = previewDialogService.PreviewChanges(
EditorFeaturesResources.Preview_Changes,
"vs.codefix.previewchanges",
_originalCodeAction.Title,
EditorFeaturesResources.Changes,
CodeAnalysis.Glyph.OpenFolder,
_changeSummary.NewSolution,
_changeSummary.OldSolution,
showCheckBoxes: false);
if (changedSolution == null)
{
// User pressed the cancel button.
return ImmutableArray<CodeActionOperation>.Empty;
}
cancellationToken.ThrowIfCancellationRequested();
return await _originalCodeAction.GetOperationsAsync(cancellationToken).ConfigureAwait(false);
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/VisualStudio/Core/Test/CodeModel/AbstractFileCodeModelTests.vb | ' 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.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel
Public MustInherit Class AbstractFileCodeModelTests
Inherits AbstractCodeModelObjectTests(Of EnvDTE80.FileCodeModel2)
Protected Async Function TestOperation(code As XElement, expectedCode As XElement, operation As Action(Of EnvDTE80.FileCodeModel2)) As Task
WpfTestRunner.RequireWpfFact($"Test calls {NameOf(Me.TestOperation)} which means we're creating new {NameOf(EnvDTE.CodeModel)} elements.")
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim fileCodeModel = state.FileCodeModel
Assert.NotNull(fileCodeModel)
operation(fileCodeModel)
Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString()
Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim())
End Using
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim fileCodeModel = state.FileCodeModel
Assert.NotNull(fileCodeModel)
fileCodeModel.BeginBatch()
operation(fileCodeModel)
fileCodeModel.EndBatch()
Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString()
Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim())
End Using
End Function
Protected Sub TestOperation(code As XElement, operation As Action(Of EnvDTE80.FileCodeModel2))
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim fileCodeModel = state.FileCodeModel
Assert.NotNull(fileCodeModel)
operation(fileCodeModel)
End Using
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim fileCodeModel = state.FileCodeModel
Assert.NotNull(fileCodeModel)
fileCodeModel.BeginBatch()
operation(fileCodeModel)
fileCodeModel.EndBatch()
End Using
End Sub
Protected Overrides Sub TestChildren(code As XElement, ParamArray expectedChildren() As Action(Of Object))
TestOperation(code,
Sub(fileCodeModel)
Dim children = fileCodeModel.CodeElements
Assert.Equal(expectedChildren.Length, children.Count)
For i = 1 To children.Count
expectedChildren(i - 1)(children.Item(i))
Next
End Sub)
End Sub
Protected Overrides Async Function TestAddAttribute(code As XElement, expectedCode As XElement, data As AttributeData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newAttribute = fileCodeModel.AddAttribute(data.Name, data.Value, data.Position)
Assert.NotNull(newAttribute)
Assert.Equal(data.Name, newAttribute.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddClass(code As XElement, expectedCode As XElement, data As ClassData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newClass = fileCodeModel.AddClass(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access)
Assert.NotNull(newClass)
Assert.Equal(data.Name, newClass.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddDelegate(code As XElement, expectedCode As XElement, data As DelegateData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newDelegate = fileCodeModel.AddDelegate(data.Name, data.Type, data.Position, data.Access)
Assert.NotNull(newDelegate)
Assert.Equal(data.Name, newDelegate.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddEnum(code As XElement, expectedCode As XElement, data As EnumData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newEnum = fileCodeModel.AddEnum(data.Name, data.Position, data.Base, data.Access)
Assert.NotNull(newEnum)
Assert.Equal(data.Name, newEnum.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddFunction(code As XElement, expectedCode As XElement, data As FunctionData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Assert.Throws(Of System.Runtime.InteropServices.COMException)(
Sub()
fileCodeModel.AddFunction(data.Name, data.Kind, data.Type, data.Position, data.Access)
End Sub)
End Sub)
End Function
Protected Overrides Async Function TestAddImport(code As XElement, expectedCode As XElement, data As ImportData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newImport = fileCodeModel.AddImport(data.Namespace, data.Position, data.Alias)
Assert.NotNull(newImport)
Assert.Equal(data.Namespace, newImport.Namespace)
If data.Alias IsNot Nothing Then
Assert.Equal(data.Alias, newImport.Alias)
End If
End Sub)
End Function
Protected Overrides Async Function TestAddInterface(code As XElement, expectedCode As XElement, data As InterfaceData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newInterface = fileCodeModel.AddInterface(data.Name, data.Position, data.Bases, data.Access)
Assert.NotNull(newInterface)
Assert.Equal(data.Name, newInterface.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddNamespace(code As XElement, expectedCode As XElement, data As NamespaceData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newNamespace = fileCodeModel.AddNamespace(data.Name, data.Position)
Assert.NotNull(newNamespace)
Assert.Equal(data.Name, newNamespace.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddStruct(code As XElement, expectedCode As XElement, data As StructData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newStruct = fileCodeModel.AddStruct(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access)
Assert.NotNull(newStruct)
Assert.Equal(data.Name, newStruct.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddVariable(code As XElement, expectedCode As XElement, data As VariableData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Assert.Throws(Of System.Runtime.InteropServices.COMException)(
Sub()
fileCodeModel.AddVariable(data.Name, data.Type, data.Position, data.Access)
End Sub)
End Sub)
End Function
Protected Overrides Async Function TestRemoveChild(code As XElement, expectedCode As XElement, element As Object) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
fileCodeModel.Remove(element)
End Sub)
End Function
End Class
End Namespace
| ' 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.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel
Public MustInherit Class AbstractFileCodeModelTests
Inherits AbstractCodeModelObjectTests(Of EnvDTE80.FileCodeModel2)
Protected Async Function TestOperation(code As XElement, expectedCode As XElement, operation As Action(Of EnvDTE80.FileCodeModel2)) As Task
WpfTestRunner.RequireWpfFact($"Test calls {NameOf(Me.TestOperation)} which means we're creating new {NameOf(EnvDTE.CodeModel)} elements.")
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim fileCodeModel = state.FileCodeModel
Assert.NotNull(fileCodeModel)
operation(fileCodeModel)
Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString()
Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim())
End Using
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim fileCodeModel = state.FileCodeModel
Assert.NotNull(fileCodeModel)
fileCodeModel.BeginBatch()
operation(fileCodeModel)
fileCodeModel.EndBatch()
Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString()
Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim())
End Using
End Function
Protected Sub TestOperation(code As XElement, operation As Action(Of EnvDTE80.FileCodeModel2))
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim fileCodeModel = state.FileCodeModel
Assert.NotNull(fileCodeModel)
operation(fileCodeModel)
End Using
Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code))
Dim fileCodeModel = state.FileCodeModel
Assert.NotNull(fileCodeModel)
fileCodeModel.BeginBatch()
operation(fileCodeModel)
fileCodeModel.EndBatch()
End Using
End Sub
Protected Overrides Sub TestChildren(code As XElement, ParamArray expectedChildren() As Action(Of Object))
TestOperation(code,
Sub(fileCodeModel)
Dim children = fileCodeModel.CodeElements
Assert.Equal(expectedChildren.Length, children.Count)
For i = 1 To children.Count
expectedChildren(i - 1)(children.Item(i))
Next
End Sub)
End Sub
Protected Overrides Async Function TestAddAttribute(code As XElement, expectedCode As XElement, data As AttributeData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newAttribute = fileCodeModel.AddAttribute(data.Name, data.Value, data.Position)
Assert.NotNull(newAttribute)
Assert.Equal(data.Name, newAttribute.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddClass(code As XElement, expectedCode As XElement, data As ClassData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newClass = fileCodeModel.AddClass(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access)
Assert.NotNull(newClass)
Assert.Equal(data.Name, newClass.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddDelegate(code As XElement, expectedCode As XElement, data As DelegateData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newDelegate = fileCodeModel.AddDelegate(data.Name, data.Type, data.Position, data.Access)
Assert.NotNull(newDelegate)
Assert.Equal(data.Name, newDelegate.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddEnum(code As XElement, expectedCode As XElement, data As EnumData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newEnum = fileCodeModel.AddEnum(data.Name, data.Position, data.Base, data.Access)
Assert.NotNull(newEnum)
Assert.Equal(data.Name, newEnum.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddFunction(code As XElement, expectedCode As XElement, data As FunctionData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Assert.Throws(Of System.Runtime.InteropServices.COMException)(
Sub()
fileCodeModel.AddFunction(data.Name, data.Kind, data.Type, data.Position, data.Access)
End Sub)
End Sub)
End Function
Protected Overrides Async Function TestAddImport(code As XElement, expectedCode As XElement, data As ImportData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newImport = fileCodeModel.AddImport(data.Namespace, data.Position, data.Alias)
Assert.NotNull(newImport)
Assert.Equal(data.Namespace, newImport.Namespace)
If data.Alias IsNot Nothing Then
Assert.Equal(data.Alias, newImport.Alias)
End If
End Sub)
End Function
Protected Overrides Async Function TestAddInterface(code As XElement, expectedCode As XElement, data As InterfaceData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newInterface = fileCodeModel.AddInterface(data.Name, data.Position, data.Bases, data.Access)
Assert.NotNull(newInterface)
Assert.Equal(data.Name, newInterface.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddNamespace(code As XElement, expectedCode As XElement, data As NamespaceData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newNamespace = fileCodeModel.AddNamespace(data.Name, data.Position)
Assert.NotNull(newNamespace)
Assert.Equal(data.Name, newNamespace.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddStruct(code As XElement, expectedCode As XElement, data As StructData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Dim newStruct = fileCodeModel.AddStruct(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access)
Assert.NotNull(newStruct)
Assert.Equal(data.Name, newStruct.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddVariable(code As XElement, expectedCode As XElement, data As VariableData) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
Assert.Throws(Of System.Runtime.InteropServices.COMException)(
Sub()
fileCodeModel.AddVariable(data.Name, data.Type, data.Position, data.Access)
End Sub)
End Sub)
End Function
Protected Overrides Async Function TestRemoveChild(code As XElement, expectedCode As XElement, element As Object) As Task
Await TestOperation(code, expectedCode,
Sub(fileCodeModel)
fileCodeModel.Remove(element)
End Sub)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/VisualStudio/IntegrationTest/TestUtilities/ActivityLogCollector.cs | // 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.IO;
using System.Text;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities
{
internal static class ActivityLogCollector
{
internal static void TryWriteActivityLogToFile(string filePath)
{
var vsAppDataDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft", "VisualStudio");
if (!Directory.Exists(vsAppDataDirectory))
return;
var content = new StringBuilder();
foreach (var folder in Directory.GetDirectories(vsAppDataDirectory, $"{Settings.Default.VsProductVersion}*{Settings.Default.VsRootSuffix}"))
{
var activityLog = Path.Combine(folder, "ActivityLog.xml");
if (File.Exists(activityLog))
{
try
{
content.AppendLine(File.ReadAllText(activityLog));
}
catch (Exception e)
{
content.AppendLine(e.ToString());
}
}
}
File.WriteAllText(filePath, content.ToString(), Encoding.UTF8);
}
}
}
| // 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.IO;
using System.Text;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities
{
internal static class ActivityLogCollector
{
internal static void TryWriteActivityLogToFile(string filePath)
{
var vsAppDataDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft", "VisualStudio");
if (!Directory.Exists(vsAppDataDirectory))
return;
var content = new StringBuilder();
foreach (var folder in Directory.GetDirectories(vsAppDataDirectory, $"{Settings.Default.VsProductVersion}*{Settings.Default.VsRootSuffix}"))
{
var activityLog = Path.Combine(folder, "ActivityLog.xml");
if (File.Exists(activityLog))
{
try
{
content.AppendLine(File.ReadAllText(activityLog));
}
catch (Exception e)
{
content.AppendLine(e.ToString());
}
}
}
File.WriteAllText(filePath, content.ToString(), Encoding.UTF8);
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/SerializableImportCompletionItem.cs | // 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.Runtime.Serialization;
namespace Microsoft.CodeAnalysis.Completion.Providers
{
[DataContract]
internal readonly struct SerializableImportCompletionItem
{
[DataMember(Order = 0)]
public readonly string SymbolKeyData;
[DataMember(Order = 1)]
public readonly string Name;
[DataMember(Order = 2)]
public readonly int Arity;
[DataMember(Order = 3)]
public readonly Glyph Glyph;
[DataMember(Order = 4)]
public readonly string ContainingNamespace;
[DataMember(Order = 5)]
public readonly int AdditionalOverloadCount;
[DataMember(Order = 6)]
public readonly bool IncludedInTargetTypeCompletion;
public SerializableImportCompletionItem(string symbolKeyData, string name, int arity, Glyph glyph, string containingNamespace, int additionalOverloadCount, bool includedInTargetTypeCompletion)
{
SymbolKeyData = symbolKeyData;
Arity = arity;
Name = name;
Glyph = glyph;
ContainingNamespace = containingNamespace;
AdditionalOverloadCount = additionalOverloadCount;
IncludedInTargetTypeCompletion = includedInTargetTypeCompletion;
}
}
}
| // 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.Runtime.Serialization;
namespace Microsoft.CodeAnalysis.Completion.Providers
{
[DataContract]
internal readonly struct SerializableImportCompletionItem
{
[DataMember(Order = 0)]
public readonly string SymbolKeyData;
[DataMember(Order = 1)]
public readonly string Name;
[DataMember(Order = 2)]
public readonly int Arity;
[DataMember(Order = 3)]
public readonly Glyph Glyph;
[DataMember(Order = 4)]
public readonly string ContainingNamespace;
[DataMember(Order = 5)]
public readonly int AdditionalOverloadCount;
[DataMember(Order = 6)]
public readonly bool IncludedInTargetTypeCompletion;
public SerializableImportCompletionItem(string symbolKeyData, string name, int arity, Glyph glyph, string containingNamespace, int additionalOverloadCount, bool includedInTargetTypeCompletion)
{
SymbolKeyData = symbolKeyData;
Arity = arity;
Name = name;
Glyph = glyph;
ContainingNamespace = containingNamespace;
AdditionalOverloadCount = additionalOverloadCount;
IncludedInTargetTypeCompletion = includedInTargetTypeCompletion;
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/GeneratedNameParser.vb | ' 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.
Imports System.Globalization
Imports System.Runtime.InteropServices
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend NotInheritable Class GeneratedNameParser
Friend Shared Function GetKind(name As String) As GeneratedNameKind
If name.StartsWith(GeneratedNameConstants.HoistedMeName, StringComparison.Ordinal) Then
Return GeneratedNameKind.HoistedMeField
ElseIf name.StartsWith(GeneratedNameConstants.StateMachineStateFieldName, StringComparison.Ordinal) Then
Return GeneratedNameKind.StateMachineStateField
ElseIf name.StartsWith(GeneratedNameConstants.StaticLocalFieldNamePrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.StaticLocalField
ElseIf name.StartsWith(GeneratedNameConstants.HoistedSynthesizedLocalPrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.HoistedSynthesizedLocalField
ElseIf name.StartsWith(GeneratedNameConstants.HoistedUserVariablePrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.HoistedUserVariableField
ElseIf name.StartsWith(GeneratedNameConstants.IteratorCurrentFieldName, StringComparison.Ordinal) Then
Return GeneratedNameKind.IteratorCurrentField
ElseIf name.StartsWith(GeneratedNameConstants.IteratorInitialThreadIdName, StringComparison.Ordinal) Then
Return GeneratedNameKind.IteratorInitialThreadIdField
ElseIf name.StartsWith(GeneratedNameConstants.IteratorParameterProxyPrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.IteratorParameterProxyField
ElseIf name.StartsWith(GeneratedNameConstants.StateMachineAwaiterFieldPrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.StateMachineAwaiterField
ElseIf name.StartsWith(GeneratedNameConstants.StateMachineHoistedUserVariablePrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.StateMachineHoistedUserVariableField
ElseIf name.StartsWith(GeneratedNameConstants.AnonymousTypeTemplateNamePrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.AnonymousType
ElseIf name.StartsWith(GeneratedNameConstants.DisplayClassPrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.LambdaDisplayClass
ElseIf name.Equals(GeneratedNameConstants.It, StringComparison.Ordinal) OrElse
name.Equals(GeneratedNameConstants.It1, StringComparison.Ordinal) OrElse
name.Equals(GeneratedNameConstants.It2, StringComparison.Ordinal) Then
Return GeneratedNameKind.TransparentIdentifier
ElseIf name.Equals(GeneratedNameConstants.ItAnonymous, StringComparison.Ordinal) Then
' We distinguish GeneratedNameConstants.ItAnonymous, because it won't be an instance
' of an anonymous type.
Return GeneratedNameKind.AnonymousTransparentIdentifier
End If
Return GeneratedNameKind.None
End Function
Public Shared Function TryParseStateMachineTypeName(stateMachineTypeName As String, <Out> ByRef methodName As String) As Boolean
If Not stateMachineTypeName.StartsWith(GeneratedNameConstants.StateMachineTypeNamePrefix, StringComparison.Ordinal) Then
Return False
End If
Dim prefixLength As Integer = GeneratedNameConstants.StateMachineTypeNamePrefix.Length
Dim separatorPos = stateMachineTypeName.IndexOf(GeneratedNameConstants.MethodNameSeparator, prefixLength)
If separatorPos < 0 OrElse separatorPos = stateMachineTypeName.Length - 1 Then
Return False
End If
methodName = stateMachineTypeName.Substring(separatorPos + 1)
Return True
End Function
''' <summary>
''' Try to parse the local (or parameter) name and return <paramref name="variableName"/> if successful.
''' </summary>
Public Shared Function TryParseHoistedUserVariableName(proxyName As String, <Out> ByRef variableName As String) As Boolean
variableName = Nothing
Dim prefixLen As Integer = GeneratedNameConstants.HoistedUserVariablePrefix.Length
If proxyName.Length <= prefixLen Then
Return False
End If
' All names should start with "$VB$Local_"
If Not proxyName.StartsWith(GeneratedNameConstants.HoistedUserVariablePrefix, StringComparison.Ordinal) Then
Return False
End If
variableName = proxyName.Substring(prefixLen)
Return True
End Function
''' <summary>
''' Try to parse the local name and return <paramref name="variableName"/> and <paramref name="index"/> if successful.
''' </summary>
Public Shared Function TryParseStateMachineHoistedUserVariableName(proxyName As String, <Out> ByRef variableName As String, <Out()> ByRef index As Integer) As Boolean
variableName = Nothing
index = 0
' All names should start with "$VB$ResumableLocal_"
If Not proxyName.StartsWith(GeneratedNameConstants.StateMachineHoistedUserVariablePrefix, StringComparison.Ordinal) Then
Return False
End If
Dim prefixLen As Integer = GeneratedNameConstants.StateMachineHoistedUserVariablePrefix.Length
Dim separator As Integer = proxyName.LastIndexOf("$"c)
If separator <= prefixLen Then
Return False
End If
variableName = proxyName.Substring(prefixLen, separator - prefixLen)
Return Integer.TryParse(proxyName.Substring(separator + 1), NumberStyles.None, CultureInfo.InvariantCulture, index)
End Function
Friend Shared Function TryParseStaticLocalFieldName(
fieldName As String,
<Out> ByRef methodName As String,
<Out> ByRef methodSignature As String,
<Out> ByRef localName As String) As Boolean
If fieldName.StartsWith(GeneratedNameConstants.StaticLocalFieldNamePrefix, StringComparison.Ordinal) Then
Dim parts = fieldName.Split("$"c)
If parts.Length = 5 Then
methodName = parts(2)
methodSignature = parts(3)
localName = parts(4)
Return True
End If
End If
methodName = Nothing
methodSignature = Nothing
localName = Nothing
Return False
End Function
' Extracts the slot index from a name of a field that stores hoisted variables or awaiters.
' Such a name ends with "$prefix{slot index}".
' Returned slot index is >= 0.
Friend Shared Function TryParseSlotIndex(prefix As String, fieldName As String, <Out> ByRef slotIndex As Integer) As Boolean
If fieldName.StartsWith(prefix, StringComparison.Ordinal) AndAlso
Integer.TryParse(fieldName.Substring(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, slotIndex) Then
Return True
End If
slotIndex = -1
Return False
End Function
End Class
End Namespace
| ' 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.
Imports System.Globalization
Imports System.Runtime.InteropServices
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend NotInheritable Class GeneratedNameParser
Friend Shared Function GetKind(name As String) As GeneratedNameKind
If name.StartsWith(GeneratedNameConstants.HoistedMeName, StringComparison.Ordinal) Then
Return GeneratedNameKind.HoistedMeField
ElseIf name.StartsWith(GeneratedNameConstants.StateMachineStateFieldName, StringComparison.Ordinal) Then
Return GeneratedNameKind.StateMachineStateField
ElseIf name.StartsWith(GeneratedNameConstants.StaticLocalFieldNamePrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.StaticLocalField
ElseIf name.StartsWith(GeneratedNameConstants.HoistedSynthesizedLocalPrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.HoistedSynthesizedLocalField
ElseIf name.StartsWith(GeneratedNameConstants.HoistedUserVariablePrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.HoistedUserVariableField
ElseIf name.StartsWith(GeneratedNameConstants.IteratorCurrentFieldName, StringComparison.Ordinal) Then
Return GeneratedNameKind.IteratorCurrentField
ElseIf name.StartsWith(GeneratedNameConstants.IteratorInitialThreadIdName, StringComparison.Ordinal) Then
Return GeneratedNameKind.IteratorInitialThreadIdField
ElseIf name.StartsWith(GeneratedNameConstants.IteratorParameterProxyPrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.IteratorParameterProxyField
ElseIf name.StartsWith(GeneratedNameConstants.StateMachineAwaiterFieldPrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.StateMachineAwaiterField
ElseIf name.StartsWith(GeneratedNameConstants.StateMachineHoistedUserVariablePrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.StateMachineHoistedUserVariableField
ElseIf name.StartsWith(GeneratedNameConstants.AnonymousTypeTemplateNamePrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.AnonymousType
ElseIf name.StartsWith(GeneratedNameConstants.DisplayClassPrefix, StringComparison.Ordinal) Then
Return GeneratedNameKind.LambdaDisplayClass
ElseIf name.Equals(GeneratedNameConstants.It, StringComparison.Ordinal) OrElse
name.Equals(GeneratedNameConstants.It1, StringComparison.Ordinal) OrElse
name.Equals(GeneratedNameConstants.It2, StringComparison.Ordinal) Then
Return GeneratedNameKind.TransparentIdentifier
ElseIf name.Equals(GeneratedNameConstants.ItAnonymous, StringComparison.Ordinal) Then
' We distinguish GeneratedNameConstants.ItAnonymous, because it won't be an instance
' of an anonymous type.
Return GeneratedNameKind.AnonymousTransparentIdentifier
End If
Return GeneratedNameKind.None
End Function
Public Shared Function TryParseStateMachineTypeName(stateMachineTypeName As String, <Out> ByRef methodName As String) As Boolean
If Not stateMachineTypeName.StartsWith(GeneratedNameConstants.StateMachineTypeNamePrefix, StringComparison.Ordinal) Then
Return False
End If
Dim prefixLength As Integer = GeneratedNameConstants.StateMachineTypeNamePrefix.Length
Dim separatorPos = stateMachineTypeName.IndexOf(GeneratedNameConstants.MethodNameSeparator, prefixLength)
If separatorPos < 0 OrElse separatorPos = stateMachineTypeName.Length - 1 Then
Return False
End If
methodName = stateMachineTypeName.Substring(separatorPos + 1)
Return True
End Function
''' <summary>
''' Try to parse the local (or parameter) name and return <paramref name="variableName"/> if successful.
''' </summary>
Public Shared Function TryParseHoistedUserVariableName(proxyName As String, <Out> ByRef variableName As String) As Boolean
variableName = Nothing
Dim prefixLen As Integer = GeneratedNameConstants.HoistedUserVariablePrefix.Length
If proxyName.Length <= prefixLen Then
Return False
End If
' All names should start with "$VB$Local_"
If Not proxyName.StartsWith(GeneratedNameConstants.HoistedUserVariablePrefix, StringComparison.Ordinal) Then
Return False
End If
variableName = proxyName.Substring(prefixLen)
Return True
End Function
''' <summary>
''' Try to parse the local name and return <paramref name="variableName"/> and <paramref name="index"/> if successful.
''' </summary>
Public Shared Function TryParseStateMachineHoistedUserVariableName(proxyName As String, <Out> ByRef variableName As String, <Out()> ByRef index As Integer) As Boolean
variableName = Nothing
index = 0
' All names should start with "$VB$ResumableLocal_"
If Not proxyName.StartsWith(GeneratedNameConstants.StateMachineHoistedUserVariablePrefix, StringComparison.Ordinal) Then
Return False
End If
Dim prefixLen As Integer = GeneratedNameConstants.StateMachineHoistedUserVariablePrefix.Length
Dim separator As Integer = proxyName.LastIndexOf("$"c)
If separator <= prefixLen Then
Return False
End If
variableName = proxyName.Substring(prefixLen, separator - prefixLen)
Return Integer.TryParse(proxyName.Substring(separator + 1), NumberStyles.None, CultureInfo.InvariantCulture, index)
End Function
Friend Shared Function TryParseStaticLocalFieldName(
fieldName As String,
<Out> ByRef methodName As String,
<Out> ByRef methodSignature As String,
<Out> ByRef localName As String) As Boolean
If fieldName.StartsWith(GeneratedNameConstants.StaticLocalFieldNamePrefix, StringComparison.Ordinal) Then
Dim parts = fieldName.Split("$"c)
If parts.Length = 5 Then
methodName = parts(2)
methodSignature = parts(3)
localName = parts(4)
Return True
End If
End If
methodName = Nothing
methodSignature = Nothing
localName = Nothing
Return False
End Function
' Extracts the slot index from a name of a field that stores hoisted variables or awaiters.
' Such a name ends with "$prefix{slot index}".
' Returned slot index is >= 0.
Friend Shared Function TryParseSlotIndex(prefix As String, fieldName As String, <Out> ByRef slotIndex As Integer) As Boolean
If fieldName.StartsWith(prefix, StringComparison.Ordinal) AndAlso
Integer.TryParse(fieldName.Substring(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, slotIndex) Then
Return True
End If
slotIndex = -1
Return False
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/VisualStudio/Core/Test/Venus/ContainedDocumentTests.vb | ' 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.
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus
Public Class ContainedDocumentTests
<Fact>
Public Sub ContainedDocument_AcceptsNullInput()
Dim documentId = ContainedDocument.TryGetContainedDocument(Nothing)
Assert.Null(documentId)
End Sub
End Class
End Namespace
| ' 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.
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus
Public Class ContainedDocumentTests
<Fact>
Public Sub ContainedDocument_AcceptsNullInput()
Dim documentId = ContainedDocument.TryGetContainedDocument(Nothing)
Assert.Null(documentId)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/EditorFeatures/VisualBasicTest/Recommendations/Statements/EndKeywordRecommenderTests.vb | ' 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.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements
Public Class EndKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EndInMethodBodyTest()
' It's always a statement (or at least for now)
VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "End")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EndAfterStatementTest()
VerifyRecommendationsContain(<MethodBody>
Dim x
|</MethodBody>, "End")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EndMissingInClassBlockTest()
VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "End")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EndInSingleLineLambdaTest()
VerifyRecommendationsContain(<MethodBody>Dim x = Sub() |</MethodBody>, "End")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EndNotInSingleLineFunctionLambdaTest()
VerifyRecommendationsMissing(<MethodBody>Dim x = Function() |</MethodBody>, "End")
End Sub
<WorkItem(530599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530599")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EndNotOutsideOfMethodBodyTest()
VerifyRecommendationsMissing(<MethodBody>Class C
|</MethodBody>, "End")
End Sub
End Class
End Namespace
| ' 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.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements
Public Class EndKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EndInMethodBodyTest()
' It's always a statement (or at least for now)
VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "End")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EndAfterStatementTest()
VerifyRecommendationsContain(<MethodBody>
Dim x
|</MethodBody>, "End")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EndMissingInClassBlockTest()
VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "End")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EndInSingleLineLambdaTest()
VerifyRecommendationsContain(<MethodBody>Dim x = Sub() |</MethodBody>, "End")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EndNotInSingleLineFunctionLambdaTest()
VerifyRecommendationsMissing(<MethodBody>Dim x = Function() |</MethodBody>, "End")
End Sub
<WorkItem(530599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530599")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EndNotOutsideOfMethodBodyTest()
VerifyRecommendationsMissing(<MethodBody>Class C
|</MethodBody>, "End")
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ValuesSources/ValueSource.cs | // 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.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
namespace Roslyn.Utilities
{
/// <summary>
/// A class that abstracts the accessing of a value that is guaranteed to be available at some point.
/// </summary>
internal abstract class ValueSource<T>
{
public abstract bool TryGetValue([MaybeNullWhen(false)] out T value);
public abstract T GetValue(CancellationToken cancellationToken = default);
public abstract Task<T> GetValueAsync(CancellationToken cancellationToken = default);
}
internal static class ValueSourceExtensions
{
internal static T? GetValueOrNull<T>(this Optional<T> optional) where T : class
=> optional.Value;
internal static T GetValueOrDefault<T>(this Optional<T> optional) where T : struct
=> optional.Value;
internal static T? GetValueOrNull<T>(this ValueSource<Optional<T>> optional, CancellationToken cancellationToken = default) where T : class
=> optional.GetValue(cancellationToken).GetValueOrNull();
internal static T GetValueOrDefault<T>(this ValueSource<Optional<T>> optional, CancellationToken cancellationToken = default) where T : struct
=> optional.GetValue(cancellationToken).GetValueOrDefault();
}
}
| // 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.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
namespace Roslyn.Utilities
{
/// <summary>
/// A class that abstracts the accessing of a value that is guaranteed to be available at some point.
/// </summary>
internal abstract class ValueSource<T>
{
public abstract bool TryGetValue([MaybeNullWhen(false)] out T value);
public abstract T GetValue(CancellationToken cancellationToken = default);
public abstract Task<T> GetValueAsync(CancellationToken cancellationToken = default);
}
internal static class ValueSourceExtensions
{
internal static T? GetValueOrNull<T>(this Optional<T> optional) where T : class
=> optional.Value;
internal static T GetValueOrDefault<T>(this Optional<T> optional) where T : struct
=> optional.Value;
internal static T? GetValueOrNull<T>(this ValueSource<Optional<T>> optional, CancellationToken cancellationToken = default) where T : class
=> optional.GetValue(cancellationToken).GetValueOrNull();
internal static T GetValueOrDefault<T>(this ValueSource<Optional<T>> optional, CancellationToken cancellationToken = default) where T : struct
=> optional.GetValue(cancellationToken).GetValueOrDefault();
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/CSharp/Portable/Syntax/SwitchStatementSyntax.cs | // 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 Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class SwitchStatementSyntax
{
public SwitchStatementSyntax Update(SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList<SwitchSectionSyntax> sections, SyntaxToken closeBraceToken)
=> Update(AttributeLists, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static SwitchStatementSyntax SwitchStatement(SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList<SwitchSectionSyntax> sections, SyntaxToken closeBraceToken)
=> SwitchStatement(attributeLists: default, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken);
}
}
| // 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 Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class SwitchStatementSyntax
{
public SwitchStatementSyntax Update(SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList<SwitchSectionSyntax> sections, SyntaxToken closeBraceToken)
=> Update(AttributeLists, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static SwitchStatementSyntax SwitchStatement(SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList<SwitchSectionSyntax> sections, SyntaxToken closeBraceToken)
=> SwitchStatement(attributeLists: default, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken);
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/UnusedParametersPreference.cs | // 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.CodeAnalysis.CodeStyle
{
/// <summary>
/// Preferences for flagging unused parameters.
/// </summary>
internal enum UnusedParametersPreference
{
// Ununsed parameters of non-public methods are flagged.
NonPublicMethods = 0,
// Unused parameters of methods with any accessibility (private/public/protected/internal) are flagged.
AllMethods = 1,
}
}
| // 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.CodeAnalysis.CodeStyle
{
/// <summary>
/// Preferences for flagging unused parameters.
/// </summary>
internal enum UnusedParametersPreference
{
// Ununsed parameters of non-public methods are flagged.
NonPublicMethods = 0,
// Unused parameters of methods with any accessibility (private/public/protected/internal) are flagged.
AllMethods = 1,
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/VisualBasic/Test/Semantic/Compilation/MyTemplateTests.vb | ' 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.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class MyTemplateTests
Inherits BasicTestBase
Friend Shared Function GetMyTemplateTree(compilation As VisualBasicCompilation) As SyntaxTree
Dim MyTemplate As SyntaxTree = Nothing
For Each tree In compilation.AllSyntaxTrees
If tree.IsMyTemplate Then
' should be only one My template
Assert.Null(MyTemplate)
MyTemplate = tree
End If
Next
Return MyTemplate
End Function
<Fact()>
Public Sub LoadMyTemplate()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Module M1
Sub Main
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources,
references:={MsvbRef},
options:=TestOptions.ReleaseDll)
Dim MyTemplate = GetMyTemplateTree(compilation)
Assert.NotNull(MyTemplate)
Dim text = MyTemplate.GetText.ToString
Assert.Contains("Private ReadOnly m_Context As New Global.Microsoft.VisualBasic.MyServices.Internal.ContextValue(Of T)", text, StringComparison.Ordinal)
End Sub
<Fact()>
Public Sub LoadMyTemplateNoRuntime()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Module M1
Sub Main
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources,
references:={SystemCoreRef},
options:=TestOptions.ReleaseDll)
Dim MyTemplate = GetMyTemplateTree(compilation)
Dim text = MyTemplate.GetText.ToString
Assert.Contains("Private ReadOnly m_Context As New Global.Microsoft.VisualBasic.MyServices.Internal.ContextValue(Of T)", text, StringComparison.Ordinal)
End Sub
<Fact()>
Public Sub LoadMyTemplateRuntimeNotFile()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Module M1
Sub Main
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources,
references:={SystemCoreRef, MsvbRef},
options:=TestOptions.ReleaseDll)
Dim MyTemplate = GetMyTemplateTree(compilation)
Dim text = MyTemplate.GetText.ToString
Assert.Contains("Private ReadOnly m_Context As New Global.Microsoft.VisualBasic.MyServices.Internal.ContextValue(Of T)", text, StringComparison.Ordinal)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub MyConsoleApp()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Imports System
Module Module1
Sub Main()
Console.WriteLine(My.Application.IsNetworkDeployed)
End Sub
End Module
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(sources, options:=compilationOptions)
CompileAndVerify(compilation, expectedOutput:="False")
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), GetType(HasValidFonts), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub MyWinformApp()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Imports System
Module m1
Function Test As String
Return My.Forms.Form1.Text
End Function
End Module
Public Class Form1
Private Sub Form1_Load( sender As Object, e As EventArgs) Handles MyBase.Load
Console.WriteLine(Test)
Me.Close
End Sub
End Class
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.SuspendLayout
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6!, 13!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(292, 273)
Me.Name = "Form1"
Me.Text = "HelloWinform"
Me.WindowState = System.Windows.Forms.FormWindowState.Minimized
Me.ResumeLayout(false)
End Sub
End Class
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.WindowsApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("WindowsForms")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithOutputKind(OutputKind.WindowsApplication).WithParseOptions(parseOptions).WithMainTypeName("Form1")
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources, {SystemWindowsFormsRef, SystemDrawingRef}, compilationOptions)
compilation.VerifyDiagnostics()
CompileAndVerify(compilation, expectedOutput:="HelloWinform")
End Sub
<Fact()>
Public Sub MyApplicationSemanticInfo()
Dim sources = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Module1
Sub Main()
Console.WriteLine(My.Application.IsNetworkDeployed)'BIND:"Application"
End Sub
End Module
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(sources, options:=compilationOptions)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Equal("My.MyApplication", semanticSummary.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind)
Assert.Equal("My.MyApplication", semanticSummary.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason)
Assert.Equal(0, semanticSummary.CandidateSymbols.Length)
Assert.Null(semanticSummary.Alias)
Assert.Equal(0, semanticSummary.MemberGroup.Length)
Assert.False(semanticSummary.ConstantValue.HasValue)
Dim sym = semanticSummary.Symbol
Assert.IsType(Of MyTemplateLocation)(sym.Locations(0))
Assert.True(sym.DeclaringSyntaxReferences.IsEmpty)
End Sub
<Fact()>
Public Sub MySettingExtraMember()
Dim sources = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
My.Application.Goo()'BIND:"Goo"
End Sub
End Module
Namespace My
Partial Class MyApplication
Public Function Goo() As Integer
Return 1
End Function
End Class
End Namespace
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(sources, options:=compilationOptions)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("Function My.MyApplication.Goo() As System.Int32", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind)
Assert.Equal(0, semanticSummary.CandidateSymbols.Length)
Assert.Null(semanticSummary.Alias)
Assert.Equal(1, semanticSummary.MemberGroup.Length)
Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Function My.MyApplication.Goo() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.False(semanticSummary.ConstantValue.HasValue)
Dim sym = semanticSummary.Symbol
Assert.IsType(Of SourceLocation)(sym.Locations(0))
Assert.Equal("Public Function Goo() As Integer", sym.DeclaringSyntaxReferences(0).GetSyntax().ToString())
Dim parent = sym.ContainingType
Assert.Equal(1, parent.Locations.OfType(Of SourceLocation).Count)
Assert.Equal(1, parent.Locations.OfType(Of MyTemplateLocation).Count)
Assert.Equal("Partial Class MyApplication", parent.DeclaringSyntaxReferences.Single.GetSyntax.ToString)
End Sub
End Class
End Namespace
| ' 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.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class MyTemplateTests
Inherits BasicTestBase
Friend Shared Function GetMyTemplateTree(compilation As VisualBasicCompilation) As SyntaxTree
Dim MyTemplate As SyntaxTree = Nothing
For Each tree In compilation.AllSyntaxTrees
If tree.IsMyTemplate Then
' should be only one My template
Assert.Null(MyTemplate)
MyTemplate = tree
End If
Next
Return MyTemplate
End Function
<Fact()>
Public Sub LoadMyTemplate()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Module M1
Sub Main
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources,
references:={MsvbRef},
options:=TestOptions.ReleaseDll)
Dim MyTemplate = GetMyTemplateTree(compilation)
Assert.NotNull(MyTemplate)
Dim text = MyTemplate.GetText.ToString
Assert.Contains("Private ReadOnly m_Context As New Global.Microsoft.VisualBasic.MyServices.Internal.ContextValue(Of T)", text, StringComparison.Ordinal)
End Sub
<Fact()>
Public Sub LoadMyTemplateNoRuntime()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Module M1
Sub Main
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources,
references:={SystemCoreRef},
options:=TestOptions.ReleaseDll)
Dim MyTemplate = GetMyTemplateTree(compilation)
Dim text = MyTemplate.GetText.ToString
Assert.Contains("Private ReadOnly m_Context As New Global.Microsoft.VisualBasic.MyServices.Internal.ContextValue(Of T)", text, StringComparison.Ordinal)
End Sub
<Fact()>
Public Sub LoadMyTemplateRuntimeNotFile()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Module M1
Sub Main
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources,
references:={SystemCoreRef, MsvbRef},
options:=TestOptions.ReleaseDll)
Dim MyTemplate = GetMyTemplateTree(compilation)
Dim text = MyTemplate.GetText.ToString
Assert.Contains("Private ReadOnly m_Context As New Global.Microsoft.VisualBasic.MyServices.Internal.ContextValue(Of T)", text, StringComparison.Ordinal)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub MyConsoleApp()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Imports System
Module Module1
Sub Main()
Console.WriteLine(My.Application.IsNetworkDeployed)
End Sub
End Module
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(sources, options:=compilationOptions)
CompileAndVerify(compilation, expectedOutput:="False")
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), GetType(HasValidFonts), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub MyWinformApp()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Imports System
Module m1
Function Test As String
Return My.Forms.Form1.Text
End Function
End Module
Public Class Form1
Private Sub Form1_Load( sender As Object, e As EventArgs) Handles MyBase.Load
Console.WriteLine(Test)
Me.Close
End Sub
End Class
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.SuspendLayout
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6!, 13!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(292, 273)
Me.Name = "Form1"
Me.Text = "HelloWinform"
Me.WindowState = System.Windows.Forms.FormWindowState.Minimized
Me.ResumeLayout(false)
End Sub
End Class
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.WindowsApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("WindowsForms")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithOutputKind(OutputKind.WindowsApplication).WithParseOptions(parseOptions).WithMainTypeName("Form1")
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources, {SystemWindowsFormsRef, SystemDrawingRef}, compilationOptions)
compilation.VerifyDiagnostics()
CompileAndVerify(compilation, expectedOutput:="HelloWinform")
End Sub
<Fact()>
Public Sub MyApplicationSemanticInfo()
Dim sources = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Module1
Sub Main()
Console.WriteLine(My.Application.IsNetworkDeployed)'BIND:"Application"
End Sub
End Module
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(sources, options:=compilationOptions)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Equal("My.MyApplication", semanticSummary.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind)
Assert.Equal("My.MyApplication", semanticSummary.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason)
Assert.Equal(0, semanticSummary.CandidateSymbols.Length)
Assert.Null(semanticSummary.Alias)
Assert.Equal(0, semanticSummary.MemberGroup.Length)
Assert.False(semanticSummary.ConstantValue.HasValue)
Dim sym = semanticSummary.Symbol
Assert.IsType(Of MyTemplateLocation)(sym.Locations(0))
Assert.True(sym.DeclaringSyntaxReferences.IsEmpty)
End Sub
<Fact()>
Public Sub MySettingExtraMember()
Dim sources = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
My.Application.Goo()'BIND:"Goo"
End Sub
End Module
Namespace My
Partial Class MyApplication
Public Function Goo() As Integer
Return 1
End Function
End Class
End Namespace
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(sources, options:=compilationOptions)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("Function My.MyApplication.Goo() As System.Int32", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind)
Assert.Equal(0, semanticSummary.CandidateSymbols.Length)
Assert.Null(semanticSummary.Alias)
Assert.Equal(1, semanticSummary.MemberGroup.Length)
Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Function My.MyApplication.Goo() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.False(semanticSummary.ConstantValue.HasValue)
Dim sym = semanticSummary.Symbol
Assert.IsType(Of SourceLocation)(sym.Locations(0))
Assert.Equal("Public Function Goo() As Integer", sym.DeclaringSyntaxReferences(0).GetSyntax().ToString())
Dim parent = sym.ContainingType
Assert.Equal(1, parent.Locations.OfType(Of SourceLocation).Count)
Assert.Equal(1, parent.Locations.OfType(Of MyTemplateLocation).Count)
Assert.Equal("Partial Class MyApplication", parent.DeclaringSyntaxReferences.Single.GetSyntax.ToString)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/NamedParameterCompletionProviderTests.cs | // 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.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources
{
public class NamedParameterCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType()
=> typeof(NamedParameterCompletionProvider);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SendEnterThroughToEditorTest()
{
const string markup = @"
class Goo
{
public Goo(int a = 42)
{ }
void Bar()
{
var b = new Goo($$
}
}";
await VerifySendEnterThroughToEnterAsync(markup, "a:", sendThroughEnterOption: EnterKeyRule.Never, expected: false);
await VerifySendEnterThroughToEnterAsync(markup, "a:", sendThroughEnterOption: EnterKeyRule.AfterFullyTypedWord, expected: true);
await VerifySendEnterThroughToEnterAsync(markup, "a:", sendThroughEnterOption: EnterKeyRule.Always, expected: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommitCharacterTest()
{
const string markup = @"
class Goo
{
public Goo(int a = 42)
{ }
void Bar()
{
var b = new Goo($$
}
}";
await VerifyCommonCommitCharactersAsync(markup, textTypedSoFar: "");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InObjectCreation()
{
var markup = @"
class Goo
{
public Goo(int a = 42)
{ }
void Bar()
{
var b = new Goo($$
}
}";
await VerifyItemExistsAsync(markup, "a", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InBaseConstructor()
{
var markup = @"
class Goo
{
public Goo(int a = 42)
{ }
}
class DogBed : Goo
{
public DogBed(int b) : base($$
}
";
await VerifyItemExistsAsync(markup, "a", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InvocationExpression()
{
var markup = @"
class Goo
{
void Bar(int a)
{
Bar($$
}
}
";
await VerifyItemExistsAsync(markup, "a", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InvocationExpressionAfterComma()
{
var markup = @"
class Goo
{
void Bar(int a, string b)
{
Bar(b:"""", $$
}
}
";
await VerifyItemExistsAsync(markup, "a", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ElementAccessExpression()
{
var markup = @"
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get
{
return arr[i];
}
set
{
arr[i] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[$$
}
}
";
await VerifyItemExistsAsync(markup, "i", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PartialMethods()
{
var markup = @"
partial class PartialClass
{
static partial void Goo(int declaring);
static partial void Goo(int implementing)
{
}
static void Caller()
{
Goo($$
}
}
";
await VerifyItemExistsAsync(markup, "declaring", displayTextSuffix: ":");
await VerifyItemIsAbsentAsync(markup, "implementing", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtendedPartialMethods()
{
var markup = @"
partial class PartialClass
{
public static partial void Goo(int declaring);
public static partial void Goo(int implementing)
{
}
static void Caller()
{
Goo($$
}
}
";
await VerifyItemExistsAsync(markup, "declaring", displayTextSuffix: ":");
await VerifyItemIsAbsentAsync(markup, "implementing", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterColon()
{
var markup = @"
class Goo
{
void Bar(int a, string b)
{
Bar(a:$$
}
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(544292, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544292")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotInCollectionInitializers()
{
var markup = @"
using System.Collections.Generic;
class Goo
{
void Bar(List<int> integers)
{
Bar(integers: new List<int> { 10, 11,$$ 12 });
}
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(544191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544191")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FilteringOverloadsByCallSite()
{
var markup = @"
class Class1
{
void Test()
{
Goo(boolean:true, $$)
}
void Goo(string str = ""hello"", char character = 'a')
{ }
void Goo(string str = ""hello"", bool boolean = false)
{ }
}
";
await VerifyItemExistsAsync(markup, "str", displayTextSuffix: ":");
await VerifyItemIsAbsentAsync(markup, "character", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DontFilterYet()
{
var markup = @"
class Class1
{
void Test()
{
Goo(str:"""", $$)
}
void Goo(string str = ""hello"", char character = 'a')
{ }
void Goo(string str = ""hello"", bool boolean = false)
{ }
}
";
await VerifyItemExistsAsync(markup, "boolean", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "character", displayTextSuffix: ":");
}
[WorkItem(544191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544191")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FilteringOverloadsByCallSiteComplex()
{
var markup = @"
class Goo
{
void Test()
{
Bar m = new Bar();
Method(obj:m, $$
}
void Method(Bar obj, int num = 23, string str = """")
{
}
void Method(double dbl = double.MinValue, string str = """")
{
}
void Method(int num = 1, bool b = false, string str = """")
{
}
void Method(Bar obj, bool b = false, string str = """")
{
}
}
class Bar { }
";
await VerifyItemExistsAsync(markup, "str", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "num", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "b", displayTextSuffix: ":");
await VerifyItemIsAbsentAsync(markup, "dbl", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloads()
{
var markup = @"
class Goo
{
void Test()
{
object m = null;
Method(m, $$
}
void Method(object obj, int num = 23, string str = """")
{
}
void Method(int num = 1, bool b = false, string str = """")
{
}
void Method(object obj, bool b = false, string str = """")
{
}
}
";
await VerifyItemExistsAsync(markup, "str", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "num", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "b", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExistingNamedParamsAreFilteredOut()
{
var markup = @"
class Goo
{
void Test()
{
object m = null;
Method(obj: m, str: """", $$);
}
void Method(object obj, int num = 23, string str = """")
{
}
void Method(double dbl = double.MinValue, string str = """")
{
}
void Method(int num = 1, bool b = false, string str = """")
{
}
void Method(object obj, bool b = false, string str = """")
{
}
}
";
await VerifyItemExistsAsync(markup, "num", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "b", displayTextSuffix: ":");
await VerifyItemIsAbsentAsync(markup, "obj", displayTextSuffix: ":");
await VerifyItemIsAbsentAsync(markup, "str", displayTextSuffix: ":");
}
[WorkItem(529369, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529369")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VerbatimIdentifierNotAKeyword()
{
var markup = @"
class Program
{
void Goo(int @integer)
{
Goo(@i$$
}
}
";
await VerifyItemExistsAsync(markup, "integer", displayTextSuffix: ":");
}
[WorkItem(544209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544209")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionStringInMethodOverloads()
{
var markup = @"
class Class1
{
void Test()
{
Goo(boolean: true, $$)
}
void Goo(string obj = ""hello"")
{ }
void Goo(bool boolean = false, Class1 obj = default(Class1))
{ }
}
";
await VerifyItemExistsAsync(markup, "obj", displayTextSuffix: ":",
expectedDescriptionOrNull: $"({FeaturesResources.parameter}) Class1 obj = default(Class1)");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InDelegates()
{
var markup = @"
public delegate void Del(string message);
class Program
{
public static void DelegateMethod(string message)
{
System.Console.WriteLine(message);
}
static void Main(string[] args)
{
Del handler = DelegateMethod;
handler($$
}
}";
await VerifyItemExistsAsync(markup, "message", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InDelegateInvokeSyntax()
{
var markup = @"
public delegate void Del(string message);
class Program
{
public static void DelegateMethod(string message)
{
System.Console.WriteLine(message);
}
static void Main(string[] args)
{
Del handler = DelegateMethod;
handler.Invoke($$
}
}";
await VerifyItemExistsAsync(markup, "message", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotInComment()
{
var markup = @"
public class Test
{
static void Main()
{
M(x: 0, //Hit ctrl-space at the end of this comment $$
y: 1);
}
static void M(int x, int y) { }
}
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommitWithColonWordFullyTyped()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
Main(args$$)
}
}
";
var expected = @"
class Program
{
static void Main(string[] args)
{
Main(args:)
}
}
";
await VerifyProviderCommitAsync(markup, "args:", expected, ':');
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommitWithColonWordPartiallyTyped()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
Main(arg$$)
}
}
";
var expected = @"
class Program
{
static void Main(string[] args)
{
Main(args:)
}
}
";
await VerifyProviderCommitAsync(markup, "args:", expected, ':');
}
}
}
| // 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.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources
{
public class NamedParameterCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType()
=> typeof(NamedParameterCompletionProvider);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SendEnterThroughToEditorTest()
{
const string markup = @"
class Goo
{
public Goo(int a = 42)
{ }
void Bar()
{
var b = new Goo($$
}
}";
await VerifySendEnterThroughToEnterAsync(markup, "a:", sendThroughEnterOption: EnterKeyRule.Never, expected: false);
await VerifySendEnterThroughToEnterAsync(markup, "a:", sendThroughEnterOption: EnterKeyRule.AfterFullyTypedWord, expected: true);
await VerifySendEnterThroughToEnterAsync(markup, "a:", sendThroughEnterOption: EnterKeyRule.Always, expected: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommitCharacterTest()
{
const string markup = @"
class Goo
{
public Goo(int a = 42)
{ }
void Bar()
{
var b = new Goo($$
}
}";
await VerifyCommonCommitCharactersAsync(markup, textTypedSoFar: "");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InObjectCreation()
{
var markup = @"
class Goo
{
public Goo(int a = 42)
{ }
void Bar()
{
var b = new Goo($$
}
}";
await VerifyItemExistsAsync(markup, "a", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InBaseConstructor()
{
var markup = @"
class Goo
{
public Goo(int a = 42)
{ }
}
class DogBed : Goo
{
public DogBed(int b) : base($$
}
";
await VerifyItemExistsAsync(markup, "a", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InvocationExpression()
{
var markup = @"
class Goo
{
void Bar(int a)
{
Bar($$
}
}
";
await VerifyItemExistsAsync(markup, "a", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InvocationExpressionAfterComma()
{
var markup = @"
class Goo
{
void Bar(int a, string b)
{
Bar(b:"""", $$
}
}
";
await VerifyItemExistsAsync(markup, "a", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ElementAccessExpression()
{
var markup = @"
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get
{
return arr[i];
}
set
{
arr[i] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[$$
}
}
";
await VerifyItemExistsAsync(markup, "i", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PartialMethods()
{
var markup = @"
partial class PartialClass
{
static partial void Goo(int declaring);
static partial void Goo(int implementing)
{
}
static void Caller()
{
Goo($$
}
}
";
await VerifyItemExistsAsync(markup, "declaring", displayTextSuffix: ":");
await VerifyItemIsAbsentAsync(markup, "implementing", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtendedPartialMethods()
{
var markup = @"
partial class PartialClass
{
public static partial void Goo(int declaring);
public static partial void Goo(int implementing)
{
}
static void Caller()
{
Goo($$
}
}
";
await VerifyItemExistsAsync(markup, "declaring", displayTextSuffix: ":");
await VerifyItemIsAbsentAsync(markup, "implementing", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterColon()
{
var markup = @"
class Goo
{
void Bar(int a, string b)
{
Bar(a:$$
}
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(544292, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544292")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotInCollectionInitializers()
{
var markup = @"
using System.Collections.Generic;
class Goo
{
void Bar(List<int> integers)
{
Bar(integers: new List<int> { 10, 11,$$ 12 });
}
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(544191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544191")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FilteringOverloadsByCallSite()
{
var markup = @"
class Class1
{
void Test()
{
Goo(boolean:true, $$)
}
void Goo(string str = ""hello"", char character = 'a')
{ }
void Goo(string str = ""hello"", bool boolean = false)
{ }
}
";
await VerifyItemExistsAsync(markup, "str", displayTextSuffix: ":");
await VerifyItemIsAbsentAsync(markup, "character", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DontFilterYet()
{
var markup = @"
class Class1
{
void Test()
{
Goo(str:"""", $$)
}
void Goo(string str = ""hello"", char character = 'a')
{ }
void Goo(string str = ""hello"", bool boolean = false)
{ }
}
";
await VerifyItemExistsAsync(markup, "boolean", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "character", displayTextSuffix: ":");
}
[WorkItem(544191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544191")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FilteringOverloadsByCallSiteComplex()
{
var markup = @"
class Goo
{
void Test()
{
Bar m = new Bar();
Method(obj:m, $$
}
void Method(Bar obj, int num = 23, string str = """")
{
}
void Method(double dbl = double.MinValue, string str = """")
{
}
void Method(int num = 1, bool b = false, string str = """")
{
}
void Method(Bar obj, bool b = false, string str = """")
{
}
}
class Bar { }
";
await VerifyItemExistsAsync(markup, "str", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "num", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "b", displayTextSuffix: ":");
await VerifyItemIsAbsentAsync(markup, "dbl", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloads()
{
var markup = @"
class Goo
{
void Test()
{
object m = null;
Method(m, $$
}
void Method(object obj, int num = 23, string str = """")
{
}
void Method(int num = 1, bool b = false, string str = """")
{
}
void Method(object obj, bool b = false, string str = """")
{
}
}
";
await VerifyItemExistsAsync(markup, "str", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "num", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "b", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExistingNamedParamsAreFilteredOut()
{
var markup = @"
class Goo
{
void Test()
{
object m = null;
Method(obj: m, str: """", $$);
}
void Method(object obj, int num = 23, string str = """")
{
}
void Method(double dbl = double.MinValue, string str = """")
{
}
void Method(int num = 1, bool b = false, string str = """")
{
}
void Method(object obj, bool b = false, string str = """")
{
}
}
";
await VerifyItemExistsAsync(markup, "num", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "b", displayTextSuffix: ":");
await VerifyItemIsAbsentAsync(markup, "obj", displayTextSuffix: ":");
await VerifyItemIsAbsentAsync(markup, "str", displayTextSuffix: ":");
}
[WorkItem(529369, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529369")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VerbatimIdentifierNotAKeyword()
{
var markup = @"
class Program
{
void Goo(int @integer)
{
Goo(@i$$
}
}
";
await VerifyItemExistsAsync(markup, "integer", displayTextSuffix: ":");
}
[WorkItem(544209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544209")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionStringInMethodOverloads()
{
var markup = @"
class Class1
{
void Test()
{
Goo(boolean: true, $$)
}
void Goo(string obj = ""hello"")
{ }
void Goo(bool boolean = false, Class1 obj = default(Class1))
{ }
}
";
await VerifyItemExistsAsync(markup, "obj", displayTextSuffix: ":",
expectedDescriptionOrNull: $"({FeaturesResources.parameter}) Class1 obj = default(Class1)");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InDelegates()
{
var markup = @"
public delegate void Del(string message);
class Program
{
public static void DelegateMethod(string message)
{
System.Console.WriteLine(message);
}
static void Main(string[] args)
{
Del handler = DelegateMethod;
handler($$
}
}";
await VerifyItemExistsAsync(markup, "message", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InDelegateInvokeSyntax()
{
var markup = @"
public delegate void Del(string message);
class Program
{
public static void DelegateMethod(string message)
{
System.Console.WriteLine(message);
}
static void Main(string[] args)
{
Del handler = DelegateMethod;
handler.Invoke($$
}
}";
await VerifyItemExistsAsync(markup, "message", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotInComment()
{
var markup = @"
public class Test
{
static void Main()
{
M(x: 0, //Hit ctrl-space at the end of this comment $$
y: 1);
}
static void M(int x, int y) { }
}
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommitWithColonWordFullyTyped()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
Main(args$$)
}
}
";
var expected = @"
class Program
{
static void Main(string[] args)
{
Main(args:)
}
}
";
await VerifyProviderCommitAsync(markup, "args:", expected, ':');
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommitWithColonWordPartiallyTyped()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
Main(arg$$)
}
}
";
var expected = @"
class Program
{
static void Main(string[] args)
{
Main(args:)
}
}
";
await VerifyProviderCommitAsync(markup, "args:", expected, ':');
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/Test/Utilities/CSharp/BasicCompilationUtils.cs | // 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.
#nullable disable
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.VisualBasic;
using Roslyn.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using static Microsoft.CodeAnalysis.CodeGen.CompilationTestData;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public static class BasicCompilationUtils
{
public static MetadataReference CompileToMetadata(string source, string assemblyName = null, IEnumerable<MetadataReference> references = null, Verification verify = Verification.Passes)
{
if (references == null)
{
references = new[] { TestBase.MscorlibRef };
}
var compilation = CreateCompilationWithMscorlib(source, assemblyName, references);
var verifier = Instance.CompileAndVerifyCommon(compilation, verify: verify);
return MetadataReference.CreateFromImage(verifier.EmittedAssemblyData);
}
private static VisualBasicCompilation CreateCompilationWithMscorlib(string source, string assemblyName, IEnumerable<MetadataReference> references)
{
if (assemblyName == null)
{
assemblyName = TestBase.GetUniqueName();
}
var tree = VisualBasicSyntaxTree.ParseText(source);
var options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release);
return VisualBasicCompilation.Create(assemblyName, new[] { tree }, references, options);
}
private static BasicTestBase s_instance;
private static BasicTestBase Instance => s_instance ?? (s_instance = new BasicTestBase());
private sealed class BasicTestBase : CommonTestBase
{
internal override string VisualizeRealIL(IModuleSymbol peModule, MethodData methodData, IReadOnlyDictionary<int, string> markers, bool areLocalsZeroed)
{
throw new NotImplementedException();
}
}
}
}
| // 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.
#nullable disable
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.VisualBasic;
using Roslyn.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using static Microsoft.CodeAnalysis.CodeGen.CompilationTestData;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public static class BasicCompilationUtils
{
public static MetadataReference CompileToMetadata(string source, string assemblyName = null, IEnumerable<MetadataReference> references = null, Verification verify = Verification.Passes)
{
if (references == null)
{
references = new[] { TestBase.MscorlibRef };
}
var compilation = CreateCompilationWithMscorlib(source, assemblyName, references);
var verifier = Instance.CompileAndVerifyCommon(compilation, verify: verify);
return MetadataReference.CreateFromImage(verifier.EmittedAssemblyData);
}
private static VisualBasicCompilation CreateCompilationWithMscorlib(string source, string assemblyName, IEnumerable<MetadataReference> references)
{
if (assemblyName == null)
{
assemblyName = TestBase.GetUniqueName();
}
var tree = VisualBasicSyntaxTree.ParseText(source);
var options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release);
return VisualBasicCompilation.Create(assemblyName, new[] { tree }, references, options);
}
private static BasicTestBase s_instance;
private static BasicTestBase Instance => s_instance ?? (s_instance = new BasicTestBase());
private sealed class BasicTestBase : CommonTestBase
{
internal override string VisualizeRealIL(IModuleSymbol peModule, MethodData methodData, IReadOnlyDictionary<int, string> markers, bool areLocalsZeroed)
{
throw new NotImplementedException();
}
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Tools/BuildValidator/RebuildArtifactResolver.cs | // 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.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Rebuild;
using Microsoft.CodeAnalysis.Text;
namespace BuildValidator
{
internal sealed class RebuildArtifactResolver : IRebuildArtifactResolver
{
internal LocalSourceResolver SourceResolver { get; }
internal LocalReferenceResolver ReferenceResolver { get; }
internal RebuildArtifactResolver(LocalSourceResolver sourceResolver, LocalReferenceResolver referenceResolver)
{
SourceResolver = sourceResolver;
ReferenceResolver = referenceResolver;
}
public SourceText ResolveSourceText(SourceTextInfo sourceTextInfo)
=> SourceResolver.ResolveSource(sourceTextInfo);
public MetadataReference ResolveMetadataReference(MetadataReferenceInfo metadataReferenceInfo)
{
if (!ReferenceResolver.TryResolveReferences(metadataReferenceInfo, out var metadataReference))
{
throw new InvalidOperationException($"Could not resolve reference: {metadataReferenceInfo.FileName}");
}
return metadataReference;
}
}
}
| // 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.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Rebuild;
using Microsoft.CodeAnalysis.Text;
namespace BuildValidator
{
internal sealed class RebuildArtifactResolver : IRebuildArtifactResolver
{
internal LocalSourceResolver SourceResolver { get; }
internal LocalReferenceResolver ReferenceResolver { get; }
internal RebuildArtifactResolver(LocalSourceResolver sourceResolver, LocalReferenceResolver referenceResolver)
{
SourceResolver = sourceResolver;
ReferenceResolver = referenceResolver;
}
public SourceText ResolveSourceText(SourceTextInfo sourceTextInfo)
=> SourceResolver.ResolveSource(sourceTextInfo);
public MetadataReference ResolveMetadataReference(MetadataReferenceInfo metadataReferenceInfo)
{
if (!ReferenceResolver.TryResolveReferences(metadataReferenceInfo, out var metadataReference))
{
throw new InvalidOperationException($"Could not resolve reference: {metadataReferenceInfo.FileName}");
}
return metadataReference;
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/Core/Portable/Symbols/IDynamicTypeSymbol.cs | // 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 Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents the 'dynamic' type in C#.
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface IDynamicTypeSymbol : ITypeSymbol
{
}
}
| // 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 Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents the 'dynamic' type in C#.
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface IDynamicTypeSymbol : ITypeSymbol
{
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Analyzers/VisualBasic/Analyzers/RemoveRedundantEquality/VisualBasicRemoveRedundantEqualityDiagnosticAnalyzer.vb | ' 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.
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.RemoveRedundantEquality
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveRedundantEquality
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend NotInheritable Class VisualBasicRemoveRedundantEqualityDiagnosticAnalyzer
Inherits AbstractRemoveRedundantEqualityDiagnosticAnalyzer
Public Sub New()
MyBase.New(VisualBasicSyntaxFacts.Instance)
End Sub
End Class
End Namespace
| ' 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.
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.RemoveRedundantEquality
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveRedundantEquality
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend NotInheritable Class VisualBasicRemoveRedundantEqualityDiagnosticAnalyzer
Inherits AbstractRemoveRedundantEqualityDiagnosticAnalyzer
Public Sub New()
MyBase.New(VisualBasicSyntaxFacts.Instance)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActionWithNestedActions.cs | // 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
/// <summary>
/// Lightbulb item that has child items that should be displayed as 'menu items'
/// (as opposed to 'flavor items').
/// </summary>
internal sealed class SuggestedActionWithNestedActions : SuggestedAction
{
public readonly ImmutableArray<SuggestedActionSet> NestedActionSets;
public SuggestedActionWithNestedActions(
IThreadingContext threadingContext,
SuggestedActionsSourceProvider sourceProvider, Workspace workspace,
ITextBuffer subjectBuffer, object provider,
CodeAction codeAction, ImmutableArray<SuggestedActionSet> nestedActionSets)
: base(threadingContext, sourceProvider, workspace, subjectBuffer, provider, codeAction)
{
Debug.Assert(!nestedActionSets.IsDefaultOrEmpty);
NestedActionSets = nestedActionSets;
}
public SuggestedActionWithNestedActions(
IThreadingContext threadingContext,
SuggestedActionsSourceProvider sourceProvider, Workspace workspace,
ITextBuffer subjectBuffer, object provider,
CodeAction codeAction, SuggestedActionSet nestedActionSet)
: this(threadingContext, sourceProvider, workspace, subjectBuffer, provider, codeAction, ImmutableArray.Create(nestedActionSet))
{
}
public override bool HasActionSets => true;
public sealed override Task<IEnumerable<SuggestedActionSet>> GetActionSetsAsync(CancellationToken cancellationToken)
=> Task.FromResult<IEnumerable<SuggestedActionSet>>(NestedActionSets);
protected override void InnerInvoke(IProgressTracker progressTracker, CancellationToken cancellationToken)
{
// A code action with nested actions is itself never invokable. So just do nothing if this ever gets asked.
// Report a message in debug and log a watson exception so that if this is hit we can try to narrow down how
// this happened.
Debug.Fail("InnerInvoke should not be called on a SuggestedActionWithNestedActions");
try
{
throw new InvalidOperationException("Invoke should not be called on a SuggestedActionWithNestedActions");
}
catch (Exception e) when (FatalError.ReportAndCatch(e))
{
}
}
}
}
| // 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
/// <summary>
/// Lightbulb item that has child items that should be displayed as 'menu items'
/// (as opposed to 'flavor items').
/// </summary>
internal sealed class SuggestedActionWithNestedActions : SuggestedAction
{
public readonly ImmutableArray<SuggestedActionSet> NestedActionSets;
public SuggestedActionWithNestedActions(
IThreadingContext threadingContext,
SuggestedActionsSourceProvider sourceProvider, Workspace workspace,
ITextBuffer subjectBuffer, object provider,
CodeAction codeAction, ImmutableArray<SuggestedActionSet> nestedActionSets)
: base(threadingContext, sourceProvider, workspace, subjectBuffer, provider, codeAction)
{
Debug.Assert(!nestedActionSets.IsDefaultOrEmpty);
NestedActionSets = nestedActionSets;
}
public SuggestedActionWithNestedActions(
IThreadingContext threadingContext,
SuggestedActionsSourceProvider sourceProvider, Workspace workspace,
ITextBuffer subjectBuffer, object provider,
CodeAction codeAction, SuggestedActionSet nestedActionSet)
: this(threadingContext, sourceProvider, workspace, subjectBuffer, provider, codeAction, ImmutableArray.Create(nestedActionSet))
{
}
public override bool HasActionSets => true;
public sealed override Task<IEnumerable<SuggestedActionSet>> GetActionSetsAsync(CancellationToken cancellationToken)
=> Task.FromResult<IEnumerable<SuggestedActionSet>>(NestedActionSets);
protected override void InnerInvoke(IProgressTracker progressTracker, CancellationToken cancellationToken)
{
// A code action with nested actions is itself never invokable. So just do nothing if this ever gets asked.
// Report a message in debug and log a watson exception so that if this is hit we can try to narrow down how
// this happened.
Debug.Fail("InnerInvoke should not be called on a SuggestedActionWithNestedActions");
try
{
throw new InvalidOperationException("Invoke should not be called on a SuggestedActionWithNestedActions");
}
catch (Exception e) when (FatalError.ReportAndCatch(e))
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/VisualStudio/Core/Def/Implementation/WorkspaceCacheService.cs | // 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.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.VisualStudio.LanguageServices
{
[ExportWorkspaceService(typeof(IWorkspaceCacheService), ServiceLayer.Host), Shared]
internal sealed class WorkspaceCacheService : IWorkspaceCacheService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public WorkspaceCacheService()
{
}
/// <summary>
/// Called by the host to try and reduce memory occupied by caches.
/// </summary>
public void FlushCaches()
=> this.CacheFlushRequested?.Invoke(this, EventArgs.Empty);
/// <summary>
/// Raised by the host when available memory is getting low in order to request that caches be flushed.
/// </summary>
public event EventHandler CacheFlushRequested;
}
}
| // 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.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.VisualStudio.LanguageServices
{
[ExportWorkspaceService(typeof(IWorkspaceCacheService), ServiceLayer.Host), Shared]
internal sealed class WorkspaceCacheService : IWorkspaceCacheService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public WorkspaceCacheService()
{
}
/// <summary>
/// Called by the host to try and reduce memory occupied by caches.
/// </summary>
public void FlushCaches()
=> this.CacheFlushRequested?.Invoke(this, EventArgs.Empty);
/// <summary>
/// Raised by the host when available memory is getting low in order to request that caches be flushed.
/// </summary>
public event EventHandler CacheFlushRequested;
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractDiagnosticProviderBasedUserDiagnosticTest.cs | // 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.
#nullable disable
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic;
using Microsoft.CodeAnalysis.CSharp.UseAutoProperty;
using Microsoft.CodeAnalysis.CSharp.UseLocalFunction;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.VisualBasic.UseAutoProperty;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
{
public abstract partial class AbstractDiagnosticProviderBasedUserDiagnosticTest : AbstractUserDiagnosticTest
{
private readonly ConcurrentDictionary<Workspace, (DiagnosticAnalyzer, CodeFixProvider)> _analyzerAndFixerMap = new();
protected AbstractDiagnosticProviderBasedUserDiagnosticTest(ITestOutputHelper logger)
: base(logger)
{
}
internal abstract (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace);
internal virtual (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace, TestParameters parameters)
=> CreateDiagnosticProviderAndFixer(workspace);
private (DiagnosticAnalyzer, CodeFixProvider) GetOrCreateDiagnosticProviderAndFixer(
Workspace workspace, TestParameters parameters)
{
return parameters.fixProviderData == null
? _analyzerAndFixerMap.GetOrAdd(workspace, CreateDiagnosticProviderAndFixer)
: CreateDiagnosticProviderAndFixer(workspace, parameters);
}
internal virtual bool ShouldSkipMessageDescriptionVerification(DiagnosticDescriptor descriptor)
{
if (descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.NotConfigurable))
{
if (!descriptor.IsEnabledByDefault || descriptor.DefaultSeverity == DiagnosticSeverity.Hidden)
{
// The message only displayed if either enabled and not hidden, or configurable
return true;
}
}
return false;
}
[Fact]
public void TestSupportedDiagnosticsMessageTitle()
{
using (var workspace = new AdhocWorkspace())
{
var diagnosticAnalyzer = CreateDiagnosticProviderAndFixer(workspace).Item1;
if (diagnosticAnalyzer == null)
{
return;
}
foreach (var descriptor in diagnosticAnalyzer.SupportedDiagnostics)
{
if (descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.NotConfigurable))
{
// The title only displayed for rule configuration
continue;
}
Assert.NotEqual("", descriptor.Title?.ToString() ?? "");
}
}
}
[Fact]
public void TestSupportedDiagnosticsMessageDescription()
{
using (var workspace = new AdhocWorkspace())
{
var diagnosticAnalyzer = CreateDiagnosticProviderAndFixer(workspace).Item1;
if (diagnosticAnalyzer == null)
{
return;
}
foreach (var descriptor in diagnosticAnalyzer.SupportedDiagnostics)
{
if (ShouldSkipMessageDescriptionVerification(descriptor))
{
continue;
}
Assert.NotEqual("", descriptor.MessageFormat?.ToString() ?? "");
}
}
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/26717")]
public void TestSupportedDiagnosticsMessageHelpLinkUri()
{
using (var workspace = new AdhocWorkspace())
{
var diagnosticAnalyzer = CreateDiagnosticProviderAndFixer(workspace).Item1;
if (diagnosticAnalyzer == null)
{
return;
}
foreach (var descriptor in diagnosticAnalyzer.SupportedDiagnostics)
{
Assert.NotEqual("", descriptor.HelpLinkUri ?? "");
}
}
}
internal override async Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync(
TestWorkspace workspace, TestParameters parameters)
{
var (analyzer, _) = GetOrCreateDiagnosticProviderAndFixer(workspace, parameters);
AddAnalyzerToWorkspace(workspace, analyzer, parameters);
var document = GetDocumentAndSelectSpan(workspace, out var span);
var allDiagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(workspace, document, span);
AssertNoAnalyzerExceptionDiagnostics(allDiagnostics);
return allDiagnostics;
}
internal override async Task<(ImmutableArray<Diagnostic>, ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetDiagnosticAndFixesAsync(
TestWorkspace workspace, TestParameters parameters)
{
var (analyzer, fixer) = GetOrCreateDiagnosticProviderAndFixer(workspace, parameters);
AddAnalyzerToWorkspace(workspace, analyzer, parameters);
string annotation = null;
if (!TryGetDocumentAndSelectSpan(workspace, out var document, out var span))
{
document = GetDocumentAndAnnotatedSpan(workspace, out annotation, out span);
}
var testDriver = new TestDiagnosticAnalyzerDriver(workspace, document.Project);
var filterSpan = parameters.includeDiagnosticsOutsideSelection ? (TextSpan?)null : span;
var diagnostics = (await testDriver.GetAllDiagnosticsAsync(document, filterSpan)).ToImmutableArray();
AssertNoAnalyzerExceptionDiagnostics(diagnostics);
if (fixer == null)
{
return (diagnostics, ImmutableArray<CodeAction>.Empty, null);
}
var ids = new HashSet<string>(fixer.FixableDiagnosticIds);
var dxs = diagnostics.Where(d => ids.Contains(d.Id)).ToList();
var (resultDiagnostics, codeActions, actionToInvoke) = await GetDiagnosticAndFixesAsync(
dxs, fixer, testDriver, document, span, annotation, parameters.index);
// If we are also testing non-fixable diagnostics,
// then the result diagnostics need to include all diagnostics,
// not just the fixable ones returned from GetDiagnosticAndFixesAsync.
if (parameters.retainNonFixableDiagnostics)
{
resultDiagnostics = diagnostics;
}
return (resultDiagnostics, codeActions, actionToInvoke);
}
private protected async Task TestDiagnosticInfoAsync(
string initialMarkup,
OptionsCollection options,
string diagnosticId,
DiagnosticSeverity diagnosticSeverity,
LocalizableString diagnosticMessage = null)
{
await TestDiagnosticInfoAsync(initialMarkup, null, null, options, diagnosticId, diagnosticSeverity, diagnosticMessage);
await TestDiagnosticInfoAsync(initialMarkup, GetScriptOptions(), null, options, diagnosticId, diagnosticSeverity, diagnosticMessage);
}
private protected async Task TestDiagnosticInfoAsync(
string initialMarkup,
ParseOptions parseOptions,
CompilationOptions compilationOptions,
OptionsCollection options,
string diagnosticId,
DiagnosticSeverity diagnosticSeverity,
LocalizableString diagnosticMessage = null)
{
var testOptions = new TestParameters(parseOptions, compilationOptions, options);
using (var workspace = CreateWorkspaceFromOptions(initialMarkup, testOptions))
{
var diagnostics = (await GetDiagnosticsAsync(workspace, testOptions)).ToImmutableArray();
diagnostics = diagnostics.WhereAsArray(d => d.Id == diagnosticId);
Assert.Equal(1, diagnostics.Count());
var hostDocument = workspace.Documents.Single(d => d.SelectedSpans.Any());
var expected = hostDocument.SelectedSpans.Single();
var actual = diagnostics.Single().Location.SourceSpan;
Assert.Equal(expected, actual);
Assert.Equal(diagnosticSeverity, diagnostics.Single().Severity);
if (diagnosticMessage != null)
{
Assert.Equal(diagnosticMessage, diagnostics.Single().GetMessage());
}
}
}
#pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved
/// <summary>
/// The internal method <see cref="AnalyzerExecutor.IsAnalyzerExceptionDiagnostic(Diagnostic)"/> does
/// essentially this, but due to linked files between projects, this project cannot have internals visible
/// access to the Microsoft.CodeAnalysis project without the cascading effect of many extern aliases, so it
/// is re-implemented here in a way that is potentially overly aggressive with the knowledge that if this method
/// starts failing on non-analyzer exception diagnostics, it can be appropriately tuned or re-evaluated.
/// </summary>
private static void AssertNoAnalyzerExceptionDiagnostics(IEnumerable<Diagnostic> diagnostics)
#pragma warning restore CS1574 // XML comment has cref attribute that could not be resolved
{
var analyzerExceptionDiagnostics = diagnostics.Where(diag => diag.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.AnalyzerException));
AssertEx.Empty(analyzerExceptionDiagnostics, "Found analyzer exception diagnostics");
}
// This region provides instances of code fix providers from Features layers, such that the corresponding
// analyzer has been ported to CodeStyle layer, but not the fixer.
// This enables porting the tests for the ported analyzer in CodeStyle layer.
#region CodeFixProvider Helpers
// https://github.com/dotnet/roslyn/issues/43056 blocks porting the fixer to CodeStyle layer.
protected static CodeFixProvider GetMakeLocalFunctionStaticCodeFixProvider() => new MakeLocalFunctionStaticCodeFixProvider();
// https://github.com/dotnet/roslyn/issues/43056 blocks porting the fixer to CodeStyle layer.
protected static CodeFixProvider GetCSharpUseLocalFunctionCodeFixProvider() => new CSharpUseLocalFunctionCodeFixProvider();
// https://github.com/dotnet/roslyn/issues/43091 blocks porting the fixer to CodeStyle layer.
protected static CodeFixProvider GetCSharpUseAutoPropertyCodeFixProvider() => new CSharpUseAutoPropertyCodeFixProvider();
// https://github.com/dotnet/roslyn/issues/43091 blocks porting the fixer to CodeStyle layer.
protected static CodeFixProvider GetVisualBasicUseAutoPropertyCodeFixProvider() => new VisualBasicUseAutoPropertyCodeFixProvider();
#endregion
}
}
| // 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.
#nullable disable
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic;
using Microsoft.CodeAnalysis.CSharp.UseAutoProperty;
using Microsoft.CodeAnalysis.CSharp.UseLocalFunction;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.VisualBasic.UseAutoProperty;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
{
public abstract partial class AbstractDiagnosticProviderBasedUserDiagnosticTest : AbstractUserDiagnosticTest
{
private readonly ConcurrentDictionary<Workspace, (DiagnosticAnalyzer, CodeFixProvider)> _analyzerAndFixerMap = new();
protected AbstractDiagnosticProviderBasedUserDiagnosticTest(ITestOutputHelper logger)
: base(logger)
{
}
internal abstract (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace);
internal virtual (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace, TestParameters parameters)
=> CreateDiagnosticProviderAndFixer(workspace);
private (DiagnosticAnalyzer, CodeFixProvider) GetOrCreateDiagnosticProviderAndFixer(
Workspace workspace, TestParameters parameters)
{
return parameters.fixProviderData == null
? _analyzerAndFixerMap.GetOrAdd(workspace, CreateDiagnosticProviderAndFixer)
: CreateDiagnosticProviderAndFixer(workspace, parameters);
}
internal virtual bool ShouldSkipMessageDescriptionVerification(DiagnosticDescriptor descriptor)
{
if (descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.NotConfigurable))
{
if (!descriptor.IsEnabledByDefault || descriptor.DefaultSeverity == DiagnosticSeverity.Hidden)
{
// The message only displayed if either enabled and not hidden, or configurable
return true;
}
}
return false;
}
[Fact]
public void TestSupportedDiagnosticsMessageTitle()
{
using (var workspace = new AdhocWorkspace())
{
var diagnosticAnalyzer = CreateDiagnosticProviderAndFixer(workspace).Item1;
if (diagnosticAnalyzer == null)
{
return;
}
foreach (var descriptor in diagnosticAnalyzer.SupportedDiagnostics)
{
if (descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.NotConfigurable))
{
// The title only displayed for rule configuration
continue;
}
Assert.NotEqual("", descriptor.Title?.ToString() ?? "");
}
}
}
[Fact]
public void TestSupportedDiagnosticsMessageDescription()
{
using (var workspace = new AdhocWorkspace())
{
var diagnosticAnalyzer = CreateDiagnosticProviderAndFixer(workspace).Item1;
if (diagnosticAnalyzer == null)
{
return;
}
foreach (var descriptor in diagnosticAnalyzer.SupportedDiagnostics)
{
if (ShouldSkipMessageDescriptionVerification(descriptor))
{
continue;
}
Assert.NotEqual("", descriptor.MessageFormat?.ToString() ?? "");
}
}
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/26717")]
public void TestSupportedDiagnosticsMessageHelpLinkUri()
{
using (var workspace = new AdhocWorkspace())
{
var diagnosticAnalyzer = CreateDiagnosticProviderAndFixer(workspace).Item1;
if (diagnosticAnalyzer == null)
{
return;
}
foreach (var descriptor in diagnosticAnalyzer.SupportedDiagnostics)
{
Assert.NotEqual("", descriptor.HelpLinkUri ?? "");
}
}
}
internal override async Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync(
TestWorkspace workspace, TestParameters parameters)
{
var (analyzer, _) = GetOrCreateDiagnosticProviderAndFixer(workspace, parameters);
AddAnalyzerToWorkspace(workspace, analyzer, parameters);
var document = GetDocumentAndSelectSpan(workspace, out var span);
var allDiagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(workspace, document, span);
AssertNoAnalyzerExceptionDiagnostics(allDiagnostics);
return allDiagnostics;
}
internal override async Task<(ImmutableArray<Diagnostic>, ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetDiagnosticAndFixesAsync(
TestWorkspace workspace, TestParameters parameters)
{
var (analyzer, fixer) = GetOrCreateDiagnosticProviderAndFixer(workspace, parameters);
AddAnalyzerToWorkspace(workspace, analyzer, parameters);
string annotation = null;
if (!TryGetDocumentAndSelectSpan(workspace, out var document, out var span))
{
document = GetDocumentAndAnnotatedSpan(workspace, out annotation, out span);
}
var testDriver = new TestDiagnosticAnalyzerDriver(workspace, document.Project);
var filterSpan = parameters.includeDiagnosticsOutsideSelection ? (TextSpan?)null : span;
var diagnostics = (await testDriver.GetAllDiagnosticsAsync(document, filterSpan)).ToImmutableArray();
AssertNoAnalyzerExceptionDiagnostics(diagnostics);
if (fixer == null)
{
return (diagnostics, ImmutableArray<CodeAction>.Empty, null);
}
var ids = new HashSet<string>(fixer.FixableDiagnosticIds);
var dxs = diagnostics.Where(d => ids.Contains(d.Id)).ToList();
var (resultDiagnostics, codeActions, actionToInvoke) = await GetDiagnosticAndFixesAsync(
dxs, fixer, testDriver, document, span, annotation, parameters.index);
// If we are also testing non-fixable diagnostics,
// then the result diagnostics need to include all diagnostics,
// not just the fixable ones returned from GetDiagnosticAndFixesAsync.
if (parameters.retainNonFixableDiagnostics)
{
resultDiagnostics = diagnostics;
}
return (resultDiagnostics, codeActions, actionToInvoke);
}
private protected async Task TestDiagnosticInfoAsync(
string initialMarkup,
OptionsCollection options,
string diagnosticId,
DiagnosticSeverity diagnosticSeverity,
LocalizableString diagnosticMessage = null)
{
await TestDiagnosticInfoAsync(initialMarkup, null, null, options, diagnosticId, diagnosticSeverity, diagnosticMessage);
await TestDiagnosticInfoAsync(initialMarkup, GetScriptOptions(), null, options, diagnosticId, diagnosticSeverity, diagnosticMessage);
}
private protected async Task TestDiagnosticInfoAsync(
string initialMarkup,
ParseOptions parseOptions,
CompilationOptions compilationOptions,
OptionsCollection options,
string diagnosticId,
DiagnosticSeverity diagnosticSeverity,
LocalizableString diagnosticMessage = null)
{
var testOptions = new TestParameters(parseOptions, compilationOptions, options);
using (var workspace = CreateWorkspaceFromOptions(initialMarkup, testOptions))
{
var diagnostics = (await GetDiagnosticsAsync(workspace, testOptions)).ToImmutableArray();
diagnostics = diagnostics.WhereAsArray(d => d.Id == diagnosticId);
Assert.Equal(1, diagnostics.Count());
var hostDocument = workspace.Documents.Single(d => d.SelectedSpans.Any());
var expected = hostDocument.SelectedSpans.Single();
var actual = diagnostics.Single().Location.SourceSpan;
Assert.Equal(expected, actual);
Assert.Equal(diagnosticSeverity, diagnostics.Single().Severity);
if (diagnosticMessage != null)
{
Assert.Equal(diagnosticMessage, diagnostics.Single().GetMessage());
}
}
}
#pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved
/// <summary>
/// The internal method <see cref="AnalyzerExecutor.IsAnalyzerExceptionDiagnostic(Diagnostic)"/> does
/// essentially this, but due to linked files between projects, this project cannot have internals visible
/// access to the Microsoft.CodeAnalysis project without the cascading effect of many extern aliases, so it
/// is re-implemented here in a way that is potentially overly aggressive with the knowledge that if this method
/// starts failing on non-analyzer exception diagnostics, it can be appropriately tuned or re-evaluated.
/// </summary>
private static void AssertNoAnalyzerExceptionDiagnostics(IEnumerable<Diagnostic> diagnostics)
#pragma warning restore CS1574 // XML comment has cref attribute that could not be resolved
{
var analyzerExceptionDiagnostics = diagnostics.Where(diag => diag.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.AnalyzerException));
AssertEx.Empty(analyzerExceptionDiagnostics, "Found analyzer exception diagnostics");
}
// This region provides instances of code fix providers from Features layers, such that the corresponding
// analyzer has been ported to CodeStyle layer, but not the fixer.
// This enables porting the tests for the ported analyzer in CodeStyle layer.
#region CodeFixProvider Helpers
// https://github.com/dotnet/roslyn/issues/43056 blocks porting the fixer to CodeStyle layer.
protected static CodeFixProvider GetMakeLocalFunctionStaticCodeFixProvider() => new MakeLocalFunctionStaticCodeFixProvider();
// https://github.com/dotnet/roslyn/issues/43056 blocks porting the fixer to CodeStyle layer.
protected static CodeFixProvider GetCSharpUseLocalFunctionCodeFixProvider() => new CSharpUseLocalFunctionCodeFixProvider();
// https://github.com/dotnet/roslyn/issues/43091 blocks porting the fixer to CodeStyle layer.
protected static CodeFixProvider GetCSharpUseAutoPropertyCodeFixProvider() => new CSharpUseAutoPropertyCodeFixProvider();
// https://github.com/dotnet/roslyn/issues/43091 blocks porting the fixer to CodeStyle layer.
protected static CodeFixProvider GetVisualBasicUseAutoPropertyCodeFixProvider() => new VisualBasicUseAutoPropertyCodeFixProvider();
#endregion
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/VisualStudio/Core/Def/Implementation/Progression/GraphQueries/ImplementsGraphQuery.cs | // 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.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.GraphModel.Schemas;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
internal sealed class ImplementsGraphQuery : IGraphQuery
{
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.GraphQuery_Implements, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken))
{
var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false);
foreach (var node in context.InputNodes)
{
var symbol = graphBuilder.GetSymbol(node, cancellationToken);
if (symbol is INamedTypeSymbol namedType)
{
var implementedSymbols = ImmutableArray<ISymbol>.CastUp(namedType.AllInterfaces);
await AddImplementedSymbolsAsync(graphBuilder, node, implementedSymbols, cancellationToken).ConfigureAwait(false);
}
else if (symbol is IMethodSymbol ||
symbol is IPropertySymbol ||
symbol is IEventSymbol)
{
var implements = await SymbolFinder.FindImplementedInterfaceMembersArrayAsync(symbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false);
await AddImplementedSymbolsAsync(graphBuilder, node, implements, cancellationToken).ConfigureAwait(false);
}
}
return graphBuilder;
}
}
private static async Task AddImplementedSymbolsAsync(
GraphBuilder graphBuilder, GraphNode node, ImmutableArray<ISymbol> implementedSymbols, CancellationToken cancellationToken)
{
foreach (var interfaceType in implementedSymbols)
{
var interfaceTypeNode = await graphBuilder.AddNodeAsync(
interfaceType, relatedNode: node, cancellationToken).ConfigureAwait(false);
graphBuilder.AddLink(node, CodeLinkCategories.Implements, interfaceTypeNode, cancellationToken);
}
}
}
}
| // 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.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.GraphModel.Schemas;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
internal sealed class ImplementsGraphQuery : IGraphQuery
{
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.GraphQuery_Implements, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken))
{
var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false);
foreach (var node in context.InputNodes)
{
var symbol = graphBuilder.GetSymbol(node, cancellationToken);
if (symbol is INamedTypeSymbol namedType)
{
var implementedSymbols = ImmutableArray<ISymbol>.CastUp(namedType.AllInterfaces);
await AddImplementedSymbolsAsync(graphBuilder, node, implementedSymbols, cancellationToken).ConfigureAwait(false);
}
else if (symbol is IMethodSymbol ||
symbol is IPropertySymbol ||
symbol is IEventSymbol)
{
var implements = await SymbolFinder.FindImplementedInterfaceMembersArrayAsync(symbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false);
await AddImplementedSymbolsAsync(graphBuilder, node, implements, cancellationToken).ConfigureAwait(false);
}
}
return graphBuilder;
}
}
private static async Task AddImplementedSymbolsAsync(
GraphBuilder graphBuilder, GraphNode node, ImmutableArray<ISymbol> implementedSymbols, CancellationToken cancellationToken)
{
foreach (var interfaceType in implementedSymbols)
{
var interfaceTypeNode = await graphBuilder.AddNodeAsync(
interfaceType, relatedNode: node, cancellationToken).ConfigureAwait(false);
graphBuilder.AddLink(node, CodeLinkCategories.Implements, interfaceTypeNode, cancellationToken);
}
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/EditorFeatures/Core/Shared/BrowserHelper.cs | // 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.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.Editor.Shared
{
internal static class BrowserHelper
{
/// <summary>
/// Unique VS session id.
/// Internal for testing.
/// TODO: Revisit - static non-deterministic data https://github.com/dotnet/roslyn/issues/39415
/// </summary>
internal static readonly string EscapedRequestId = Guid.NewGuid().ToString();
private const string BingGetApiUrl = "https://bingdev.cloudapp.net/BingUrl.svc/Get";
private const int BingQueryArgumentMaxLength = 10240;
private static bool TryGetWellFormedHttpUri(string? link, [NotNullWhen(true)] out Uri? uri)
{
uri = null;
if (string.IsNullOrWhiteSpace(link) || !Uri.IsWellFormedUriString(link, UriKind.Absolute))
{
return false;
}
var absoluteUri = new Uri(link, UriKind.Absolute);
if (absoluteUri.Scheme != Uri.UriSchemeHttp && absoluteUri.Scheme != Uri.UriSchemeHttps)
{
return false;
}
uri = absoluteUri;
return true;
}
public static Uri? GetHelpLink(DiagnosticDescriptor descriptor, string language)
=> GetHelpLink(descriptor.Id, descriptor.GetBingHelpMessage(), language, descriptor.HelpLinkUri);
public static Uri? GetHelpLink(DiagnosticData data)
=> GetHelpLink(data.Id, data.ENUMessageForBingSearch, data.Language, data.HelpLink);
private static Uri? GetHelpLink(string diagnosticId, string? title, string? language, string? rawHelpLink)
{
if (string.IsNullOrWhiteSpace(diagnosticId))
{
return null;
}
if (TryGetWellFormedHttpUri(rawHelpLink, out var link))
{
return link;
}
return new Uri(BingGetApiUrl +
"?selectedText=" + EscapeDataString(title) +
"&mainLanguage=" + EscapeDataString(language) +
"&requestId=" + EscapedRequestId +
"&errorCode=" + EscapeDataString(diagnosticId));
}
private static string EscapeDataString(string? str)
{
if (str == null)
{
return string.Empty;
}
try
{
// Uri has limit on string size (32766 characters).
return Uri.EscapeDataString(str.Substring(0, Math.Min(str.Length, BingQueryArgumentMaxLength)));
}
catch (UriFormatException)
{
return string.Empty;
}
}
public static string? GetHelpLinkToolTip(DiagnosticData data)
{
var helpLink = GetHelpLink(data);
if (helpLink == null)
{
return null;
}
return GetHelpLinkToolTip(data.Id, helpLink);
}
public static string GetHelpLinkToolTip(string diagnosticId, Uri uri)
{
var strUri = uri.ToString();
var resourceName = strUri.StartsWith(BingGetApiUrl, StringComparison.Ordinal) ?
EditorFeaturesResources.Get_help_for_0_from_Bing : EditorFeaturesResources.Get_help_for_0;
// We make sure not to use Uri.AbsoluteUri for the url displayed in the tooltip so that the url displayed in the tooltip stays human readable.
return string.Format(resourceName, diagnosticId) + "\r\n" + strUri;
}
}
}
| // 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.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.Editor.Shared
{
internal static class BrowserHelper
{
/// <summary>
/// Unique VS session id.
/// Internal for testing.
/// TODO: Revisit - static non-deterministic data https://github.com/dotnet/roslyn/issues/39415
/// </summary>
internal static readonly string EscapedRequestId = Guid.NewGuid().ToString();
private const string BingGetApiUrl = "https://bingdev.cloudapp.net/BingUrl.svc/Get";
private const int BingQueryArgumentMaxLength = 10240;
private static bool TryGetWellFormedHttpUri(string? link, [NotNullWhen(true)] out Uri? uri)
{
uri = null;
if (string.IsNullOrWhiteSpace(link) || !Uri.IsWellFormedUriString(link, UriKind.Absolute))
{
return false;
}
var absoluteUri = new Uri(link, UriKind.Absolute);
if (absoluteUri.Scheme != Uri.UriSchemeHttp && absoluteUri.Scheme != Uri.UriSchemeHttps)
{
return false;
}
uri = absoluteUri;
return true;
}
public static Uri? GetHelpLink(DiagnosticDescriptor descriptor, string language)
=> GetHelpLink(descriptor.Id, descriptor.GetBingHelpMessage(), language, descriptor.HelpLinkUri);
public static Uri? GetHelpLink(DiagnosticData data)
=> GetHelpLink(data.Id, data.ENUMessageForBingSearch, data.Language, data.HelpLink);
private static Uri? GetHelpLink(string diagnosticId, string? title, string? language, string? rawHelpLink)
{
if (string.IsNullOrWhiteSpace(diagnosticId))
{
return null;
}
if (TryGetWellFormedHttpUri(rawHelpLink, out var link))
{
return link;
}
return new Uri(BingGetApiUrl +
"?selectedText=" + EscapeDataString(title) +
"&mainLanguage=" + EscapeDataString(language) +
"&requestId=" + EscapedRequestId +
"&errorCode=" + EscapeDataString(diagnosticId));
}
private static string EscapeDataString(string? str)
{
if (str == null)
{
return string.Empty;
}
try
{
// Uri has limit on string size (32766 characters).
return Uri.EscapeDataString(str.Substring(0, Math.Min(str.Length, BingQueryArgumentMaxLength)));
}
catch (UriFormatException)
{
return string.Empty;
}
}
public static string? GetHelpLinkToolTip(DiagnosticData data)
{
var helpLink = GetHelpLink(data);
if (helpLink == null)
{
return null;
}
return GetHelpLinkToolTip(data.Id, helpLink);
}
public static string GetHelpLinkToolTip(string diagnosticId, Uri uri)
{
var strUri = uri.ToString();
var resourceName = strUri.StartsWith(BingGetApiUrl, StringComparison.Ordinal) ?
EditorFeaturesResources.Get_help_for_0_from_Bing : EditorFeaturesResources.Get_help_for_0;
// We make sure not to use Uri.AbsoluteUri for the url displayed in the tooltip so that the url displayed in the tooltip stays human readable.
return string.Format(resourceName, diagnosticId) + "\r\n" + strUri;
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer_IncrementalAnalyzer.cs | // 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Workspaces.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2
{
internal partial class DiagnosticIncrementalAnalyzer
{
public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken)
=> AnalyzeDocumentForKindAsync(document, AnalysisKind.Syntax, cancellationToken);
public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken)
=> AnalyzeDocumentForKindAsync(document, AnalysisKind.Semantic, cancellationToken);
public Task AnalyzeNonSourceDocumentAsync(TextDocument textDocument, InvocationReasons reasons, CancellationToken cancellationToken)
=> AnalyzeDocumentForKindAsync(textDocument, AnalysisKind.Syntax, cancellationToken);
private async Task AnalyzeDocumentForKindAsync(TextDocument document, AnalysisKind kind, CancellationToken cancellationToken)
{
try
{
if (!AnalysisEnabled(document, _documentTrackingService))
{
// to reduce allocations, here, we don't clear existing diagnostics since it is dealt by other entry point such as
// DocumentReset or DocumentClosed.
return;
}
var stateSets = _stateManager.GetOrUpdateStateSets(document.Project);
var compilationWithAnalyzers = await GetOrCreateCompilationWithAnalyzersAsync(document.Project, stateSets, cancellationToken).ConfigureAwait(false);
// We split the diagnostic computation for document into following steps:
// 1. Try to get cached diagnostics for each analyzer, while computing the set of analyzers that do not have cached diagnostics.
// 2. Execute all the non-cached analyzers with a single invocation into CompilationWithAnalyzers.
// 3. Fetch computed diagnostics per-analyzer from the above invocation, and cache and raise diagnostic reported events.
// In near future, the diagnostic computation invocation into CompilationWithAnalyzers will be moved to OOP.
// This should help simplify and/or remove the IDE layer diagnostic caching in devenv process.
// First attempt to fetch diagnostics from the cache, while computing the state sets for analyzers that are not cached.
using var _ = ArrayBuilder<StateSet>.GetInstance(out var nonCachedStateSets);
foreach (var stateSet in stateSets)
{
var data = await TryGetCachedDocumentAnalysisDataAsync(document, stateSet, kind, cancellationToken).ConfigureAwait(false);
if (data.HasValue)
{
// We need to persist and raise diagnostics for suppressed analyzer.
PersistAndRaiseDiagnosticsIfNeeded(data.Value, stateSet);
}
else
{
nonCachedStateSets.Add(stateSet);
}
}
// Then, compute the diagnostics for non-cached state sets, and cache and raise diagnostic reported events for these diagnostics.
if (nonCachedStateSets.Count > 0)
{
var analysisScope = new DocumentAnalysisScope(document, span: null, nonCachedStateSets.SelectAsArray(s => s.Analyzer), kind);
var executor = new DocumentAnalysisExecutor(analysisScope, compilationWithAnalyzers, _diagnosticAnalyzerRunner, logPerformanceInfo: true, onAnalysisException: OnAnalysisException);
foreach (var stateSet in nonCachedStateSets)
{
var computedData = await ComputeDocumentAnalysisDataAsync(executor, stateSet, cancellationToken).ConfigureAwait(false);
PersistAndRaiseDiagnosticsIfNeeded(computedData, stateSet);
}
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
void PersistAndRaiseDiagnosticsIfNeeded(DocumentAnalysisData result, StateSet stateSet)
{
if (result.FromCache == true)
{
RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, result.Items);
return;
}
// no cancellation after this point.
var state = stateSet.GetOrCreateActiveFileState(document.Id);
state.Save(kind, result.ToPersistData());
RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, result.OldItems, result.Items);
}
void OnAnalysisException()
{
// Do not re-use cached CompilationWithAnalyzers instance in presence of an exception, as the underlying analysis state might be corrupt.
ClearCompilationsWithAnalyzersCache(document.Project);
}
}
public async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken)
{
// Perf optimization. check whether we want to analyze this project or not.
if (!FullAnalysisEnabled(project, forceAnalyzerRun: false))
{
return;
}
await AnalyzeProjectAsync(project, forceAnalyzerRun: false, cancellationToken).ConfigureAwait(false);
}
public Task ForceAnalyzeProjectAsync(Project project, CancellationToken cancellationToken)
=> AnalyzeProjectAsync(project, forceAnalyzerRun: true, cancellationToken);
private async Task AnalyzeProjectAsync(Project project, bool forceAnalyzerRun, CancellationToken cancellationToken)
{
try
{
var stateSets = GetStateSetsForFullSolutionAnalysis(_stateManager.GetOrUpdateStateSets(project), project);
var options = project.Solution.Options;
// PERF: get analyzers that are not suppressed and marked as open file only
// this is perf optimization. we cache these result since we know the result. (no diagnostics)
var activeAnalyzers = stateSets
.Select(s => s.Analyzer)
.Where(a => !DiagnosticAnalyzerInfoCache.IsAnalyzerSuppressed(a, project) && !a.IsOpenFileOnly(options));
// get driver only with active analyzers.
var compilationWithAnalyzers = await AnalyzerHelper.CreateCompilationWithAnalyzersAsync(project, activeAnalyzers, includeSuppressedDiagnostics: true, cancellationToken).ConfigureAwait(false);
var result = await GetProjectAnalysisDataAsync(compilationWithAnalyzers, project, stateSets, forceAnalyzerRun, cancellationToken).ConfigureAwait(false);
if (result.OldResult == null)
{
RaiseProjectDiagnosticsIfNeeded(project, stateSets, result.Result);
return;
}
// we might not have compilationWithAnalyzers even if project supports compilation if we are called with no analyzers.
var compilation = compilationWithAnalyzers?.Compilation ??
(project.SupportsCompilation ? await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false) : null);
// no cancellation after this point.
// any analyzer that doesn't have result will be treated as returned empty set
// which means we will remove those from error list
foreach (var stateSet in stateSets)
{
var state = stateSet.GetOrCreateProjectState(project.Id);
await state.SaveToInMemoryStorageAsync(project, result.GetResult(stateSet.Analyzer)).ConfigureAwait(false);
}
RaiseProjectDiagnosticsIfNeeded(project, stateSets, result.OldResult, result.Result);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
=> TextDocumentOpenAsync(document, cancellationToken);
public Task NonSourceDocumentOpenAsync(TextDocument document, CancellationToken cancellationToken)
=> TextDocumentOpenAsync(document, cancellationToken);
private async Task TextDocumentOpenAsync(TextDocument document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentOpen, GetOpenLogMessage, document, cancellationToken))
{
var stateSets = _stateManager.GetStateSets(document.Project);
// let other component knows about this event
ClearCompilationsWithAnalyzersCache();
// can not be canceled
foreach (var stateSet in stateSets)
await stateSet.OnDocumentOpenedAsync(document).ConfigureAwait(false);
}
}
public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken)
=> TextDocumentCloseAsync(document, cancellationToken);
public Task NonSourceDocumentCloseAsync(TextDocument document, CancellationToken cancellationToken)
=> TextDocumentCloseAsync(document, cancellationToken);
private async Task TextDocumentCloseAsync(TextDocument document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentClose, GetResetLogMessage, document, cancellationToken))
{
var stateSets = _stateManager.GetStateSets(document.Project);
// let other components knows about this event
ClearCompilationsWithAnalyzersCache();
// can not be canceled
var documentHadDiagnostics = false;
foreach (var stateSet in stateSets)
documentHadDiagnostics |= await stateSet.OnDocumentClosedAsync(document).ConfigureAwait(false);
RaiseDiagnosticsRemovedIfRequiredForClosedOrResetDocument(document, stateSets, documentHadDiagnostics);
}
}
public Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
=> TextDocumentResetAsync(document, cancellationToken);
public Task NonSourceDocumentResetAsync(TextDocument document, CancellationToken cancellationToken)
=> TextDocumentResetAsync(document, cancellationToken);
private Task TextDocumentResetAsync(TextDocument document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentReset, GetResetLogMessage, document, cancellationToken))
{
var stateSets = _stateManager.GetStateSets(document.Project);
// let other components knows about this event
ClearCompilationsWithAnalyzersCache();
// can not be canceled
var documentHadDiagnostics = false;
foreach (var stateSet in stateSets)
documentHadDiagnostics |= stateSet.OnDocumentReset(document);
RaiseDiagnosticsRemovedIfRequiredForClosedOrResetDocument(document, stateSets, documentHadDiagnostics);
}
return Task.CompletedTask;
}
private void RaiseDiagnosticsRemovedIfRequiredForClosedOrResetDocument(TextDocument document, IEnumerable<StateSet> stateSets, bool documentHadDiagnostics)
{
// if there was no diagnostic reported for this document OR Full solution analysis is enabled, nothing to clean up
if (!documentHadDiagnostics ||
FullAnalysisEnabled(document.Project, forceAnalyzerRun: false))
{
// this is Perf to reduce raising events unnecessarily.
return;
}
var removeDiagnosticsOnDocumentClose = document.Project.Solution.Options.GetOption(ServiceFeatureOnOffOptions.RemoveDocumentDiagnosticsOnDocumentClose, document.Project.Language);
if (!removeDiagnosticsOnDocumentClose)
{
return;
}
RaiseDiagnosticsRemovedForDocument(document.Id, stateSets);
}
public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_RemoveDocument, GetRemoveLogMessage, documentId, CancellationToken.None))
{
var stateSets = _stateManager.GetStateSets(documentId.ProjectId);
// let other components knows about this event
ClearCompilationsWithAnalyzersCache();
var changed = false;
foreach (var stateSet in stateSets)
changed |= stateSet.OnDocumentRemoved(documentId);
// if there was no diagnostic reported for this document, nothing to clean up
// this is Perf to reduce raising events unnecessarily.
if (changed)
RaiseDiagnosticsRemovedForDocument(documentId, stateSets);
}
return Task.CompletedTask;
}
private void RaiseDiagnosticsRemovedForDocument(DocumentId documentId, IEnumerable<StateSet> stateSets)
{
// remove all diagnostics for the document
AnalyzerService.RaiseBulkDiagnosticsUpdated(raiseEvents =>
{
foreach (var stateSet in stateSets)
{
// clear all doucment diagnostics
RaiseDiagnosticsRemoved(documentId, solution: null, stateSet, AnalysisKind.Syntax, raiseEvents);
RaiseDiagnosticsRemoved(documentId, solution: null, stateSet, AnalysisKind.Semantic, raiseEvents);
RaiseDiagnosticsRemoved(documentId, solution: null, stateSet, AnalysisKind.NonLocal, raiseEvents);
}
});
}
public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellation)
{
using (Logger.LogBlock(FunctionId.Diagnostics_RemoveProject, GetRemoveLogMessage, projectId, CancellationToken.None))
{
var stateSets = _stateManager.GetStateSets(projectId);
// let other components knows about this event
ClearCompilationsWithAnalyzersCache();
var changed = _stateManager.OnProjectRemoved(stateSets, projectId);
// if there was no diagnostic reported for this project, nothing to clean up
// this is Perf to reduce raising events unnecessarily.
if (changed)
{
// remove all diagnostics for the project
AnalyzerService.RaiseBulkDiagnosticsUpdated(raiseEvents =>
{
foreach (var stateSet in stateSets)
{
// clear all project diagnostics
RaiseDiagnosticsRemoved(projectId, solution: null, stateSet, raiseEvents);
}
});
}
}
return Task.CompletedTask;
}
public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
{
// let other components knows about this event
ClearCompilationsWithAnalyzersCache();
return Task.CompletedTask;
}
private static bool AnalysisEnabled(TextDocument document, IDocumentTrackingService documentTrackingService)
{
if (document.Services.GetService<DocumentPropertiesService>()?.DiagnosticsLspClientName != null)
{
// This is a generated Razor document, and they want diagnostics, so let's report it
return true;
}
if (!document.SupportsDiagnostics())
{
return false;
}
// change it to check active file (or visible files), not open files if active file tracking is enabled.
// otherwise, use open file.
if (SolutionCrawlerOptions.GetBackgroundAnalysisScope(document.Project) == BackgroundAnalysisScope.ActiveFile)
{
return documentTrackingService.TryGetActiveDocument() == document.Id;
}
else
{
return document.IsOpen();
}
}
/// <summary>
/// Return list of <see cref="StateSet"/> to be used for full solution analysis.
/// </summary>
private IReadOnlyList<StateSet> GetStateSetsForFullSolutionAnalysis(IEnumerable<StateSet> stateSets, Project project)
{
// If full analysis is off, remove state that is created from build.
// this will make sure diagnostics from build (converted from build to live) will never be cleared
// until next build.
if (SolutionCrawlerOptions.GetBackgroundAnalysisScope(project) != BackgroundAnalysisScope.FullSolution)
{
stateSets = stateSets.Where(s => !s.FromBuild(project.Id));
}
// include all analyzers if option is on
if (project.Solution.Workspace.Options.GetOption(InternalDiagnosticsOptions.ProcessHiddenDiagnostics))
{
return stateSets.ToList();
}
// Compute analyzer config options for computing effective severity.
// Note that these options are not cached onto the project, so we compute it once upfront.
var analyzerConfigOptions = project.GetAnalyzerConfigOptions();
// Include only analyzers we want to run for full solution analysis.
// Analyzers not included here will never be saved because result is unknown.
return stateSets.Where(s => IsCandidateForFullSolutionAnalysis(s.Analyzer, project, analyzerConfigOptions)).ToList();
}
private bool IsCandidateForFullSolutionAnalysis(DiagnosticAnalyzer analyzer, Project project, AnalyzerConfigOptionsResult? analyzerConfigOptions)
{
// PERF: Don't query descriptors for compiler analyzer or file content load analyzer, always execute them.
if (analyzer == FileContentLoadAnalyzer.Instance || analyzer.IsCompilerAnalyzer())
{
return true;
}
if (analyzer.IsBuiltInAnalyzer())
{
// always return true for builtin analyzer. we can't use
// descriptor check since many builtin analyzer always return
// hidden descriptor regardless what descriptor it actually
// return on runtime. they do this so that they can control
// severity through option page rather than rule set editor.
// this is special behavior only ide analyzer can do. we hope
// once we support editorconfig fully, third party can use this
// ability as well and we can remove this kind special treatment on builtin
// analyzer.
return true;
}
if (analyzer is DiagnosticSuppressor)
{
// Always execute diagnostic suppressors.
return true;
}
// For most of analyzers, the number of diagnostic descriptors is small, so this should be cheap.
var descriptors = DiagnosticAnalyzerInfoCache.GetDiagnosticDescriptors(analyzer);
return descriptors.Any(d => d.GetEffectiveSeverity(project.CompilationOptions!, analyzerConfigOptions) != ReportDiagnostic.Hidden);
}
private void RaiseProjectDiagnosticsIfNeeded(
Project project,
IEnumerable<StateSet> stateSets,
ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> result)
{
RaiseProjectDiagnosticsIfNeeded(project, stateSets, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>.Empty, result);
}
private void RaiseProjectDiagnosticsIfNeeded(
Project project,
IEnumerable<StateSet> stateSets,
ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> oldResult,
ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> newResult)
{
if (oldResult.Count == 0 && newResult.Count == 0)
{
// there is nothing to update
return;
}
AnalyzerService.RaiseBulkDiagnosticsUpdated(raiseEvents =>
{
foreach (var stateSet in stateSets)
{
var analyzer = stateSet.Analyzer;
var oldAnalysisResult = GetResultOrEmpty(oldResult, analyzer, project.Id, VersionStamp.Default);
var newAnalysisResult = GetResultOrEmpty(newResult, analyzer, project.Id, VersionStamp.Default);
// Perf - 4 different cases.
// upper 3 cases can be removed and it will still work. but this is hot path so if we can bail out
// without any allocations, that's better.
if (oldAnalysisResult.IsEmpty && newAnalysisResult.IsEmpty)
{
// nothing to do
continue;
}
if (!oldAnalysisResult.IsEmpty && newAnalysisResult.IsEmpty)
{
RoslynDebug.Assert(oldAnalysisResult.DocumentIds != null);
// remove old diagnostics
RaiseProjectDiagnosticsRemoved(stateSet, oldAnalysisResult.ProjectId, oldAnalysisResult.DocumentIds, handleActiveFile: false, raiseEvents);
continue;
}
if (oldAnalysisResult.IsEmpty && !newAnalysisResult.IsEmpty)
{
// add new diagnostics
RaiseProjectDiagnosticsCreated(project, stateSet, oldAnalysisResult, newAnalysisResult, raiseEvents);
continue;
}
// both old and new has items in them. update existing items
RoslynDebug.Assert(oldAnalysisResult.DocumentIds != null);
RoslynDebug.Assert(newAnalysisResult.DocumentIds != null);
// first remove ones no longer needed.
var documentsToRemove = oldAnalysisResult.DocumentIds.Except(newAnalysisResult.DocumentIds);
RaiseProjectDiagnosticsRemoved(stateSet, oldAnalysisResult.ProjectId, documentsToRemove, handleActiveFile: false, raiseEvents);
// next update or create new ones
RaiseProjectDiagnosticsCreated(project, stateSet, oldAnalysisResult, newAnalysisResult, raiseEvents);
}
});
}
private void RaiseDocumentDiagnosticsIfNeeded(TextDocument document, StateSet stateSet, AnalysisKind kind, ImmutableArray<DiagnosticData> items)
=> RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, ImmutableArray<DiagnosticData>.Empty, items);
private void RaiseDocumentDiagnosticsIfNeeded(
TextDocument document, StateSet stateSet, AnalysisKind kind, ImmutableArray<DiagnosticData> oldItems, ImmutableArray<DiagnosticData> newItems)
{
RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, oldItems, newItems, AnalyzerService.RaiseDiagnosticsUpdated, forceUpdate: false);
}
private void RaiseDocumentDiagnosticsIfNeeded(
TextDocument document, StateSet stateSet, AnalysisKind kind,
DiagnosticAnalysisResult oldResult, DiagnosticAnalysisResult newResult,
Action<DiagnosticsUpdatedArgs> raiseEvents)
{
// if our old result is from build and we don't have actual data, don't try micro-optimize and always refresh diagnostics.
// most of time, we don't actually load or hold the old data in memory from persistent storage due to perf reasons.
//
// we need this special behavior for errors from build since unlike live errors, we don't know whether errors
// from build is for syntax, semantic or others. due to that, we blindly mark them as semantic errors (most common type of errors from build)
//
// that can sometime cause issues. for example, if the error turns out to be syntax error (live) then we at the end fail to de-dup.
// but since this optimization saves us a lot of refresh between live errors analysis we want to disable this only in this condition.
var forceUpdate = oldResult.FromBuild && oldResult.IsAggregatedForm;
var oldItems = oldResult.GetDocumentDiagnostics(document.Id, kind);
var newItems = newResult.GetDocumentDiagnostics(document.Id, kind);
RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, oldItems, newItems, raiseEvents, forceUpdate);
}
private void RaiseDocumentDiagnosticsIfNeeded(
TextDocument document, StateSet stateSet, AnalysisKind kind,
ImmutableArray<DiagnosticData> oldItems, ImmutableArray<DiagnosticData> newItems,
Action<DiagnosticsUpdatedArgs> raiseEvents,
bool forceUpdate)
{
if (!forceUpdate && oldItems.IsEmpty && newItems.IsEmpty)
{
// there is nothing to update
return;
}
RaiseDiagnosticsCreated(document, stateSet, kind, newItems, raiseEvents);
}
private void RaiseProjectDiagnosticsCreated(Project project, StateSet stateSet, DiagnosticAnalysisResult oldAnalysisResult, DiagnosticAnalysisResult newAnalysisResult, Action<DiagnosticsUpdatedArgs> raiseEvents)
{
RoslynDebug.Assert(newAnalysisResult.DocumentIds != null);
foreach (var documentId in newAnalysisResult.DocumentIds)
{
var document = project.GetTextDocument(documentId);
if (document == null)
{
// it can happen with build synchronization since, in build case,
// we don't have actual snapshot (we have no idea what sources out of proc build has picked up)
// so we might be out of sync.
// example of such cases will be changing anything about solution while building is going on.
// it can be user explicit actions such as unloading project, deleting a file, but also it can be
// something project system or roslyn workspace does such as populating workspace right after
// solution is loaded.
continue;
}
RaiseDocumentDiagnosticsIfNeeded(document, stateSet, AnalysisKind.NonLocal, oldAnalysisResult, newAnalysisResult, raiseEvents);
// we don't raise events for active file. it will be taken cared by active file analysis
if (stateSet.IsActiveFile(documentId))
{
continue;
}
RaiseDocumentDiagnosticsIfNeeded(document, stateSet, AnalysisKind.Syntax, oldAnalysisResult, newAnalysisResult, raiseEvents);
RaiseDocumentDiagnosticsIfNeeded(document, stateSet, AnalysisKind.Semantic, oldAnalysisResult, newAnalysisResult, raiseEvents);
}
RaiseDiagnosticsCreated(project, stateSet, newAnalysisResult.GetOtherDiagnostics(), raiseEvents);
}
private void RaiseProjectDiagnosticsRemoved(StateSet stateSet, ProjectId projectId, IEnumerable<DocumentId> documentIds, bool handleActiveFile, Action<DiagnosticsUpdatedArgs> raiseEvents)
{
foreach (var documentId in documentIds)
{
RaiseDiagnosticsRemoved(documentId, solution: null, stateSet, AnalysisKind.NonLocal, raiseEvents);
// we don't raise events for active file. it will be taken care of by active file analysis
if (!handleActiveFile && stateSet.IsActiveFile(documentId))
{
continue;
}
RaiseDiagnosticsRemoved(documentId, solution: null, stateSet, AnalysisKind.Syntax, raiseEvents);
RaiseDiagnosticsRemoved(documentId, solution: null, stateSet, AnalysisKind.Semantic, raiseEvents);
}
RaiseDiagnosticsRemoved(projectId, solution: null, stateSet, raiseEvents);
}
}
}
| // 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Workspaces.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2
{
internal partial class DiagnosticIncrementalAnalyzer
{
public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken)
=> AnalyzeDocumentForKindAsync(document, AnalysisKind.Syntax, cancellationToken);
public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken)
=> AnalyzeDocumentForKindAsync(document, AnalysisKind.Semantic, cancellationToken);
public Task AnalyzeNonSourceDocumentAsync(TextDocument textDocument, InvocationReasons reasons, CancellationToken cancellationToken)
=> AnalyzeDocumentForKindAsync(textDocument, AnalysisKind.Syntax, cancellationToken);
private async Task AnalyzeDocumentForKindAsync(TextDocument document, AnalysisKind kind, CancellationToken cancellationToken)
{
try
{
if (!AnalysisEnabled(document, _documentTrackingService))
{
// to reduce allocations, here, we don't clear existing diagnostics since it is dealt by other entry point such as
// DocumentReset or DocumentClosed.
return;
}
var stateSets = _stateManager.GetOrUpdateStateSets(document.Project);
var compilationWithAnalyzers = await GetOrCreateCompilationWithAnalyzersAsync(document.Project, stateSets, cancellationToken).ConfigureAwait(false);
// We split the diagnostic computation for document into following steps:
// 1. Try to get cached diagnostics for each analyzer, while computing the set of analyzers that do not have cached diagnostics.
// 2. Execute all the non-cached analyzers with a single invocation into CompilationWithAnalyzers.
// 3. Fetch computed diagnostics per-analyzer from the above invocation, and cache and raise diagnostic reported events.
// In near future, the diagnostic computation invocation into CompilationWithAnalyzers will be moved to OOP.
// This should help simplify and/or remove the IDE layer diagnostic caching in devenv process.
// First attempt to fetch diagnostics from the cache, while computing the state sets for analyzers that are not cached.
using var _ = ArrayBuilder<StateSet>.GetInstance(out var nonCachedStateSets);
foreach (var stateSet in stateSets)
{
var data = await TryGetCachedDocumentAnalysisDataAsync(document, stateSet, kind, cancellationToken).ConfigureAwait(false);
if (data.HasValue)
{
// We need to persist and raise diagnostics for suppressed analyzer.
PersistAndRaiseDiagnosticsIfNeeded(data.Value, stateSet);
}
else
{
nonCachedStateSets.Add(stateSet);
}
}
// Then, compute the diagnostics for non-cached state sets, and cache and raise diagnostic reported events for these diagnostics.
if (nonCachedStateSets.Count > 0)
{
var analysisScope = new DocumentAnalysisScope(document, span: null, nonCachedStateSets.SelectAsArray(s => s.Analyzer), kind);
var executor = new DocumentAnalysisExecutor(analysisScope, compilationWithAnalyzers, _diagnosticAnalyzerRunner, logPerformanceInfo: true, onAnalysisException: OnAnalysisException);
foreach (var stateSet in nonCachedStateSets)
{
var computedData = await ComputeDocumentAnalysisDataAsync(executor, stateSet, cancellationToken).ConfigureAwait(false);
PersistAndRaiseDiagnosticsIfNeeded(computedData, stateSet);
}
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
void PersistAndRaiseDiagnosticsIfNeeded(DocumentAnalysisData result, StateSet stateSet)
{
if (result.FromCache == true)
{
RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, result.Items);
return;
}
// no cancellation after this point.
var state = stateSet.GetOrCreateActiveFileState(document.Id);
state.Save(kind, result.ToPersistData());
RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, result.OldItems, result.Items);
}
void OnAnalysisException()
{
// Do not re-use cached CompilationWithAnalyzers instance in presence of an exception, as the underlying analysis state might be corrupt.
ClearCompilationsWithAnalyzersCache(document.Project);
}
}
public async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken)
{
// Perf optimization. check whether we want to analyze this project or not.
if (!FullAnalysisEnabled(project, forceAnalyzerRun: false))
{
return;
}
await AnalyzeProjectAsync(project, forceAnalyzerRun: false, cancellationToken).ConfigureAwait(false);
}
public Task ForceAnalyzeProjectAsync(Project project, CancellationToken cancellationToken)
=> AnalyzeProjectAsync(project, forceAnalyzerRun: true, cancellationToken);
private async Task AnalyzeProjectAsync(Project project, bool forceAnalyzerRun, CancellationToken cancellationToken)
{
try
{
var stateSets = GetStateSetsForFullSolutionAnalysis(_stateManager.GetOrUpdateStateSets(project), project);
var options = project.Solution.Options;
// PERF: get analyzers that are not suppressed and marked as open file only
// this is perf optimization. we cache these result since we know the result. (no diagnostics)
var activeAnalyzers = stateSets
.Select(s => s.Analyzer)
.Where(a => !DiagnosticAnalyzerInfoCache.IsAnalyzerSuppressed(a, project) && !a.IsOpenFileOnly(options));
// get driver only with active analyzers.
var compilationWithAnalyzers = await AnalyzerHelper.CreateCompilationWithAnalyzersAsync(project, activeAnalyzers, includeSuppressedDiagnostics: true, cancellationToken).ConfigureAwait(false);
var result = await GetProjectAnalysisDataAsync(compilationWithAnalyzers, project, stateSets, forceAnalyzerRun, cancellationToken).ConfigureAwait(false);
if (result.OldResult == null)
{
RaiseProjectDiagnosticsIfNeeded(project, stateSets, result.Result);
return;
}
// we might not have compilationWithAnalyzers even if project supports compilation if we are called with no analyzers.
var compilation = compilationWithAnalyzers?.Compilation ??
(project.SupportsCompilation ? await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false) : null);
// no cancellation after this point.
// any analyzer that doesn't have result will be treated as returned empty set
// which means we will remove those from error list
foreach (var stateSet in stateSets)
{
var state = stateSet.GetOrCreateProjectState(project.Id);
await state.SaveToInMemoryStorageAsync(project, result.GetResult(stateSet.Analyzer)).ConfigureAwait(false);
}
RaiseProjectDiagnosticsIfNeeded(project, stateSets, result.OldResult, result.Result);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
=> TextDocumentOpenAsync(document, cancellationToken);
public Task NonSourceDocumentOpenAsync(TextDocument document, CancellationToken cancellationToken)
=> TextDocumentOpenAsync(document, cancellationToken);
private async Task TextDocumentOpenAsync(TextDocument document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentOpen, GetOpenLogMessage, document, cancellationToken))
{
var stateSets = _stateManager.GetStateSets(document.Project);
// let other component knows about this event
ClearCompilationsWithAnalyzersCache();
// can not be canceled
foreach (var stateSet in stateSets)
await stateSet.OnDocumentOpenedAsync(document).ConfigureAwait(false);
}
}
public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken)
=> TextDocumentCloseAsync(document, cancellationToken);
public Task NonSourceDocumentCloseAsync(TextDocument document, CancellationToken cancellationToken)
=> TextDocumentCloseAsync(document, cancellationToken);
private async Task TextDocumentCloseAsync(TextDocument document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentClose, GetResetLogMessage, document, cancellationToken))
{
var stateSets = _stateManager.GetStateSets(document.Project);
// let other components knows about this event
ClearCompilationsWithAnalyzersCache();
// can not be canceled
var documentHadDiagnostics = false;
foreach (var stateSet in stateSets)
documentHadDiagnostics |= await stateSet.OnDocumentClosedAsync(document).ConfigureAwait(false);
RaiseDiagnosticsRemovedIfRequiredForClosedOrResetDocument(document, stateSets, documentHadDiagnostics);
}
}
public Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
=> TextDocumentResetAsync(document, cancellationToken);
public Task NonSourceDocumentResetAsync(TextDocument document, CancellationToken cancellationToken)
=> TextDocumentResetAsync(document, cancellationToken);
private Task TextDocumentResetAsync(TextDocument document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentReset, GetResetLogMessage, document, cancellationToken))
{
var stateSets = _stateManager.GetStateSets(document.Project);
// let other components knows about this event
ClearCompilationsWithAnalyzersCache();
// can not be canceled
var documentHadDiagnostics = false;
foreach (var stateSet in stateSets)
documentHadDiagnostics |= stateSet.OnDocumentReset(document);
RaiseDiagnosticsRemovedIfRequiredForClosedOrResetDocument(document, stateSets, documentHadDiagnostics);
}
return Task.CompletedTask;
}
private void RaiseDiagnosticsRemovedIfRequiredForClosedOrResetDocument(TextDocument document, IEnumerable<StateSet> stateSets, bool documentHadDiagnostics)
{
// if there was no diagnostic reported for this document OR Full solution analysis is enabled, nothing to clean up
if (!documentHadDiagnostics ||
FullAnalysisEnabled(document.Project, forceAnalyzerRun: false))
{
// this is Perf to reduce raising events unnecessarily.
return;
}
var removeDiagnosticsOnDocumentClose = document.Project.Solution.Options.GetOption(ServiceFeatureOnOffOptions.RemoveDocumentDiagnosticsOnDocumentClose, document.Project.Language);
if (!removeDiagnosticsOnDocumentClose)
{
return;
}
RaiseDiagnosticsRemovedForDocument(document.Id, stateSets);
}
public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_RemoveDocument, GetRemoveLogMessage, documentId, CancellationToken.None))
{
var stateSets = _stateManager.GetStateSets(documentId.ProjectId);
// let other components knows about this event
ClearCompilationsWithAnalyzersCache();
var changed = false;
foreach (var stateSet in stateSets)
changed |= stateSet.OnDocumentRemoved(documentId);
// if there was no diagnostic reported for this document, nothing to clean up
// this is Perf to reduce raising events unnecessarily.
if (changed)
RaiseDiagnosticsRemovedForDocument(documentId, stateSets);
}
return Task.CompletedTask;
}
private void RaiseDiagnosticsRemovedForDocument(DocumentId documentId, IEnumerable<StateSet> stateSets)
{
// remove all diagnostics for the document
AnalyzerService.RaiseBulkDiagnosticsUpdated(raiseEvents =>
{
foreach (var stateSet in stateSets)
{
// clear all doucment diagnostics
RaiseDiagnosticsRemoved(documentId, solution: null, stateSet, AnalysisKind.Syntax, raiseEvents);
RaiseDiagnosticsRemoved(documentId, solution: null, stateSet, AnalysisKind.Semantic, raiseEvents);
RaiseDiagnosticsRemoved(documentId, solution: null, stateSet, AnalysisKind.NonLocal, raiseEvents);
}
});
}
public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellation)
{
using (Logger.LogBlock(FunctionId.Diagnostics_RemoveProject, GetRemoveLogMessage, projectId, CancellationToken.None))
{
var stateSets = _stateManager.GetStateSets(projectId);
// let other components knows about this event
ClearCompilationsWithAnalyzersCache();
var changed = _stateManager.OnProjectRemoved(stateSets, projectId);
// if there was no diagnostic reported for this project, nothing to clean up
// this is Perf to reduce raising events unnecessarily.
if (changed)
{
// remove all diagnostics for the project
AnalyzerService.RaiseBulkDiagnosticsUpdated(raiseEvents =>
{
foreach (var stateSet in stateSets)
{
// clear all project diagnostics
RaiseDiagnosticsRemoved(projectId, solution: null, stateSet, raiseEvents);
}
});
}
}
return Task.CompletedTask;
}
public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
{
// let other components knows about this event
ClearCompilationsWithAnalyzersCache();
return Task.CompletedTask;
}
private static bool AnalysisEnabled(TextDocument document, IDocumentTrackingService documentTrackingService)
{
if (document.Services.GetService<DocumentPropertiesService>()?.DiagnosticsLspClientName != null)
{
// This is a generated Razor document, and they want diagnostics, so let's report it
return true;
}
if (!document.SupportsDiagnostics())
{
return false;
}
// change it to check active file (or visible files), not open files if active file tracking is enabled.
// otherwise, use open file.
if (SolutionCrawlerOptions.GetBackgroundAnalysisScope(document.Project) == BackgroundAnalysisScope.ActiveFile)
{
return documentTrackingService.TryGetActiveDocument() == document.Id;
}
else
{
return document.IsOpen();
}
}
/// <summary>
/// Return list of <see cref="StateSet"/> to be used for full solution analysis.
/// </summary>
private IReadOnlyList<StateSet> GetStateSetsForFullSolutionAnalysis(IEnumerable<StateSet> stateSets, Project project)
{
// If full analysis is off, remove state that is created from build.
// this will make sure diagnostics from build (converted from build to live) will never be cleared
// until next build.
if (SolutionCrawlerOptions.GetBackgroundAnalysisScope(project) != BackgroundAnalysisScope.FullSolution)
{
stateSets = stateSets.Where(s => !s.FromBuild(project.Id));
}
// include all analyzers if option is on
if (project.Solution.Workspace.Options.GetOption(InternalDiagnosticsOptions.ProcessHiddenDiagnostics))
{
return stateSets.ToList();
}
// Compute analyzer config options for computing effective severity.
// Note that these options are not cached onto the project, so we compute it once upfront.
var analyzerConfigOptions = project.GetAnalyzerConfigOptions();
// Include only analyzers we want to run for full solution analysis.
// Analyzers not included here will never be saved because result is unknown.
return stateSets.Where(s => IsCandidateForFullSolutionAnalysis(s.Analyzer, project, analyzerConfigOptions)).ToList();
}
private bool IsCandidateForFullSolutionAnalysis(DiagnosticAnalyzer analyzer, Project project, AnalyzerConfigOptionsResult? analyzerConfigOptions)
{
// PERF: Don't query descriptors for compiler analyzer or file content load analyzer, always execute them.
if (analyzer == FileContentLoadAnalyzer.Instance || analyzer.IsCompilerAnalyzer())
{
return true;
}
if (analyzer.IsBuiltInAnalyzer())
{
// always return true for builtin analyzer. we can't use
// descriptor check since many builtin analyzer always return
// hidden descriptor regardless what descriptor it actually
// return on runtime. they do this so that they can control
// severity through option page rather than rule set editor.
// this is special behavior only ide analyzer can do. we hope
// once we support editorconfig fully, third party can use this
// ability as well and we can remove this kind special treatment on builtin
// analyzer.
return true;
}
if (analyzer is DiagnosticSuppressor)
{
// Always execute diagnostic suppressors.
return true;
}
// For most of analyzers, the number of diagnostic descriptors is small, so this should be cheap.
var descriptors = DiagnosticAnalyzerInfoCache.GetDiagnosticDescriptors(analyzer);
return descriptors.Any(d => d.GetEffectiveSeverity(project.CompilationOptions!, analyzerConfigOptions) != ReportDiagnostic.Hidden);
}
private void RaiseProjectDiagnosticsIfNeeded(
Project project,
IEnumerable<StateSet> stateSets,
ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> result)
{
RaiseProjectDiagnosticsIfNeeded(project, stateSets, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>.Empty, result);
}
private void RaiseProjectDiagnosticsIfNeeded(
Project project,
IEnumerable<StateSet> stateSets,
ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> oldResult,
ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> newResult)
{
if (oldResult.Count == 0 && newResult.Count == 0)
{
// there is nothing to update
return;
}
AnalyzerService.RaiseBulkDiagnosticsUpdated(raiseEvents =>
{
foreach (var stateSet in stateSets)
{
var analyzer = stateSet.Analyzer;
var oldAnalysisResult = GetResultOrEmpty(oldResult, analyzer, project.Id, VersionStamp.Default);
var newAnalysisResult = GetResultOrEmpty(newResult, analyzer, project.Id, VersionStamp.Default);
// Perf - 4 different cases.
// upper 3 cases can be removed and it will still work. but this is hot path so if we can bail out
// without any allocations, that's better.
if (oldAnalysisResult.IsEmpty && newAnalysisResult.IsEmpty)
{
// nothing to do
continue;
}
if (!oldAnalysisResult.IsEmpty && newAnalysisResult.IsEmpty)
{
RoslynDebug.Assert(oldAnalysisResult.DocumentIds != null);
// remove old diagnostics
RaiseProjectDiagnosticsRemoved(stateSet, oldAnalysisResult.ProjectId, oldAnalysisResult.DocumentIds, handleActiveFile: false, raiseEvents);
continue;
}
if (oldAnalysisResult.IsEmpty && !newAnalysisResult.IsEmpty)
{
// add new diagnostics
RaiseProjectDiagnosticsCreated(project, stateSet, oldAnalysisResult, newAnalysisResult, raiseEvents);
continue;
}
// both old and new has items in them. update existing items
RoslynDebug.Assert(oldAnalysisResult.DocumentIds != null);
RoslynDebug.Assert(newAnalysisResult.DocumentIds != null);
// first remove ones no longer needed.
var documentsToRemove = oldAnalysisResult.DocumentIds.Except(newAnalysisResult.DocumentIds);
RaiseProjectDiagnosticsRemoved(stateSet, oldAnalysisResult.ProjectId, documentsToRemove, handleActiveFile: false, raiseEvents);
// next update or create new ones
RaiseProjectDiagnosticsCreated(project, stateSet, oldAnalysisResult, newAnalysisResult, raiseEvents);
}
});
}
private void RaiseDocumentDiagnosticsIfNeeded(TextDocument document, StateSet stateSet, AnalysisKind kind, ImmutableArray<DiagnosticData> items)
=> RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, ImmutableArray<DiagnosticData>.Empty, items);
private void RaiseDocumentDiagnosticsIfNeeded(
TextDocument document, StateSet stateSet, AnalysisKind kind, ImmutableArray<DiagnosticData> oldItems, ImmutableArray<DiagnosticData> newItems)
{
RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, oldItems, newItems, AnalyzerService.RaiseDiagnosticsUpdated, forceUpdate: false);
}
private void RaiseDocumentDiagnosticsIfNeeded(
TextDocument document, StateSet stateSet, AnalysisKind kind,
DiagnosticAnalysisResult oldResult, DiagnosticAnalysisResult newResult,
Action<DiagnosticsUpdatedArgs> raiseEvents)
{
// if our old result is from build and we don't have actual data, don't try micro-optimize and always refresh diagnostics.
// most of time, we don't actually load or hold the old data in memory from persistent storage due to perf reasons.
//
// we need this special behavior for errors from build since unlike live errors, we don't know whether errors
// from build is for syntax, semantic or others. due to that, we blindly mark them as semantic errors (most common type of errors from build)
//
// that can sometime cause issues. for example, if the error turns out to be syntax error (live) then we at the end fail to de-dup.
// but since this optimization saves us a lot of refresh between live errors analysis we want to disable this only in this condition.
var forceUpdate = oldResult.FromBuild && oldResult.IsAggregatedForm;
var oldItems = oldResult.GetDocumentDiagnostics(document.Id, kind);
var newItems = newResult.GetDocumentDiagnostics(document.Id, kind);
RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, oldItems, newItems, raiseEvents, forceUpdate);
}
private void RaiseDocumentDiagnosticsIfNeeded(
TextDocument document, StateSet stateSet, AnalysisKind kind,
ImmutableArray<DiagnosticData> oldItems, ImmutableArray<DiagnosticData> newItems,
Action<DiagnosticsUpdatedArgs> raiseEvents,
bool forceUpdate)
{
if (!forceUpdate && oldItems.IsEmpty && newItems.IsEmpty)
{
// there is nothing to update
return;
}
RaiseDiagnosticsCreated(document, stateSet, kind, newItems, raiseEvents);
}
private void RaiseProjectDiagnosticsCreated(Project project, StateSet stateSet, DiagnosticAnalysisResult oldAnalysisResult, DiagnosticAnalysisResult newAnalysisResult, Action<DiagnosticsUpdatedArgs> raiseEvents)
{
RoslynDebug.Assert(newAnalysisResult.DocumentIds != null);
foreach (var documentId in newAnalysisResult.DocumentIds)
{
var document = project.GetTextDocument(documentId);
if (document == null)
{
// it can happen with build synchronization since, in build case,
// we don't have actual snapshot (we have no idea what sources out of proc build has picked up)
// so we might be out of sync.
// example of such cases will be changing anything about solution while building is going on.
// it can be user explicit actions such as unloading project, deleting a file, but also it can be
// something project system or roslyn workspace does such as populating workspace right after
// solution is loaded.
continue;
}
RaiseDocumentDiagnosticsIfNeeded(document, stateSet, AnalysisKind.NonLocal, oldAnalysisResult, newAnalysisResult, raiseEvents);
// we don't raise events for active file. it will be taken cared by active file analysis
if (stateSet.IsActiveFile(documentId))
{
continue;
}
RaiseDocumentDiagnosticsIfNeeded(document, stateSet, AnalysisKind.Syntax, oldAnalysisResult, newAnalysisResult, raiseEvents);
RaiseDocumentDiagnosticsIfNeeded(document, stateSet, AnalysisKind.Semantic, oldAnalysisResult, newAnalysisResult, raiseEvents);
}
RaiseDiagnosticsCreated(project, stateSet, newAnalysisResult.GetOtherDiagnostics(), raiseEvents);
}
private void RaiseProjectDiagnosticsRemoved(StateSet stateSet, ProjectId projectId, IEnumerable<DocumentId> documentIds, bool handleActiveFile, Action<DiagnosticsUpdatedArgs> raiseEvents)
{
foreach (var documentId in documentIds)
{
RaiseDiagnosticsRemoved(documentId, solution: null, stateSet, AnalysisKind.NonLocal, raiseEvents);
// we don't raise events for active file. it will be taken care of by active file analysis
if (!handleActiveFile && stateSet.IsActiveFile(documentId))
{
continue;
}
RaiseDiagnosticsRemoved(documentId, solution: null, stateSet, AnalysisKind.Syntax, raiseEvents);
RaiseDiagnosticsRemoved(documentId, solution: null, stateSet, AnalysisKind.Semantic, raiseEvents);
}
RaiseDiagnosticsRemoved(projectId, solution: null, stateSet, raiseEvents);
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Features/Core/Portable/Diagnostics/DiagnosticProviderMetadata.cs | // 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.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal class DiagnosticProviderMetadata : ILanguageMetadata
{
public string Name { get; }
public string Language { get; }
public DiagnosticProviderMetadata(IDictionary<string, object> data)
{
Name = (string)data.GetValueOrDefault("Name");
Language = (string)data.GetValueOrDefault("Language");
}
}
}
| // 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.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal class DiagnosticProviderMetadata : ILanguageMetadata
{
public string Name { get; }
public string Language { get; }
public DiagnosticProviderMetadata(IDictionary<string, object> data)
{
Name = (string)data.GetValueOrDefault("Name");
Language = (string)data.GetValueOrDefault("Language");
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Analyzers/VisualBasic/Tests/UseIsNotExpression/UseIsNotExpressionTests.vb | ' 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.
Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of
Microsoft.CodeAnalysis.VisualBasic.UseIsNotExpression.VisualBasicUseIsNotExpressionDiagnosticAnalyzer,
Microsoft.CodeAnalysis.VisualBasic.UseIsNotExpression.VisualBasicUseIsNotExpressionCodeFixProvider)
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.UseIsNotExpression
Partial Public Class UseIsNotExpressionTests
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIsNotExpression)>
<WorkItem(46706, "https://github.com/dotnet/roslyn/issues/46706")>
Public Async Function TestIsExpression() As Task
Await New VerifyVB.Test With {
.TestCode = "
class C
sub M(o as object)
if not o [|is|] nothing
end if
end sub
end class",
.FixedCode = "
class C
sub M(o as object)
if o IsNot nothing
end if
end sub
end class"
}.RunAsync()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIsNotExpression)>
Public Async Function TestTypeOfIsExpression() As Task
Await New VerifyVB.Test With {
.TestCode = "
class C
sub M(o as object)
if not typeof o [|is|] string
end if
end sub
end class",
.FixedCode = "
class C
sub M(o as object)
if typeof o IsNot string
end if
end sub
end class"
}.RunAsync()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIsNotExpression)>
Public Async Function TestVB12() As Task
Await New VerifyVB.Test With {
.TestCode = "
class C
sub M(o as object)
if not o is nothing
end if
end sub
end class",
.LanguageVersion = LanguageVersion.VisualBasic12
}.RunAsync()
End Function
End Class
End Namespace
| ' 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.
Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of
Microsoft.CodeAnalysis.VisualBasic.UseIsNotExpression.VisualBasicUseIsNotExpressionDiagnosticAnalyzer,
Microsoft.CodeAnalysis.VisualBasic.UseIsNotExpression.VisualBasicUseIsNotExpressionCodeFixProvider)
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.UseIsNotExpression
Partial Public Class UseIsNotExpressionTests
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIsNotExpression)>
<WorkItem(46706, "https://github.com/dotnet/roslyn/issues/46706")>
Public Async Function TestIsExpression() As Task
Await New VerifyVB.Test With {
.TestCode = "
class C
sub M(o as object)
if not o [|is|] nothing
end if
end sub
end class",
.FixedCode = "
class C
sub M(o as object)
if o IsNot nothing
end if
end sub
end class"
}.RunAsync()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIsNotExpression)>
Public Async Function TestTypeOfIsExpression() As Task
Await New VerifyVB.Test With {
.TestCode = "
class C
sub M(o as object)
if not typeof o [|is|] string
end if
end sub
end class",
.FixedCode = "
class C
sub M(o as object)
if typeof o IsNot string
end if
end sub
end class"
}.RunAsync()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIsNotExpression)>
Public Async Function TestVB12() As Task
Await New VerifyVB.Test With {
.TestCode = "
class C
sub M(o as object)
if not o is nothing
end if
end sub
end class",
.LanguageVersion = LanguageVersion.VisualBasic12
}.RunAsync()
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/EditorFeatures/CSharpTest2/Recommendations/BreakKeywordRecommenderTests.cs | // 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.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class BreakKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot()
{
await VerifyAbsenceAsync(
@"$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement()
{
await VerifyAbsenceAsync(
@"System.Console.WriteLine();
$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration()
{
await VerifyAbsenceAsync(
@"int i = 0;
$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestEmptyStatement(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestBeforeStatement(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$
return true;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterStatement(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"return true;
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterBlock(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if (true) {
}
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterIf(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if (true)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterDo(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"do
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterWhile(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"while (true)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterFor(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"for (int i = 0; i < 10; i++)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterForeach(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach (var v in bar)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotInsideLambda(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"foreach (var v in bar) {
var d = () => {
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotInsideAnonymousMethod(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"foreach (var v in bar) {
var d = delegate {
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInsideSwitch(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (a) {
case 0:
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotInsideSwitchWithLambda(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"switch (a) {
case 0:
var d = () => {
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInsideSwitchOutsideLambda(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (a) {
case 0:
var d = () => {
};
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotAfterBreak(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"break $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInClass()
{
await VerifyAbsenceAsync(@"class C
{
$$
}");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterYield(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"yield $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterSwitchInSwitch(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (expr) {
default:
switch (expr) {
}
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterBlockInSwitch(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (expr) {
default:
{
}
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
}
}
| // 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.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class BreakKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot()
{
await VerifyAbsenceAsync(
@"$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement()
{
await VerifyAbsenceAsync(
@"System.Console.WriteLine();
$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration()
{
await VerifyAbsenceAsync(
@"int i = 0;
$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestEmptyStatement(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestBeforeStatement(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$
return true;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterStatement(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"return true;
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterBlock(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if (true) {
}
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterIf(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if (true)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterDo(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"do
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterWhile(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"while (true)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterFor(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"for (int i = 0; i < 10; i++)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterForeach(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach (var v in bar)
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotInsideLambda(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"foreach (var v in bar) {
var d = () => {
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotInsideAnonymousMethod(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"foreach (var v in bar) {
var d = delegate {
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInsideSwitch(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (a) {
case 0:
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotInsideSwitchWithLambda(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"switch (a) {
case 0:
var d = () => {
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInsideSwitchOutsideLambda(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (a) {
case 0:
var d = () => {
};
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotAfterBreak(bool topLevelStatement)
{
await VerifyAbsenceAsync(AddInsideMethod(
@"break $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInClass()
{
await VerifyAbsenceAsync(@"class C
{
$$
}");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterYield(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"yield $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterSwitchInSwitch(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (expr) {
default:
switch (expr) {
}
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterBlockInSwitch(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (expr) {
default:
{
}
$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Workspaces/Core/Portable/Classification/SyntaxClassification/EmbeddedLanguagesClassifier.cs | // 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.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.Classification.Classifiers
{
internal class EmbeddedLanguagesClassifier : AbstractSyntaxClassifier
{
private readonly IEmbeddedLanguagesProvider _languagesProvider;
public override ImmutableArray<int> SyntaxTokenKinds { get; }
public EmbeddedLanguagesClassifier(IEmbeddedLanguagesProvider languagesProvider)
{
_languagesProvider = languagesProvider;
SyntaxTokenKinds =
languagesProvider.Languages.Where(p => p.Classifier != null)
.SelectMany(p => p.Classifier.SyntaxTokenKinds)
.Distinct()
.ToImmutableArray();
}
public override void AddClassifications(Workspace workspace, SyntaxToken token, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken)
{
foreach (var language in _languagesProvider.Languages)
{
var classifier = language.Classifier;
if (classifier != null)
{
var count = result.Count;
classifier.AddClassifications(workspace, token, semanticModel, result, cancellationToken);
if (result.Count != count)
{
// This classifier added values. No need to check the other ones.
return;
}
}
}
}
}
}
| // 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.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.Classification.Classifiers
{
internal class EmbeddedLanguagesClassifier : AbstractSyntaxClassifier
{
private readonly IEmbeddedLanguagesProvider _languagesProvider;
public override ImmutableArray<int> SyntaxTokenKinds { get; }
public EmbeddedLanguagesClassifier(IEmbeddedLanguagesProvider languagesProvider)
{
_languagesProvider = languagesProvider;
SyntaxTokenKinds =
languagesProvider.Languages.Where(p => p.Classifier != null)
.SelectMany(p => p.Classifier.SyntaxTokenKinds)
.Distinct()
.ToImmutableArray();
}
public override void AddClassifications(Workspace workspace, SyntaxToken token, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken)
{
foreach (var language in _languagesProvider.Languages)
{
var classifier = language.Classifier;
if (classifier != null)
{
var count = result.Count;
classifier.AddClassifications(workspace, token, semanticModel, result, cancellationToken);
if (result.Count != count)
{
// This classifier added values. No need to check the other ones.
return;
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/VisualBasic/Portable/Symbols/Source/LambdaSymbol.vb | ' 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.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a method symbol for a lambda method.
''' </summary>
Friend MustInherit Class LambdaSymbol
Inherits MethodSymbol
''' <summary>
''' This symbol is used as the return type of a LambdaSymbol when we are interpreting
''' lambda's body in order to infer its return type.
''' </summary>
Friend Shared ReadOnly ReturnTypeIsBeingInferred As TypeSymbol = New ErrorTypeSymbol()
''' <summary>
''' This symbol is used as the return type of a LambdaSymbol when we failed to
''' infer lambda's return type, but still want to interpret its body.
''' </summary>
Friend Shared ReadOnly ReturnTypeIsUnknown As TypeSymbol = New ErrorTypeSymbol()
''' <summary>
''' This symbol is used as the return type of a LambdaSymbol when we are dealing with
''' query lambda and the return type should be taken from the target delegate upon
''' successful conversion. The LambdaSymbol will be mutated then.
''' </summary>
Friend Shared ReadOnly ReturnTypePendingDelegate As TypeSymbol = New ErrorTypeSymbol()
''' <summary>
''' This symbol is used as the return type of a LambdaSymbol when System.Void is used in code.
''' </summary>
Friend Shared ReadOnly ReturnTypeVoidReplacement As TypeSymbol = New ErrorTypeSymbol()
''' <summary>
''' This symbol is used as a sentinel while we are binding a lambda in error recovery mode.
''' </summary>
Friend Shared ReadOnly ErrorRecoveryInferenceError As TypeSymbol = New ErrorTypeSymbol()
Private ReadOnly _syntaxNode As SyntaxNode
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
''' <summary>
''' Can mutate for a query lambda from ReturnTypePendingDelegate
''' to the return type of the target delegate.
''' </summary>
Protected m_ReturnType As TypeSymbol
' The binder associated with the block containing this lambda
Private ReadOnly _binder As Binder
Protected Sub New(
syntaxNode As SyntaxNode,
parameters As ImmutableArray(Of BoundLambdaParameterSymbol),
returnType As TypeSymbol,
binder As Binder
)
Debug.Assert(syntaxNode IsNot Nothing)
Debug.Assert(returnType IsNot Nothing)
_syntaxNode = syntaxNode
_parameters = StaticCast(Of ParameterSymbol).From(parameters)
m_ReturnType = returnType
_binder = binder
For Each param In parameters
param.SetLambdaSymbol(Me)
Next
End Sub
Public MustOverride ReadOnly Property SynthesizedKind As SynthesizedLambdaKind
Friend NotOverridable Overrides ReadOnly Property IsQueryLambdaMethod As Boolean
Get
Return SynthesizedKind.IsQueryLambda
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return 0
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
Return ImmutableArray(Of String).Empty
End Function
Public Overrides ReadOnly Property AssociatedSymbol As Symbol
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention
Get
Return Cci.CallingConvention.Default
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _binder.ContainingMember
End Get
End Property
Friend ReadOnly Property ContainingBinder As Binder
Get
Return _binder
End Get
End Property
''' <summary>
''' "Me" parameter for this lambda will be that of the containing symbol
''' </summary>
Friend Overrides Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean
Debug.Assert(ContainingSymbol IsNot Nothing)
Select Case ContainingSymbol.Kind
Case SymbolKind.Field
meParameter = DirectCast(ContainingSymbol, FieldSymbol).MeParameter
Case SymbolKind.Property
meParameter = DirectCast(ContainingSymbol, PropertySymbol).MeParameter
Case SymbolKind.Method
meParameter = DirectCast(ContainingSymbol, MethodSymbol).MeParameter
Case Else
meParameter = Nothing
End Select
Return True
End Function
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.Private
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)
Get
Return ImmutableArray(Of MethodSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsExternalMethod As Boolean
Get
Return False
End Get
End Property
Public Overrides Function GetDllImportData() As DllImportData
Return Nothing
End Function
Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes
Get
Return Nothing
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property HasDeclarativeSecurity As Boolean
Get
Return False
End Get
End Property
Friend NotOverridable Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute)
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverloads As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Dim container As Symbol = ContainingSymbol
Select Case container.Kind
Case SymbolKind.Field, SymbolKind.Property, SymbolKind.Method
Return container.IsShared
Case Else
Return True
End Select
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return m_ReturnType.IsVoidType()
End Get
End Property
Public Overrides ReadOnly Property IsVararg As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsInitOnly As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray.Create(_syntaxNode.GetLocation())
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray.Create(_syntaxNode.GetReference())
End Get
End Property
Friend Overrides ReadOnly Property IsLambdaMethod As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property MethodKind As MethodKind
Get
Return MethodKind.LambdaMethod
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _parameters
End Get
End Property
Public Overrides ReadOnly Property ReturnsByRef As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return m_ReturnType
End Get
End Property
Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return ImmutableArray(Of CustomModifier).Empty
End Get
End Property
Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return ImmutableArray(Of CustomModifier).Empty
End Get
End Property
Friend Overrides ReadOnly Property Syntax As SyntaxNode
Get
Return _syntaxNode
End Get
End Property
Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol)
Get
Return ImmutableArray(Of TypeSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean
Return False
End Function
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
' lambdas contain user code
Return True
End Get
End Property
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Me Then
Return True
End If
Dim symbol = TryCast(obj, LambdaSymbol)
Return symbol IsNot Nothing AndAlso
symbol._syntaxNode Is Me._syntaxNode AndAlso
Equals(symbol.ContainingSymbol, Me.ContainingSymbol) AndAlso
MethodSignatureComparer.AllAspectsSignatureComparer.Equals(symbol, Me)
End Function
Public Overrides Function GetHashCode() As Integer
Dim hc As Integer = Hash.Combine(Me.Syntax.GetHashCode(), Me._parameters.Length)
hc = Hash.Combine(hc, Me.ReturnType.GetHashCode())
For i = 0 To Me._parameters.Length - 1
hc = Hash.Combine(hc, Me._parameters(i).Type.GetHashCode())
Next
Return hc
End Function
End Class
End Namespace
| ' 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.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a method symbol for a lambda method.
''' </summary>
Friend MustInherit Class LambdaSymbol
Inherits MethodSymbol
''' <summary>
''' This symbol is used as the return type of a LambdaSymbol when we are interpreting
''' lambda's body in order to infer its return type.
''' </summary>
Friend Shared ReadOnly ReturnTypeIsBeingInferred As TypeSymbol = New ErrorTypeSymbol()
''' <summary>
''' This symbol is used as the return type of a LambdaSymbol when we failed to
''' infer lambda's return type, but still want to interpret its body.
''' </summary>
Friend Shared ReadOnly ReturnTypeIsUnknown As TypeSymbol = New ErrorTypeSymbol()
''' <summary>
''' This symbol is used as the return type of a LambdaSymbol when we are dealing with
''' query lambda and the return type should be taken from the target delegate upon
''' successful conversion. The LambdaSymbol will be mutated then.
''' </summary>
Friend Shared ReadOnly ReturnTypePendingDelegate As TypeSymbol = New ErrorTypeSymbol()
''' <summary>
''' This symbol is used as the return type of a LambdaSymbol when System.Void is used in code.
''' </summary>
Friend Shared ReadOnly ReturnTypeVoidReplacement As TypeSymbol = New ErrorTypeSymbol()
''' <summary>
''' This symbol is used as a sentinel while we are binding a lambda in error recovery mode.
''' </summary>
Friend Shared ReadOnly ErrorRecoveryInferenceError As TypeSymbol = New ErrorTypeSymbol()
Private ReadOnly _syntaxNode As SyntaxNode
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
''' <summary>
''' Can mutate for a query lambda from ReturnTypePendingDelegate
''' to the return type of the target delegate.
''' </summary>
Protected m_ReturnType As TypeSymbol
' The binder associated with the block containing this lambda
Private ReadOnly _binder As Binder
Protected Sub New(
syntaxNode As SyntaxNode,
parameters As ImmutableArray(Of BoundLambdaParameterSymbol),
returnType As TypeSymbol,
binder As Binder
)
Debug.Assert(syntaxNode IsNot Nothing)
Debug.Assert(returnType IsNot Nothing)
_syntaxNode = syntaxNode
_parameters = StaticCast(Of ParameterSymbol).From(parameters)
m_ReturnType = returnType
_binder = binder
For Each param In parameters
param.SetLambdaSymbol(Me)
Next
End Sub
Public MustOverride ReadOnly Property SynthesizedKind As SynthesizedLambdaKind
Friend NotOverridable Overrides ReadOnly Property IsQueryLambdaMethod As Boolean
Get
Return SynthesizedKind.IsQueryLambda
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return 0
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
Return ImmutableArray(Of String).Empty
End Function
Public Overrides ReadOnly Property AssociatedSymbol As Symbol
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention
Get
Return Cci.CallingConvention.Default
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _binder.ContainingMember
End Get
End Property
Friend ReadOnly Property ContainingBinder As Binder
Get
Return _binder
End Get
End Property
''' <summary>
''' "Me" parameter for this lambda will be that of the containing symbol
''' </summary>
Friend Overrides Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean
Debug.Assert(ContainingSymbol IsNot Nothing)
Select Case ContainingSymbol.Kind
Case SymbolKind.Field
meParameter = DirectCast(ContainingSymbol, FieldSymbol).MeParameter
Case SymbolKind.Property
meParameter = DirectCast(ContainingSymbol, PropertySymbol).MeParameter
Case SymbolKind.Method
meParameter = DirectCast(ContainingSymbol, MethodSymbol).MeParameter
Case Else
meParameter = Nothing
End Select
Return True
End Function
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.Private
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)
Get
Return ImmutableArray(Of MethodSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsExternalMethod As Boolean
Get
Return False
End Get
End Property
Public Overrides Function GetDllImportData() As DllImportData
Return Nothing
End Function
Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes
Get
Return Nothing
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property HasDeclarativeSecurity As Boolean
Get
Return False
End Get
End Property
Friend NotOverridable Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute)
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverloads As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Dim container As Symbol = ContainingSymbol
Select Case container.Kind
Case SymbolKind.Field, SymbolKind.Property, SymbolKind.Method
Return container.IsShared
Case Else
Return True
End Select
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return m_ReturnType.IsVoidType()
End Get
End Property
Public Overrides ReadOnly Property IsVararg As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsInitOnly As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray.Create(_syntaxNode.GetLocation())
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray.Create(_syntaxNode.GetReference())
End Get
End Property
Friend Overrides ReadOnly Property IsLambdaMethod As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property MethodKind As MethodKind
Get
Return MethodKind.LambdaMethod
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _parameters
End Get
End Property
Public Overrides ReadOnly Property ReturnsByRef As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return m_ReturnType
End Get
End Property
Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return ImmutableArray(Of CustomModifier).Empty
End Get
End Property
Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return ImmutableArray(Of CustomModifier).Empty
End Get
End Property
Friend Overrides ReadOnly Property Syntax As SyntaxNode
Get
Return _syntaxNode
End Get
End Property
Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol)
Get
Return ImmutableArray(Of TypeSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean
Return False
End Function
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
' lambdas contain user code
Return True
End Get
End Property
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Me Then
Return True
End If
Dim symbol = TryCast(obj, LambdaSymbol)
Return symbol IsNot Nothing AndAlso
symbol._syntaxNode Is Me._syntaxNode AndAlso
Equals(symbol.ContainingSymbol, Me.ContainingSymbol) AndAlso
MethodSignatureComparer.AllAspectsSignatureComparer.Equals(symbol, Me)
End Function
Public Overrides Function GetHashCode() As Integer
Dim hc As Integer = Hash.Combine(Me.Syntax.GetHashCode(), Me._parameters.Length)
hc = Hash.Combine(hc, Me.ReturnType.GetHashCode())
For i = 0 To Me._parameters.Length - 1
hc = Hash.Combine(hc, Me._parameters(i).Type.GetHashCode())
Next
Return hc
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/EditorFeatures/Core/GoToDefinition/WellKnownSymbolTypes.cs | // 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.
#nullable disable
namespace Microsoft.CodeAnalysis.Editor.GoToDefinition
{
internal class WellKnownSymbolTypes
{
public const string Definition = nameof(Definition);
}
}
| // 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.
#nullable disable
namespace Microsoft.CodeAnalysis.Editor.GoToDefinition
{
internal class WellKnownSymbolTypes
{
public const string Definition = nameof(Definition);
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/EditorFeatures/VisualBasic/Utilities/CommandHandlers/AbstractImplementAbstractClassOrInterfaceCommandHandler.vb | ' 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.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Implementation.EndConstructGeneration
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Text.Shared.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.Commanding
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Imports Microsoft.VisualStudio.Text.Operations
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities.CommandHandlers
Friend MustInherit Class AbstractImplementAbstractClassOrInterfaceCommandHandler
Implements ICommandHandler(Of ReturnKeyCommandArgs)
Private ReadOnly _editorOperationsFactoryService As IEditorOperationsFactoryService
Public ReadOnly Property DisplayName As String Implements INamed.DisplayName
Get
Return VBEditorResources.Implement_Abstract_Class_Or_Interface
End Get
End Property
Protected Sub New(editorOperationsFactoryService As IEditorOperationsFactoryService)
_editorOperationsFactoryService = editorOperationsFactoryService
End Sub
Protected MustOverride Overloads Function TryGetNewDocument(
document As Document,
typeSyntax As TypeSyntax,
cancellationToken As CancellationToken) As Document
Private Function ExecuteCommand(args As ReturnKeyCommandArgs, context As CommandExecutionContext) As Boolean Implements ICommandHandler(Of ReturnKeyCommandArgs).ExecuteCommand
Dim caretPointOpt = args.TextView.GetCaretPoint(args.SubjectBuffer)
If caretPointOpt Is Nothing Then
Return False
End If
' Implement interface is not cancellable.
Dim _cancellationToken = CancellationToken.None
If Not TryExecute(args, _cancellationToken) Then
Return False
End If
' It's possible that there may be an end construct to generate at this position.
' We'll go ahead and generate it before determining whether we need to move the caret
TryGenerateEndConstruct(args, _cancellationToken)
Dim snapshot = args.SubjectBuffer.CurrentSnapshot
Dim caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer).Value
Dim caretLine = snapshot.GetLineFromPosition(caretPosition)
' If there is any text after the caret on the same line, we'll pass through to
' insert a new line.
Dim lastNonWhitespacePosition = If(caretLine.GetLastNonWhitespacePosition(), -1)
If lastNonWhitespacePosition > caretPosition.Position Then
Return False
End If
Dim nextLine = snapshot.GetLineFromLineNumber(caretLine.LineNumber + 1)
If Not nextLine.IsEmptyOrWhitespace() Then
' If the next line is not whitespace, we'll go ahead and pass through to insert a new line.
Return False
End If
' If the next line *is* whitespace, we're just going to move the caret down a line.
_editorOperationsFactoryService.GetEditorOperations(args.TextView).MoveLineDown(extendSelection:=False)
Return True
End Function
Private Shared Function TryGenerateEndConstruct(args As ReturnKeyCommandArgs, cancellationToken As CancellationToken) As Boolean
Dim textSnapshot = args.SubjectBuffer.CurrentSnapshot
Dim document = textSnapshot.GetOpenDocumentInCurrentContextWithChanges()
If document Is Nothing Then
Return False
End If
Dim caretPointOpt = args.TextView.GetCaretPoint(args.SubjectBuffer)
If caretPointOpt Is Nothing Then
Return False
End If
Dim caretPosition = caretPointOpt.Value.Position
If caretPosition = 0 Then
Return False
End If
Dim endConstructGenerationService = document.GetLanguageService(Of IEndConstructGenerationService)()
Return endConstructGenerationService.TryDo(args.TextView, args.SubjectBuffer, vbLf(0), cancellationToken)
End Function
Private Overloads Function TryExecute(args As ReturnKeyCommandArgs, cancellationToken As CancellationToken) As Boolean
Dim textSnapshot = args.SubjectBuffer.CurrentSnapshot
Dim text = textSnapshot.AsText()
Dim document = textSnapshot.GetOpenDocumentInCurrentContextWithChanges()
If document Is Nothing Then
Return False
End If
If Not args.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers) Then
Return False
End If
Dim caretPointOpt = args.TextView.GetCaretPoint(args.SubjectBuffer)
If caretPointOpt Is Nothing Then
Return False
End If
Dim caretPosition = caretPointOpt.Value.Position
If caretPosition = 0 Then
Return False
End If
Dim syntaxRoot = document.GetSyntaxRootSynchronously(cancellationToken)
Dim token = syntaxRoot.FindTokenOnLeftOfPosition(caretPosition)
If text.Lines.IndexOf(token.SpanStart) <> text.Lines.IndexOf(caretPosition) Then
Return False
End If
Dim statement = token.GetAncestor(Of InheritsOrImplementsStatementSyntax)()
If statement Is Nothing Then
Return False
End If
If statement.Span.End <> token.Span.End Then
Return False
End If
' We need to track this token into the resulting buffer so we know what to do with the cursor
' from there
Dim caretOffsetFromToken = caretPosition - token.Span.End
Dim tokenAnnotation As New SyntaxAnnotation()
document = document.WithSyntaxRoot(syntaxRoot.ReplaceToken(token, token.WithAdditionalAnnotations(tokenAnnotation)))
token = document.GetSyntaxRootSynchronously(cancellationToken).
GetAnnotatedNodesAndTokens(tokenAnnotation).First().AsToken()
Dim typeSyntax = token.GetAncestor(Of TypeSyntax)()
If typeSyntax Is Nothing Then
Return False
End If
' get top most identifier
Dim identifier = DirectCast(typeSyntax.AncestorsAndSelf(ascendOutOfTrivia:=False).Where(Function(t) TypeOf t Is TypeSyntax).LastOrDefault(), TypeSyntax)
If identifier Is Nothing Then
Return False
End If
Dim newDocument = TryGetNewDocument(document, identifier, cancellationToken)
If newDocument Is Nothing Then
Return False
End If
newDocument = Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, Nothing, cancellationToken).WaitAndGetResult(cancellationToken)
newDocument = Formatter.FormatAsync(newDocument, Formatter.Annotation, cancellationToken:=cancellationToken).WaitAndGetResult(cancellationToken)
newDocument.Project.Solution.Workspace.ApplyDocumentChanges(newDocument, cancellationToken)
' Place the cursor back to where it logically was after this
token = newDocument.GetSyntaxRootSynchronously(cancellationToken).
GetAnnotatedNodesAndTokens(tokenAnnotation).First().AsToken()
args.TextView.TryMoveCaretToAndEnsureVisible(
New SnapshotPoint(args.SubjectBuffer.CurrentSnapshot,
Math.Min(token.Span.End + caretOffsetFromToken, args.SubjectBuffer.CurrentSnapshot.Length)))
Return True
End Function
Private Function GetCommandState(args As ReturnKeyCommandArgs) As CommandState Implements ICommandHandler(Of ReturnKeyCommandArgs).GetCommandState
Return CommandState.Unspecified
End Function
End Class
End Namespace
| ' 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.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Implementation.EndConstructGeneration
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Text.Shared.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.Commanding
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Imports Microsoft.VisualStudio.Text.Operations
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities.CommandHandlers
Friend MustInherit Class AbstractImplementAbstractClassOrInterfaceCommandHandler
Implements ICommandHandler(Of ReturnKeyCommandArgs)
Private ReadOnly _editorOperationsFactoryService As IEditorOperationsFactoryService
Public ReadOnly Property DisplayName As String Implements INamed.DisplayName
Get
Return VBEditorResources.Implement_Abstract_Class_Or_Interface
End Get
End Property
Protected Sub New(editorOperationsFactoryService As IEditorOperationsFactoryService)
_editorOperationsFactoryService = editorOperationsFactoryService
End Sub
Protected MustOverride Overloads Function TryGetNewDocument(
document As Document,
typeSyntax As TypeSyntax,
cancellationToken As CancellationToken) As Document
Private Function ExecuteCommand(args As ReturnKeyCommandArgs, context As CommandExecutionContext) As Boolean Implements ICommandHandler(Of ReturnKeyCommandArgs).ExecuteCommand
Dim caretPointOpt = args.TextView.GetCaretPoint(args.SubjectBuffer)
If caretPointOpt Is Nothing Then
Return False
End If
' Implement interface is not cancellable.
Dim _cancellationToken = CancellationToken.None
If Not TryExecute(args, _cancellationToken) Then
Return False
End If
' It's possible that there may be an end construct to generate at this position.
' We'll go ahead and generate it before determining whether we need to move the caret
TryGenerateEndConstruct(args, _cancellationToken)
Dim snapshot = args.SubjectBuffer.CurrentSnapshot
Dim caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer).Value
Dim caretLine = snapshot.GetLineFromPosition(caretPosition)
' If there is any text after the caret on the same line, we'll pass through to
' insert a new line.
Dim lastNonWhitespacePosition = If(caretLine.GetLastNonWhitespacePosition(), -1)
If lastNonWhitespacePosition > caretPosition.Position Then
Return False
End If
Dim nextLine = snapshot.GetLineFromLineNumber(caretLine.LineNumber + 1)
If Not nextLine.IsEmptyOrWhitespace() Then
' If the next line is not whitespace, we'll go ahead and pass through to insert a new line.
Return False
End If
' If the next line *is* whitespace, we're just going to move the caret down a line.
_editorOperationsFactoryService.GetEditorOperations(args.TextView).MoveLineDown(extendSelection:=False)
Return True
End Function
Private Shared Function TryGenerateEndConstruct(args As ReturnKeyCommandArgs, cancellationToken As CancellationToken) As Boolean
Dim textSnapshot = args.SubjectBuffer.CurrentSnapshot
Dim document = textSnapshot.GetOpenDocumentInCurrentContextWithChanges()
If document Is Nothing Then
Return False
End If
Dim caretPointOpt = args.TextView.GetCaretPoint(args.SubjectBuffer)
If caretPointOpt Is Nothing Then
Return False
End If
Dim caretPosition = caretPointOpt.Value.Position
If caretPosition = 0 Then
Return False
End If
Dim endConstructGenerationService = document.GetLanguageService(Of IEndConstructGenerationService)()
Return endConstructGenerationService.TryDo(args.TextView, args.SubjectBuffer, vbLf(0), cancellationToken)
End Function
Private Overloads Function TryExecute(args As ReturnKeyCommandArgs, cancellationToken As CancellationToken) As Boolean
Dim textSnapshot = args.SubjectBuffer.CurrentSnapshot
Dim text = textSnapshot.AsText()
Dim document = textSnapshot.GetOpenDocumentInCurrentContextWithChanges()
If document Is Nothing Then
Return False
End If
If Not args.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers) Then
Return False
End If
Dim caretPointOpt = args.TextView.GetCaretPoint(args.SubjectBuffer)
If caretPointOpt Is Nothing Then
Return False
End If
Dim caretPosition = caretPointOpt.Value.Position
If caretPosition = 0 Then
Return False
End If
Dim syntaxRoot = document.GetSyntaxRootSynchronously(cancellationToken)
Dim token = syntaxRoot.FindTokenOnLeftOfPosition(caretPosition)
If text.Lines.IndexOf(token.SpanStart) <> text.Lines.IndexOf(caretPosition) Then
Return False
End If
Dim statement = token.GetAncestor(Of InheritsOrImplementsStatementSyntax)()
If statement Is Nothing Then
Return False
End If
If statement.Span.End <> token.Span.End Then
Return False
End If
' We need to track this token into the resulting buffer so we know what to do with the cursor
' from there
Dim caretOffsetFromToken = caretPosition - token.Span.End
Dim tokenAnnotation As New SyntaxAnnotation()
document = document.WithSyntaxRoot(syntaxRoot.ReplaceToken(token, token.WithAdditionalAnnotations(tokenAnnotation)))
token = document.GetSyntaxRootSynchronously(cancellationToken).
GetAnnotatedNodesAndTokens(tokenAnnotation).First().AsToken()
Dim typeSyntax = token.GetAncestor(Of TypeSyntax)()
If typeSyntax Is Nothing Then
Return False
End If
' get top most identifier
Dim identifier = DirectCast(typeSyntax.AncestorsAndSelf(ascendOutOfTrivia:=False).Where(Function(t) TypeOf t Is TypeSyntax).LastOrDefault(), TypeSyntax)
If identifier Is Nothing Then
Return False
End If
Dim newDocument = TryGetNewDocument(document, identifier, cancellationToken)
If newDocument Is Nothing Then
Return False
End If
newDocument = Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, Nothing, cancellationToken).WaitAndGetResult(cancellationToken)
newDocument = Formatter.FormatAsync(newDocument, Formatter.Annotation, cancellationToken:=cancellationToken).WaitAndGetResult(cancellationToken)
newDocument.Project.Solution.Workspace.ApplyDocumentChanges(newDocument, cancellationToken)
' Place the cursor back to where it logically was after this
token = newDocument.GetSyntaxRootSynchronously(cancellationToken).
GetAnnotatedNodesAndTokens(tokenAnnotation).First().AsToken()
args.TextView.TryMoveCaretToAndEnsureVisible(
New SnapshotPoint(args.SubjectBuffer.CurrentSnapshot,
Math.Min(token.Span.End + caretOffsetFromToken, args.SubjectBuffer.CurrentSnapshot.Length)))
Return True
End Function
Private Function GetCommandState(args As ReturnKeyCommandArgs) As CommandState Implements ICommandHandler(Of ReturnKeyCommandArgs).GetCommandState
Return CommandState.Unspecified
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/Core/CodeAnalysisTest/Collections/ImmutableSegmentedListBuilderTest.cs | // 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.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://raw.githubusercontent.com/dotnet/runtime/v6.0.0-preview.5.21301.5/src/libraries/System.Collections.Immutable/tests/ImmutableListBuilderTest.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Collections;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
public class ImmutableSegmentedListBuilderTest : ImmutableListTestBase
{
[Fact]
public void CreateBuilder()
{
ImmutableSegmentedList<string>.Builder builder = ImmutableSegmentedList.CreateBuilder<string>();
Assert.NotNull(builder);
}
[Fact]
public void ToBuilder()
{
var builder = ImmutableSegmentedList<int>.Empty.ToBuilder();
builder.Add(3);
builder.Add(5);
builder.Add(5);
Assert.Equal(3, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var list = builder.ToImmutable();
Assert.Equal(builder.Count, list.Count);
builder.Add(8);
Assert.Equal(4, builder.Count);
Assert.Equal(3, list.Count);
Assert.True(builder.Contains(8));
Assert.False(list.Contains(8));
}
[Fact]
public void BuilderFromList()
{
var list = ImmutableSegmentedList<int>.Empty.Add(1);
var builder = list.ToBuilder();
Assert.True(builder.Contains(1));
builder.Add(3);
builder.Add(5);
builder.Add(5);
Assert.Equal(4, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var list2 = builder.ToImmutable();
Assert.Equal(builder.Count, list2.Count);
Assert.True(list2.Contains(1));
builder.Add(8);
Assert.Equal(5, builder.Count);
Assert.Equal(4, list2.Count);
Assert.True(builder.Contains(8));
Assert.False(list.Contains(8));
Assert.False(list2.Contains(8));
}
[Fact]
public void SeveralChanges()
{
var mutable = ImmutableSegmentedList<int>.Empty.ToBuilder();
var immutable1 = mutable.ToImmutable();
Assert.True(IsSame(immutable1, mutable.ToImmutable())); //, "The Immutable property getter is creating new objects without any differences.");
mutable.Add(1);
var immutable2 = mutable.ToImmutable();
Assert.False(IsSame(immutable1, immutable2)); //, "Mutating the collection did not reset the Immutable property.");
Assert.True(IsSame(immutable2, mutable.ToImmutable())); //, "The Immutable property getter is creating new objects without any differences.");
Assert.Equal(1, immutable2.Count);
}
[Fact]
public void EnumerateBuilderWhileMutating()
{
var builder = ImmutableSegmentedList<int>.Empty.AddRange(Enumerable.Range(1, 10)).ToBuilder();
Assert.Equal(Enumerable.Range(1, 10), builder);
var enumerator = builder.GetEnumerator();
Assert.True(enumerator.MoveNext());
builder.Add(11);
// Verify that a new enumerator will succeed.
Assert.Equal(Enumerable.Range(1, 11), builder);
// Try enumerating further with the previous enumerable now that we've changed the collection.
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
enumerator.Reset();
enumerator.MoveNext(); // resetting should fix the problem.
// Verify that by obtaining a new enumerator, we can enumerate all the contents.
Assert.Equal(Enumerable.Range(1, 11), builder);
}
[Fact]
public void BuilderReusesUnchangedImmutableInstances()
{
var collection = ImmutableSegmentedList<int>.Empty.Add(1);
var builder = collection.ToBuilder();
Assert.True(collection == builder.ToImmutable()); // no changes at all.
builder.Add(2);
var newImmutable = builder.ToImmutable();
Assert.False(IsSame(collection, newImmutable)); // first ToImmutable with changes should be a new instance.
Assert.True(IsSame(newImmutable, builder.ToImmutable())); // second ToImmutable without changes should be the same instance.
}
[Fact]
public void Insert()
{
var mutable = ImmutableSegmentedList<int>.Empty.ToBuilder();
mutable.Insert(0, 1);
mutable.Insert(0, 0);
mutable.Insert(2, 3);
Assert.Equal(new[] { 0, 1, 3 }, mutable);
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable.Insert(-1, 0));
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable.Insert(4, 0));
}
[Fact]
public void InsertRange()
{
var mutable = ImmutableSegmentedList<int>.Empty.ToBuilder();
mutable.InsertRange(0, new[] { 1, 4, 5 });
Assert.Equal(new[] { 1, 4, 5 }, mutable);
mutable.InsertRange(1, new[] { 2, 3 });
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, mutable);
mutable.InsertRange(5, new[] { 6 });
Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable);
mutable.InsertRange(5, new int[0]);
Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable);
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(-1, new int[0]));
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(mutable.Count + 1, new int[0]));
}
[Fact]
public void AddRange()
{
var mutable = ImmutableSegmentedList<int>.Empty.ToBuilder();
mutable.AddRange(new[] { 1, 4, 5 });
Assert.Equal(new[] { 1, 4, 5 }, mutable);
mutable.AddRange(new[] { 2, 3 });
Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable);
mutable.AddRange(new int[0]);
Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable);
Assert.Throws<ArgumentNullException>("items", () => mutable.AddRange(null!));
}
[Fact]
public void Remove()
{
var mutable = ImmutableSegmentedList<int>.Empty.ToBuilder();
Assert.False(mutable.Remove(5));
mutable.Add(1);
mutable.Add(2);
mutable.Add(3);
Assert.True(mutable.Remove(2));
Assert.Equal(new[] { 1, 3 }, mutable);
Assert.True(mutable.Remove(1));
Assert.Equal(new[] { 3 }, mutable);
Assert.True(mutable.Remove(3));
Assert.Equal(new int[0], mutable);
Assert.False(mutable.Remove(5));
}
[Fact]
public void RemoveAllBugTest()
{
var builder = ImmutableSegmentedList.CreateBuilder<int>();
var elemsToRemove = new HashSet<int>() { 0, 1, 2, 3, 4, 5 };
// NOTE: this uses Add instead of AddRange because AddRange doesn't exhibit the same issue due to a different order of tree building.
// Don't change it without testing with the bug repro from https://github.com/dotnet/runtime/issues/22093.
foreach (var elem in new[] { 0, 1, 2, 3, 4, 5, 6 })
builder.Add(elem);
builder.RemoveAll(elemsToRemove.Contains);
Assert.Equal(new[] { 6 }, builder);
}
[Fact]
public void RemoveAt()
{
var mutable = ImmutableSegmentedList<int>.Empty.ToBuilder();
mutable.Add(1);
mutable.Add(2);
mutable.Add(3);
mutable.RemoveAt(2);
Assert.Equal(new[] { 1, 2 }, mutable);
mutable.RemoveAt(0);
Assert.Equal(new[] { 2 }, mutable);
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(1));
mutable.RemoveAt(0);
Assert.Equal(new int[0], mutable);
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(0));
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(1));
}
[Fact]
public void Reverse()
{
var mutable = ImmutableSegmentedList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
mutable.Reverse();
Assert.Equal(Enumerable.Range(1, 3).Reverse(), mutable);
}
[Fact]
public void Clear()
{
var mutable = ImmutableSegmentedList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
mutable.Clear();
Assert.Equal(0, mutable.Count);
// Do it again for good measure. :)
mutable.Clear();
Assert.Equal(0, mutable.Count);
}
[Fact]
public void IsReadOnly()
{
ICollection<int> builder = ImmutableSegmentedList.Create<int>().ToBuilder();
Assert.False(builder.IsReadOnly);
}
[Fact]
public void Indexer()
{
var mutable = ImmutableSegmentedList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Equal(2, mutable[1]);
mutable[1] = 5;
Assert.Equal(5, mutable[1]);
mutable[0] = -2;
mutable[2] = -3;
Assert.Equal(new[] { -2, 5, -3 }, mutable);
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable[3] = 4);
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable[-1] = 4);
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable[3]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable[-1]);
}
[Fact]
public void IndexOf()
{
IndexOfTests.IndexOfTest(
seq => ImmutableSegmentedList.CreateRange(seq).ToBuilder(),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
}
[Fact]
public void LastIndexOf()
{
IndexOfTests.LastIndexOfTest(
seq => ImmutableSegmentedList.CreateRange(seq).ToBuilder(),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, b.Count > 0 ? b.Count - 1 : 0, b.Count, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
}
[Fact]
public void GetEnumeratorExplicit()
{
ICollection<int> builder = ImmutableSegmentedList.Create<int>().ToBuilder();
var enumerator = builder.GetEnumerator();
Assert.NotNull(enumerator);
}
[Fact]
public void IsSynchronized()
{
ICollection collection = ImmutableSegmentedList.Create<int>().ToBuilder();
Assert.False(collection.IsSynchronized);
}
[Fact]
public void IListMembers()
{
IList list = ImmutableSegmentedList.Create<int>().ToBuilder();
Assert.False(list.IsReadOnly);
Assert.False(list.IsFixedSize);
Assert.Equal(0, list.Add(5));
Assert.Equal(1, list.Add(8));
Assert.True(list.Contains(5));
Assert.False(list.Contains(7));
list.Insert(1, 6);
Assert.Equal(6, list[1]);
list.Remove(5);
list[0] = 9;
Assert.Equal(new[] { 9, 8 }, list.Cast<int>().ToArray());
list.Clear();
Assert.Equal(0, list.Count);
}
[Fact]
public void IList_Remove_NullArgument()
{
this.AssertIListBaseline(RemoveFunc, 1, null);
this.AssertIListBaseline(RemoveFunc, "item", null);
this.AssertIListBaseline(RemoveFunc, new int?(1), null);
this.AssertIListBaseline(RemoveFunc, new int?(), null);
}
[Fact]
public void IList_Remove_ArgTypeMismatch()
{
this.AssertIListBaseline(RemoveFunc, "first item", new object());
this.AssertIListBaseline(RemoveFunc, 1, 1.0);
this.AssertIListBaseline(RemoveFunc, new int?(1), 1);
this.AssertIListBaseline(RemoveFunc, new int?(1), new int?(1));
this.AssertIListBaseline(RemoveFunc, new int?(1), string.Empty);
}
[Fact]
public void IList_Remove_EqualsOverride()
{
this.AssertIListBaseline(RemoveFunc, new ProgrammaticEquals(v => v is string), "foo");
this.AssertIListBaseline(RemoveFunc, new ProgrammaticEquals(v => v is string), 3);
}
[Fact(Skip = "Not implemented: https://github.com/dotnet/roslyn/issues/54429")]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSegmentedList.CreateBuilder<int>());
ImmutableSegmentedList<string>.Builder builder = ImmutableSegmentedList.CreateBuilder<string>();
builder.Add("One");
builder.Add("Two");
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(builder);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>()!.State == DebuggerBrowsableState.RootHidden);
string[]? items = itemProperty.GetValue(info.Instance) as string[];
Assert.Equal(builder, items);
}
[Fact(Skip = "Not implemented: https://github.com/dotnet/roslyn/issues/54429")]
public static void TestDebuggerAttributes_Null()
{
Type proxyType = DebuggerAttributes.GetProxyType(ImmutableSegmentedList.CreateBuilder<string>());
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null!));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
[Fact]
public void ItemRef()
{
var list = new[] { 1, 2, 3 }.ToImmutableSegmentedList();
var builder = new ImmutableSegmentedList<int>.Builder(list);
ref readonly var safeRef = ref builder.ItemRef(1);
ref var unsafeRef = ref Unsafe.AsRef(safeRef);
Assert.Equal(2, builder.ItemRef(1));
unsafeRef = 4;
Assert.Equal(4, builder.ItemRef(1));
}
[Fact]
public void ItemRef_OutOfBounds()
{
var list = new[] { 1, 2, 3 }.ToImmutableSegmentedList();
var builder = new ImmutableSegmentedList<int>.Builder(list);
Assert.Throws<ArgumentOutOfRangeException>(() => builder.ItemRef(5));
}
[Fact]
public void ToImmutableList()
{
ImmutableSegmentedList<int>.Builder builder = ImmutableSegmentedList.CreateBuilder<int>();
builder.Add(0);
builder.Add(1);
builder.Add(2);
var list = builder.ToImmutableSegmentedList();
Assert.Equal(0, builder[0]);
Assert.Equal(1, builder[1]);
Assert.Equal(2, builder[2]);
builder[1] = 5;
Assert.Equal(5, builder[1]);
Assert.Equal(1, list[1]);
builder.Clear();
Assert.True(builder.ToImmutableSegmentedList().IsEmpty);
Assert.False(list.IsEmpty);
ImmutableSegmentedList<int>.Builder? nullBuilder = null;
Assert.Throws<ArgumentNullException>("builder", () => nullBuilder!.ToImmutableSegmentedList());
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
return ImmutableSegmentedList<T>.Empty.AddRange(contents).ToBuilder();
}
private protected override void RemoveAllTestHelper<T>(ImmutableSegmentedList<T> list, Predicate<T> test)
{
var builder = list.ToBuilder();
var bcl = list.ToList();
int expected = bcl.RemoveAll(test);
var actual = builder.RemoveAll(test);
Assert.Equal(expected, actual);
Assert.Equal<T>(bcl, builder.ToList());
}
private protected override void ReverseTestHelper<T>(ImmutableSegmentedList<T> list, int index, int count)
{
var expected = list.ToList();
expected.Reverse(index, count);
var builder = list.ToBuilder();
builder.Reverse(index, count);
Assert.Equal<T>(expected, builder.ToList());
}
internal override IReadOnlyList<T> GetListQuery<T>(ImmutableSegmentedList<T> list)
{
return list.ToBuilder();
}
private protected override ImmutableSegmentedList<TOutput> ConvertAllImpl<T, TOutput>(ImmutableSegmentedList<T> list, Converter<T, TOutput> converter)
=> list.ToBuilder().ConvertAll(converter);
private protected override void ForEachImpl<T>(ImmutableSegmentedList<T> list, Action<T> action)
=> list.ToBuilder().ForEach(action);
private protected override ImmutableSegmentedList<T> GetRangeImpl<T>(ImmutableSegmentedList<T> list, int index, int count)
=> list.ToBuilder().GetRange(index, count);
private protected override void CopyToImpl<T>(ImmutableSegmentedList<T> list, T[] array)
=> list.ToBuilder().CopyTo(array);
private protected override void CopyToImpl<T>(ImmutableSegmentedList<T> list, T[] array, int arrayIndex)
=> list.ToBuilder().CopyTo(array, arrayIndex);
private protected override void CopyToImpl<T>(ImmutableSegmentedList<T> list, int index, T[] array, int arrayIndex, int count)
=> list.ToBuilder().CopyTo(index, array, arrayIndex, count);
private protected override bool ExistsImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.ToBuilder().Exists(match);
private protected override T? FindImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
where T : default
=> list.ToBuilder().Find(match);
private protected override ImmutableSegmentedList<T> FindAllImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.ToBuilder().FindAll(match);
private protected override int FindIndexImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.ToBuilder().FindIndex(match);
private protected override int FindIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, Predicate<T> match)
=> list.ToBuilder().FindIndex(startIndex, match);
private protected override int FindIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, int count, Predicate<T> match)
=> list.ToBuilder().FindIndex(startIndex, count, match);
private protected override T? FindLastImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
where T : default
=> list.ToBuilder().FindLast(match);
private protected override int FindLastIndexImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.ToBuilder().FindLastIndex(match);
private protected override int FindLastIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, Predicate<T> match)
=> list.ToBuilder().FindLastIndex(startIndex, match);
private protected override int FindLastIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, int count, Predicate<T> match)
=> list.ToBuilder().FindLastIndex(startIndex, count, match);
private protected override bool TrueForAllImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> test)
=> list.ToBuilder().TrueForAll(test);
private protected override int BinarySearchImpl<T>(ImmutableSegmentedList<T> list, T item)
=> list.ToBuilder().BinarySearch(item);
private protected override int BinarySearchImpl<T>(ImmutableSegmentedList<T> list, T item, IComparer<T>? comparer)
=> list.ToBuilder().BinarySearch(item, comparer);
private protected override int BinarySearchImpl<T>(ImmutableSegmentedList<T> list, int index, int count, T item, IComparer<T>? comparer)
=> list.ToBuilder().BinarySearch(index, count, item, comparer);
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list)
{
var builder = list.ToBuilder();
builder.Sort();
return builder.ToImmutable().ToList();
}
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list, Comparison<T> comparison)
{
var builder = list.ToBuilder();
builder.Sort(comparison);
return builder.ToImmutable().ToList();
}
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list, IComparer<T>? comparer)
{
var builder = list.ToBuilder();
builder.Sort(comparer);
return builder.ToImmutable().ToList();
}
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list, int index, int count, IComparer<T>? comparer)
{
var builder = list.ToBuilder();
builder.Sort(index, count, comparer);
return builder.ToImmutable().ToList();
}
}
}
| // 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.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://raw.githubusercontent.com/dotnet/runtime/v6.0.0-preview.5.21301.5/src/libraries/System.Collections.Immutable/tests/ImmutableListBuilderTest.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Collections;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
public class ImmutableSegmentedListBuilderTest : ImmutableListTestBase
{
[Fact]
public void CreateBuilder()
{
ImmutableSegmentedList<string>.Builder builder = ImmutableSegmentedList.CreateBuilder<string>();
Assert.NotNull(builder);
}
[Fact]
public void ToBuilder()
{
var builder = ImmutableSegmentedList<int>.Empty.ToBuilder();
builder.Add(3);
builder.Add(5);
builder.Add(5);
Assert.Equal(3, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var list = builder.ToImmutable();
Assert.Equal(builder.Count, list.Count);
builder.Add(8);
Assert.Equal(4, builder.Count);
Assert.Equal(3, list.Count);
Assert.True(builder.Contains(8));
Assert.False(list.Contains(8));
}
[Fact]
public void BuilderFromList()
{
var list = ImmutableSegmentedList<int>.Empty.Add(1);
var builder = list.ToBuilder();
Assert.True(builder.Contains(1));
builder.Add(3);
builder.Add(5);
builder.Add(5);
Assert.Equal(4, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var list2 = builder.ToImmutable();
Assert.Equal(builder.Count, list2.Count);
Assert.True(list2.Contains(1));
builder.Add(8);
Assert.Equal(5, builder.Count);
Assert.Equal(4, list2.Count);
Assert.True(builder.Contains(8));
Assert.False(list.Contains(8));
Assert.False(list2.Contains(8));
}
[Fact]
public void SeveralChanges()
{
var mutable = ImmutableSegmentedList<int>.Empty.ToBuilder();
var immutable1 = mutable.ToImmutable();
Assert.True(IsSame(immutable1, mutable.ToImmutable())); //, "The Immutable property getter is creating new objects without any differences.");
mutable.Add(1);
var immutable2 = mutable.ToImmutable();
Assert.False(IsSame(immutable1, immutable2)); //, "Mutating the collection did not reset the Immutable property.");
Assert.True(IsSame(immutable2, mutable.ToImmutable())); //, "The Immutable property getter is creating new objects without any differences.");
Assert.Equal(1, immutable2.Count);
}
[Fact]
public void EnumerateBuilderWhileMutating()
{
var builder = ImmutableSegmentedList<int>.Empty.AddRange(Enumerable.Range(1, 10)).ToBuilder();
Assert.Equal(Enumerable.Range(1, 10), builder);
var enumerator = builder.GetEnumerator();
Assert.True(enumerator.MoveNext());
builder.Add(11);
// Verify that a new enumerator will succeed.
Assert.Equal(Enumerable.Range(1, 11), builder);
// Try enumerating further with the previous enumerable now that we've changed the collection.
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
enumerator.Reset();
enumerator.MoveNext(); // resetting should fix the problem.
// Verify that by obtaining a new enumerator, we can enumerate all the contents.
Assert.Equal(Enumerable.Range(1, 11), builder);
}
[Fact]
public void BuilderReusesUnchangedImmutableInstances()
{
var collection = ImmutableSegmentedList<int>.Empty.Add(1);
var builder = collection.ToBuilder();
Assert.True(collection == builder.ToImmutable()); // no changes at all.
builder.Add(2);
var newImmutable = builder.ToImmutable();
Assert.False(IsSame(collection, newImmutable)); // first ToImmutable with changes should be a new instance.
Assert.True(IsSame(newImmutable, builder.ToImmutable())); // second ToImmutable without changes should be the same instance.
}
[Fact]
public void Insert()
{
var mutable = ImmutableSegmentedList<int>.Empty.ToBuilder();
mutable.Insert(0, 1);
mutable.Insert(0, 0);
mutable.Insert(2, 3);
Assert.Equal(new[] { 0, 1, 3 }, mutable);
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable.Insert(-1, 0));
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable.Insert(4, 0));
}
[Fact]
public void InsertRange()
{
var mutable = ImmutableSegmentedList<int>.Empty.ToBuilder();
mutable.InsertRange(0, new[] { 1, 4, 5 });
Assert.Equal(new[] { 1, 4, 5 }, mutable);
mutable.InsertRange(1, new[] { 2, 3 });
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, mutable);
mutable.InsertRange(5, new[] { 6 });
Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable);
mutable.InsertRange(5, new int[0]);
Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable);
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(-1, new int[0]));
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(mutable.Count + 1, new int[0]));
}
[Fact]
public void AddRange()
{
var mutable = ImmutableSegmentedList<int>.Empty.ToBuilder();
mutable.AddRange(new[] { 1, 4, 5 });
Assert.Equal(new[] { 1, 4, 5 }, mutable);
mutable.AddRange(new[] { 2, 3 });
Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable);
mutable.AddRange(new int[0]);
Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable);
Assert.Throws<ArgumentNullException>("items", () => mutable.AddRange(null!));
}
[Fact]
public void Remove()
{
var mutable = ImmutableSegmentedList<int>.Empty.ToBuilder();
Assert.False(mutable.Remove(5));
mutable.Add(1);
mutable.Add(2);
mutable.Add(3);
Assert.True(mutable.Remove(2));
Assert.Equal(new[] { 1, 3 }, mutable);
Assert.True(mutable.Remove(1));
Assert.Equal(new[] { 3 }, mutable);
Assert.True(mutable.Remove(3));
Assert.Equal(new int[0], mutable);
Assert.False(mutable.Remove(5));
}
[Fact]
public void RemoveAllBugTest()
{
var builder = ImmutableSegmentedList.CreateBuilder<int>();
var elemsToRemove = new HashSet<int>() { 0, 1, 2, 3, 4, 5 };
// NOTE: this uses Add instead of AddRange because AddRange doesn't exhibit the same issue due to a different order of tree building.
// Don't change it without testing with the bug repro from https://github.com/dotnet/runtime/issues/22093.
foreach (var elem in new[] { 0, 1, 2, 3, 4, 5, 6 })
builder.Add(elem);
builder.RemoveAll(elemsToRemove.Contains);
Assert.Equal(new[] { 6 }, builder);
}
[Fact]
public void RemoveAt()
{
var mutable = ImmutableSegmentedList<int>.Empty.ToBuilder();
mutable.Add(1);
mutable.Add(2);
mutable.Add(3);
mutable.RemoveAt(2);
Assert.Equal(new[] { 1, 2 }, mutable);
mutable.RemoveAt(0);
Assert.Equal(new[] { 2 }, mutable);
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(1));
mutable.RemoveAt(0);
Assert.Equal(new int[0], mutable);
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(0));
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(1));
}
[Fact]
public void Reverse()
{
var mutable = ImmutableSegmentedList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
mutable.Reverse();
Assert.Equal(Enumerable.Range(1, 3).Reverse(), mutable);
}
[Fact]
public void Clear()
{
var mutable = ImmutableSegmentedList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
mutable.Clear();
Assert.Equal(0, mutable.Count);
// Do it again for good measure. :)
mutable.Clear();
Assert.Equal(0, mutable.Count);
}
[Fact]
public void IsReadOnly()
{
ICollection<int> builder = ImmutableSegmentedList.Create<int>().ToBuilder();
Assert.False(builder.IsReadOnly);
}
[Fact]
public void Indexer()
{
var mutable = ImmutableSegmentedList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Equal(2, mutable[1]);
mutable[1] = 5;
Assert.Equal(5, mutable[1]);
mutable[0] = -2;
mutable[2] = -3;
Assert.Equal(new[] { -2, 5, -3 }, mutable);
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable[3] = 4);
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable[-1] = 4);
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable[3]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => mutable[-1]);
}
[Fact]
public void IndexOf()
{
IndexOfTests.IndexOfTest(
seq => ImmutableSegmentedList.CreateRange(seq).ToBuilder(),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
}
[Fact]
public void LastIndexOf()
{
IndexOfTests.LastIndexOfTest(
seq => ImmutableSegmentedList.CreateRange(seq).ToBuilder(),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, b.Count > 0 ? b.Count - 1 : 0, b.Count, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
}
[Fact]
public void GetEnumeratorExplicit()
{
ICollection<int> builder = ImmutableSegmentedList.Create<int>().ToBuilder();
var enumerator = builder.GetEnumerator();
Assert.NotNull(enumerator);
}
[Fact]
public void IsSynchronized()
{
ICollection collection = ImmutableSegmentedList.Create<int>().ToBuilder();
Assert.False(collection.IsSynchronized);
}
[Fact]
public void IListMembers()
{
IList list = ImmutableSegmentedList.Create<int>().ToBuilder();
Assert.False(list.IsReadOnly);
Assert.False(list.IsFixedSize);
Assert.Equal(0, list.Add(5));
Assert.Equal(1, list.Add(8));
Assert.True(list.Contains(5));
Assert.False(list.Contains(7));
list.Insert(1, 6);
Assert.Equal(6, list[1]);
list.Remove(5);
list[0] = 9;
Assert.Equal(new[] { 9, 8 }, list.Cast<int>().ToArray());
list.Clear();
Assert.Equal(0, list.Count);
}
[Fact]
public void IList_Remove_NullArgument()
{
this.AssertIListBaseline(RemoveFunc, 1, null);
this.AssertIListBaseline(RemoveFunc, "item", null);
this.AssertIListBaseline(RemoveFunc, new int?(1), null);
this.AssertIListBaseline(RemoveFunc, new int?(), null);
}
[Fact]
public void IList_Remove_ArgTypeMismatch()
{
this.AssertIListBaseline(RemoveFunc, "first item", new object());
this.AssertIListBaseline(RemoveFunc, 1, 1.0);
this.AssertIListBaseline(RemoveFunc, new int?(1), 1);
this.AssertIListBaseline(RemoveFunc, new int?(1), new int?(1));
this.AssertIListBaseline(RemoveFunc, new int?(1), string.Empty);
}
[Fact]
public void IList_Remove_EqualsOverride()
{
this.AssertIListBaseline(RemoveFunc, new ProgrammaticEquals(v => v is string), "foo");
this.AssertIListBaseline(RemoveFunc, new ProgrammaticEquals(v => v is string), 3);
}
[Fact(Skip = "Not implemented: https://github.com/dotnet/roslyn/issues/54429")]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSegmentedList.CreateBuilder<int>());
ImmutableSegmentedList<string>.Builder builder = ImmutableSegmentedList.CreateBuilder<string>();
builder.Add("One");
builder.Add("Two");
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(builder);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>()!.State == DebuggerBrowsableState.RootHidden);
string[]? items = itemProperty.GetValue(info.Instance) as string[];
Assert.Equal(builder, items);
}
[Fact(Skip = "Not implemented: https://github.com/dotnet/roslyn/issues/54429")]
public static void TestDebuggerAttributes_Null()
{
Type proxyType = DebuggerAttributes.GetProxyType(ImmutableSegmentedList.CreateBuilder<string>());
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null!));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
[Fact]
public void ItemRef()
{
var list = new[] { 1, 2, 3 }.ToImmutableSegmentedList();
var builder = new ImmutableSegmentedList<int>.Builder(list);
ref readonly var safeRef = ref builder.ItemRef(1);
ref var unsafeRef = ref Unsafe.AsRef(safeRef);
Assert.Equal(2, builder.ItemRef(1));
unsafeRef = 4;
Assert.Equal(4, builder.ItemRef(1));
}
[Fact]
public void ItemRef_OutOfBounds()
{
var list = new[] { 1, 2, 3 }.ToImmutableSegmentedList();
var builder = new ImmutableSegmentedList<int>.Builder(list);
Assert.Throws<ArgumentOutOfRangeException>(() => builder.ItemRef(5));
}
[Fact]
public void ToImmutableList()
{
ImmutableSegmentedList<int>.Builder builder = ImmutableSegmentedList.CreateBuilder<int>();
builder.Add(0);
builder.Add(1);
builder.Add(2);
var list = builder.ToImmutableSegmentedList();
Assert.Equal(0, builder[0]);
Assert.Equal(1, builder[1]);
Assert.Equal(2, builder[2]);
builder[1] = 5;
Assert.Equal(5, builder[1]);
Assert.Equal(1, list[1]);
builder.Clear();
Assert.True(builder.ToImmutableSegmentedList().IsEmpty);
Assert.False(list.IsEmpty);
ImmutableSegmentedList<int>.Builder? nullBuilder = null;
Assert.Throws<ArgumentNullException>("builder", () => nullBuilder!.ToImmutableSegmentedList());
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
return ImmutableSegmentedList<T>.Empty.AddRange(contents).ToBuilder();
}
private protected override void RemoveAllTestHelper<T>(ImmutableSegmentedList<T> list, Predicate<T> test)
{
var builder = list.ToBuilder();
var bcl = list.ToList();
int expected = bcl.RemoveAll(test);
var actual = builder.RemoveAll(test);
Assert.Equal(expected, actual);
Assert.Equal<T>(bcl, builder.ToList());
}
private protected override void ReverseTestHelper<T>(ImmutableSegmentedList<T> list, int index, int count)
{
var expected = list.ToList();
expected.Reverse(index, count);
var builder = list.ToBuilder();
builder.Reverse(index, count);
Assert.Equal<T>(expected, builder.ToList());
}
internal override IReadOnlyList<T> GetListQuery<T>(ImmutableSegmentedList<T> list)
{
return list.ToBuilder();
}
private protected override ImmutableSegmentedList<TOutput> ConvertAllImpl<T, TOutput>(ImmutableSegmentedList<T> list, Converter<T, TOutput> converter)
=> list.ToBuilder().ConvertAll(converter);
private protected override void ForEachImpl<T>(ImmutableSegmentedList<T> list, Action<T> action)
=> list.ToBuilder().ForEach(action);
private protected override ImmutableSegmentedList<T> GetRangeImpl<T>(ImmutableSegmentedList<T> list, int index, int count)
=> list.ToBuilder().GetRange(index, count);
private protected override void CopyToImpl<T>(ImmutableSegmentedList<T> list, T[] array)
=> list.ToBuilder().CopyTo(array);
private protected override void CopyToImpl<T>(ImmutableSegmentedList<T> list, T[] array, int arrayIndex)
=> list.ToBuilder().CopyTo(array, arrayIndex);
private protected override void CopyToImpl<T>(ImmutableSegmentedList<T> list, int index, T[] array, int arrayIndex, int count)
=> list.ToBuilder().CopyTo(index, array, arrayIndex, count);
private protected override bool ExistsImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.ToBuilder().Exists(match);
private protected override T? FindImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
where T : default
=> list.ToBuilder().Find(match);
private protected override ImmutableSegmentedList<T> FindAllImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.ToBuilder().FindAll(match);
private protected override int FindIndexImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.ToBuilder().FindIndex(match);
private protected override int FindIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, Predicate<T> match)
=> list.ToBuilder().FindIndex(startIndex, match);
private protected override int FindIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, int count, Predicate<T> match)
=> list.ToBuilder().FindIndex(startIndex, count, match);
private protected override T? FindLastImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
where T : default
=> list.ToBuilder().FindLast(match);
private protected override int FindLastIndexImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.ToBuilder().FindLastIndex(match);
private protected override int FindLastIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, Predicate<T> match)
=> list.ToBuilder().FindLastIndex(startIndex, match);
private protected override int FindLastIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, int count, Predicate<T> match)
=> list.ToBuilder().FindLastIndex(startIndex, count, match);
private protected override bool TrueForAllImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> test)
=> list.ToBuilder().TrueForAll(test);
private protected override int BinarySearchImpl<T>(ImmutableSegmentedList<T> list, T item)
=> list.ToBuilder().BinarySearch(item);
private protected override int BinarySearchImpl<T>(ImmutableSegmentedList<T> list, T item, IComparer<T>? comparer)
=> list.ToBuilder().BinarySearch(item, comparer);
private protected override int BinarySearchImpl<T>(ImmutableSegmentedList<T> list, int index, int count, T item, IComparer<T>? comparer)
=> list.ToBuilder().BinarySearch(index, count, item, comparer);
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list)
{
var builder = list.ToBuilder();
builder.Sort();
return builder.ToImmutable().ToList();
}
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list, Comparison<T> comparison)
{
var builder = list.ToBuilder();
builder.Sort(comparison);
return builder.ToImmutable().ToList();
}
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list, IComparer<T>? comparer)
{
var builder = list.ToBuilder();
builder.Sort(comparer);
return builder.ToImmutable().ToList();
}
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list, int index, int count, IComparer<T>? comparer)
{
var builder = list.ToBuilder();
builder.Sort(index, count, comparer);
return builder.ToImmutable().ToList();
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/ItemManager.cs | // 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.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.PatternMatching;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem;
using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion
{
internal class ItemManager : IAsyncCompletionItemManager
{
/// <summary>
/// Used for filtering non-Roslyn data only.
/// </summary>
private readonly CompletionHelper _defaultCompletionHelper;
private readonly RecentItemsManager _recentItemsManager;
/// <summary>
/// For telemetry.
/// </summary>
private readonly object _targetTypeCompletionFilterChosenMarker = new();
internal ItemManager(RecentItemsManager recentItemsManager)
{
// Let us make the completion Helper used for non-Roslyn items case-sensitive.
// We can change this if get requests from partner teams.
_defaultCompletionHelper = new CompletionHelper(isCaseSensitive: true);
_recentItemsManager = recentItemsManager;
}
public Task<ImmutableArray<VSCompletionItem>> SortCompletionListAsync(
IAsyncCompletionSession session,
AsyncCompletionSessionInitialDataSnapshot data,
CancellationToken cancellationToken)
{
if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isTargetTypeFilterEnabled) && isTargetTypeFilterEnabled)
{
AsyncCompletionLogger.LogSessionHasTargetTypeFilterEnabled();
// This method is called exactly once, so use the opportunity to set a baseline for telemetry.
if (data.InitialList.Any(i => i.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)))
{
AsyncCompletionLogger.LogSessionContainsTargetTypeFilter();
}
}
if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTypeImportCompletionEnabled) && isTypeImportCompletionEnabled)
{
AsyncCompletionLogger.LogSessionWithTypeImportCompletionEnabled();
}
// Sort by default comparer of Roslyn CompletionItem
var sortedItems = data.InitialList.OrderBy(GetOrAddRoslynCompletionItem).ToImmutableArray();
return Task.FromResult(sortedItems);
}
public Task<FilteredCompletionModel?> UpdateCompletionListAsync(
IAsyncCompletionSession session,
AsyncCompletionSessionDataSnapshot data,
CancellationToken cancellationToken)
=> Task.FromResult(UpdateCompletionList(session, data, cancellationToken));
// We might need to handle large amount of items with import completion enabled,
// so use a dedicated pool to minimize/avoid array allocations (especially in LOH)
// Set the size of pool to 1 because we don't expect UpdateCompletionListAsync to be
// called concurrently, which essentially makes the pooled list a singleton,
// but we still use ObjectPool for concurrency handling just to be robust.
private static readonly ObjectPool<List<MatchResult<VSCompletionItem>>> s_listOfMatchResultPool
= new(factory: () => new(), size: 1);
private FilteredCompletionModel? UpdateCompletionList(
IAsyncCompletionSession session,
AsyncCompletionSessionDataSnapshot data,
CancellationToken cancellationToken)
{
if (!session.Properties.TryGetProperty(CompletionSource.HasSuggestionItemOptions, out bool hasSuggestedItemOptions))
{
// This is the scenario when the session is created out of Roslyn, in some other provider, e.g. in Debugger.
// For now, the default hasSuggestedItemOptions is false.
hasSuggestedItemOptions = false;
}
hasSuggestedItemOptions |= data.DisplaySuggestionItem;
var filterText = session.ApplicableToSpan.GetText(data.Snapshot);
var reason = data.Trigger.Reason;
var initialRoslynTriggerKind = Helpers.GetRoslynTriggerKind(data.InitialTrigger);
// Check if the user is typing a number. If so, only proceed if it's a number
// directly after a <dot>. That's because it is actually reasonable for completion
// to be brought up after a <dot> and for the user to want to filter completion
// items based on a number that exists in the name of the item. However, when
// we are not after a dot (i.e. we're being brought up after <space> is typed)
// then we don't want to filter things. Consider the user writing:
//
// dim i =<space>
//
// We'll bring up the completion list here (as VB has completion on <space>).
// If the user then types '3', we don't want to match against Int32.
if (filterText.Length > 0 && char.IsNumber(filterText[0]))
{
if (!IsAfterDot(data.Snapshot, session.ApplicableToSpan))
{
// Dismiss the session.
return null;
}
}
// We need to filter if
// 1. a non-empty strict subset of filters are selected
// 2. a non-empty set of expanders are unselected
var nonExpanderFilterStates = data.SelectedFilters.WhereAsArray(f => !(f.Filter is CompletionExpander));
var selectedNonExpanderFilters = nonExpanderFilterStates.SelectAsArray(f => f.IsSelected, f => f.Filter);
var needToFilter = selectedNonExpanderFilters.Length > 0 && selectedNonExpanderFilters.Length < nonExpanderFilterStates.Length;
var unselectedExpanders = data.SelectedFilters.SelectAsArray(f => !f.IsSelected && f.Filter is CompletionExpander, f => f.Filter);
var needToFilterExpanded = unselectedExpanders.Length > 0;
if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled)
{
// Telemetry: Want to know % of sessions with the "Target type matches" filter where that filter is actually enabled
if (needToFilter &&
!session.Properties.ContainsProperty(_targetTypeCompletionFilterChosenMarker) &&
selectedNonExpanderFilters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches))
{
AsyncCompletionLogger.LogTargetTypeFilterChosenInSession();
// Make sure we only record one enabling of the filter per session
session.Properties.AddProperty(_targetTypeCompletionFilterChosenMarker, _targetTypeCompletionFilterChosenMarker);
}
}
var filterReason = Helpers.GetFilterReason(data.Trigger);
// We prefer using the original snapshot, which should always be available from items provided by Roslyn's CompletionSource.
// Only use data.Snapshot in the theoretically possible but rare case when all items we are handling are from some non-Roslyn CompletionSource.
var snapshotForDocument = TryGetInitialTriggerLocation(data, out var intialTriggerLocation)
? intialTriggerLocation.Snapshot
: data.Snapshot;
var document = snapshotForDocument?.TextBuffer.AsTextContainer().GetOpenDocumentInCurrentContext();
var completionService = document?.GetLanguageService<CompletionService>();
var completionRules = completionService?.GetRules() ?? CompletionRules.Default;
var completionHelper = document != null ? CompletionHelper.GetHelper(document) : _defaultCompletionHelper;
// DismissIfLastCharacterDeleted should be applied only when started with Insertion, and then Deleted all characters typed.
// This conforms with the original VS 2010 behavior.
if (initialRoslynTriggerKind == CompletionTriggerKind.Insertion &&
data.Trigger.Reason == CompletionTriggerReason.Backspace &&
completionRules.DismissIfLastCharacterDeleted &&
session.ApplicableToSpan.GetText(data.Snapshot).Length == 0)
{
// Dismiss the session
return null;
}
var options = document?.Project.Solution.Options;
var highlightMatchingPortions = options?.GetOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, document?.Project.Language) ?? false;
// Nothing to highlight if user hasn't typed anything yet.
highlightMatchingPortions = highlightMatchingPortions && filterText.Length > 0;
// Use a monotonically increasing integer to keep track the original alphabetical order of each item.
var currentIndex = 0;
var initialListOfItemsToBeIncluded = s_listOfMatchResultPool.Allocate();
try
{
// Filter items based on the selected filters and matching.
foreach (var item in data.InitialSortedList)
{
cancellationToken.ThrowIfCancellationRequested();
if (needToFilter && ShouldBeFilteredOutOfCompletionList(item, selectedNonExpanderFilters))
{
continue;
}
if (needToFilterExpanded && ShouldBeFilteredOutOfExpandedCompletionList(item, unselectedExpanders))
{
continue;
}
if (TryCreateMatchResult(
completionHelper,
item,
filterText,
initialRoslynTriggerKind,
filterReason,
_recentItemsManager.RecentItems,
highlightMatchingPortions: highlightMatchingPortions,
currentIndex,
out var matchResult))
{
initialListOfItemsToBeIncluded.Add(matchResult);
currentIndex++;
}
}
if (initialListOfItemsToBeIncluded.Count == 0)
{
return HandleAllItemsFilteredOut(reason, data.SelectedFilters, completionRules);
}
// Sort the items by pattern matching results.
// Note that we want to preserve the original alphabetical order for items with same pattern match score,
// but `List<T>.Sort` isn't stable. Therefore we have to add a monotonically increasing integer
// to `MatchResult` to achieve this.
initialListOfItemsToBeIncluded.Sort(MatchResult<VSCompletionItem>.SortingComparer);
var showCompletionItemFilters = options?.GetOption(CompletionOptions.ShowCompletionItemFilters, document?.Project.Language) ?? true;
var updatedFilters = showCompletionItemFilters
? GetUpdatedFilters(initialListOfItemsToBeIncluded, data.SelectedFilters)
: ImmutableArray<CompletionFilterWithState>.Empty;
// If this was deletion, then we control the entire behavior of deletion ourselves.
if (initialRoslynTriggerKind == CompletionTriggerKind.Deletion)
{
return HandleDeletionTrigger(reason, initialListOfItemsToBeIncluded, filterText, updatedFilters, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper);
}
Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod;
if (completionService == null)
{
filterMethod = (itemsWithPatternMatches, text) => CompletionService.FilterItems(completionHelper, itemsWithPatternMatches, text);
}
else
{
filterMethod = (itemsWithPatternMatches, text) => completionService.FilterItems(document, itemsWithPatternMatches, text);
}
return HandleNormalFiltering(
filterMethod,
filterText,
updatedFilters,
filterReason,
data.Trigger.Character,
initialListOfItemsToBeIncluded,
hasSuggestedItemOptions,
highlightMatchingPortions,
completionHelper);
}
finally
{
// Don't call ClearAndFree, which resets the capacity to a default value.
initialListOfItemsToBeIncluded.Clear();
s_listOfMatchResultPool.Free(initialListOfItemsToBeIncluded);
}
static bool TryGetInitialTriggerLocation(AsyncCompletionSessionDataSnapshot data, out SnapshotPoint intialTriggerLocation)
{
var firstItem = data.InitialSortedList.FirstOrDefault(static item => item.Properties.ContainsProperty(CompletionSource.TriggerLocation));
if (firstItem != null)
{
return firstItem.Properties.TryGetProperty(CompletionSource.TriggerLocation, out intialTriggerLocation);
}
intialTriggerLocation = default;
return false;
}
static bool ShouldBeFilteredOutOfCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> activeNonExpanderFilters)
{
if (item.Filters.Any(filter => activeNonExpanderFilters.Contains(filter)))
{
return false;
}
return true;
}
static bool ShouldBeFilteredOutOfExpandedCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> unselectedExpanders)
{
var associatedWithUnselectedExpander = false;
foreach (var itemFilter in item.Filters)
{
if (itemFilter is CompletionExpander)
{
if (!unselectedExpanders.Contains(itemFilter))
{
// If any of the associated expander is selected, the item should be included in the expanded list.
return false;
}
associatedWithUnselectedExpander = true;
}
}
// at this point, the item either:
// 1. has no expander filter, therefore should be included
// 2. or, all associated expanders are unselected, therefore should be excluded
return associatedWithUnselectedExpander;
}
}
private static bool IsAfterDot(ITextSnapshot snapshot, ITrackingSpan applicableToSpan)
{
var position = applicableToSpan.GetStartPoint(snapshot).Position;
return position > 0 && snapshot[position - 1] == '.';
}
private FilteredCompletionModel? HandleNormalFiltering(
Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod,
string filterText,
ImmutableArray<CompletionFilterWithState> filters,
CompletionFilterReason filterReason,
char typeChar,
List<MatchResult<VSCompletionItem>> itemsInList,
bool hasSuggestedItemOptions,
bool highlightMatchingPortions,
CompletionHelper completionHelper)
{
// Not deletion. Defer to the language to decide which item it thinks best
// matches the text typed so far.
// Ask the language to determine which of the *matched* items it wants to select.
var matchingItems = itemsInList.Where(r => r.MatchedFilterText)
.SelectAsArray(t => (t.RoslynCompletionItem, t.PatternMatch));
var chosenItems = filterMethod(matchingItems, filterText);
int selectedItemIndex;
VSCompletionItem? uniqueItem = null;
MatchResult<VSCompletionItem> bestOrFirstMatchResult;
if (chosenItems.Length == 0)
{
// We do not have matches: pick the one with longest common prefix or the first item from the list.
selectedItemIndex = 0;
bestOrFirstMatchResult = itemsInList[0];
var longestCommonPrefixLength = bestOrFirstMatchResult.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText);
for (var i = 1; i < itemsInList.Count; ++i)
{
var item = itemsInList[i];
var commonPrefixLength = item.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText);
if (commonPrefixLength > longestCommonPrefixLength)
{
selectedItemIndex = i;
bestOrFirstMatchResult = item;
longestCommonPrefixLength = commonPrefixLength;
}
}
}
else
{
var recentItems = _recentItemsManager.RecentItems;
// Of the items the service returned, pick the one most recently committed
var bestItem = GetBestCompletionItemBasedOnMRU(chosenItems, recentItems);
// Determine if we should consider this item 'unique' or not. A unique item
// will be automatically committed if the user hits the 'invoke completion'
// without bringing up the completion list. An item is unique if it was the
// only item to match the text typed so far, and there was at least some text
// typed. i.e. if we have "Console.$$" we don't want to commit something
// like "WriteLine" since no filter text has actually been provided. However,
// if "Console.WriteL$$" is typed, then we do want "WriteLine" to be committed.
selectedItemIndex = itemsInList.IndexOf(i => Equals(i.RoslynCompletionItem, bestItem));
bestOrFirstMatchResult = itemsInList[selectedItemIndex];
var deduplicatedListCount = matchingItems.Count(r => !r.RoslynCompletionItem.IsPreferredItem());
if (deduplicatedListCount == 1 &&
filterText.Length > 0)
{
uniqueItem = itemsInList[selectedItemIndex].EditorCompletionItem;
}
}
// Check that it is a filter symbol. We can be called for a non-filter symbol.
// If inserting a non-filter character (neither IsPotentialFilterCharacter, nor Helpers.IsFilterCharacter), we should dismiss completion
// except cases where this is the first symbol typed for the completion session (string.IsNullOrEmpty(filterText) or string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase)).
// In the latter case, we should keep the completion because it was confirmed just before in InitializeCompletion.
if (filterReason == CompletionFilterReason.Insertion &&
!string.IsNullOrEmpty(filterText) &&
!string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase) &&
!IsPotentialFilterCharacter(typeChar) &&
!Helpers.IsFilterCharacter(bestOrFirstMatchResult.RoslynCompletionItem, typeChar, filterText))
{
return null;
}
var isHardSelection = IsHardSelection(
filterText, bestOrFirstMatchResult.RoslynCompletionItem, bestOrFirstMatchResult.MatchedFilterText, hasSuggestedItemOptions);
var updateSelectionHint = isHardSelection ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected;
return new FilteredCompletionModel(
GetHighlightedList(itemsInList, filterText, highlightMatchingPortions, completionHelper), selectedItemIndex, filters,
updateSelectionHint, centerSelection: true, uniqueItem);
}
private static FilteredCompletionModel? HandleDeletionTrigger(
CompletionTriggerReason filterTriggerKind,
List<MatchResult<VSCompletionItem>> matchResults,
string filterText,
ImmutableArray<CompletionFilterWithState> filters,
bool hasSuggestedItemOptions,
bool highlightMatchingSpans,
CompletionHelper completionHelper)
{
var matchingItems = matchResults.Where(r => r.MatchedFilterText);
if (filterTriggerKind == CompletionTriggerReason.Insertion &&
!matchingItems.Any())
{
// The user has typed something, but nothing in the actual list matched what
// they were typing. In this case, we want to dismiss completion entirely.
// The thought process is as follows: we aggressively brought up completion
// to help them when they typed delete (in case they wanted to pick another
// item). However, they're typing something that doesn't seem to match at all
// The completion list is just distracting at this point.
return null;
}
MatchResult<VSCompletionItem>? bestMatchResult = null;
var moreThanOneMatchWithSamePriority = false;
foreach (var currentMatchResult in matchingItems)
{
if (bestMatchResult == null)
{
// We had no best result yet, so this is now our best result.
bestMatchResult = currentMatchResult;
}
else
{
var match = currentMatchResult.CompareTo(bestMatchResult.Value, filterText);
if (match > 0)
{
moreThanOneMatchWithSamePriority = false;
bestMatchResult = currentMatchResult;
}
else if (match == 0)
{
moreThanOneMatchWithSamePriority = true;
}
}
}
int index;
bool hardSelect;
// If we had a matching item, then pick the best of the matching items and
// choose that one to be hard selected. If we had no actual matching items
// (which can happen if the user deletes down to a single character and we
// include everything), then we just soft select the first item.
if (bestMatchResult != null)
{
// Only hard select this result if it's a prefix match
// We need to do this so that
// * deleting and retyping a dot in a member access does not change the
// text that originally appeared before the dot
// * deleting through a word from the end keeps that word selected
// This also preserves the behavior the VB had through Dev12.
hardSelect = !hasSuggestedItemOptions && bestMatchResult.Value.EditorCompletionItem.FilterText.StartsWith(filterText, StringComparison.CurrentCultureIgnoreCase);
index = matchResults.IndexOf(bestMatchResult.Value);
}
else
{
index = 0;
hardSelect = false;
}
return new FilteredCompletionModel(
GetHighlightedList(matchResults, filterText, highlightMatchingSpans, completionHelper), index, filters,
hardSelect ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected,
centerSelection: true,
uniqueItem: moreThanOneMatchWithSamePriority ? null : bestMatchResult.GetValueOrDefault().EditorCompletionItem);
}
private static ImmutableArray<CompletionItemWithHighlight> GetHighlightedList(
List<MatchResult<VSCompletionItem>> matchResults,
string filterText,
bool highlightMatchingPortions,
CompletionHelper completionHelper)
{
return matchResults.SelectAsArray(matchResult =>
{
var highlightedSpans = GetHighlightedSpans(matchResult, completionHelper, filterText, highlightMatchingPortions);
return new CompletionItemWithHighlight(matchResult.EditorCompletionItem, highlightedSpans);
});
static ImmutableArray<Span> GetHighlightedSpans(
MatchResult<VSCompletionItem> matchResult,
CompletionHelper completionHelper,
string filterText,
bool highlightMatchingPortions)
{
if (highlightMatchingPortions)
{
if (matchResult.RoslynCompletionItem.HasDifferentFilterText)
{
// The PatternMatch in MatchResult is calculated based on Roslyn item's FilterText,
// which can be used to calculate highlighted span for VSCompletion item's DisplayText w/o doing the matching again.
// However, if the Roslyn item's FilterText is different from its DisplayText,
// we need to do the match against the display text of the VS item directly to get the highlighted spans.
return completionHelper.GetHighlightedSpans(
matchResult.EditorCompletionItem.DisplayText, filterText, CultureInfo.CurrentCulture).SelectAsArray(s => s.ToSpan());
}
var patternMatch = matchResult.PatternMatch;
if (patternMatch.HasValue)
{
// Since VS item's display text is created as Prefix + DisplayText + Suffix,
// we can calculate the highlighted span by adding an offset that is the length of the Prefix.
return patternMatch.Value.MatchedSpans.SelectAsArray(s_highlightSpanGetter, matchResult.RoslynCompletionItem);
}
}
// If there's no match for Roslyn item's filter text which is identical to its display text,
// then we can safely assume there'd be no matching to VS item's display text.
return ImmutableArray<Span>.Empty;
}
}
private static FilteredCompletionModel? HandleAllItemsFilteredOut(
CompletionTriggerReason triggerReason,
ImmutableArray<CompletionFilterWithState> filters,
CompletionRules completionRules)
{
if (triggerReason == CompletionTriggerReason.Insertion)
{
// If the user was just typing, and the list went to empty *and* this is a
// language that wants to dismiss on empty, then just return a null model
// to stop the completion session.
if (completionRules.DismissIfEmpty)
{
return null;
}
}
// If the user has turned on some filtering states, and we filtered down to
// nothing, then we do want the UI to show that to them. That way the user
// can turn off filters they don't want and get the right set of items.
// If we are going to filter everything out, then just preserve the existing
// model (and all the previously filtered items), but switch over to soft
// selection.
var selection = UpdateSelectionHint.SoftSelected;
return new FilteredCompletionModel(
ImmutableArray<CompletionItemWithHighlight>.Empty, selectedItemIndex: 0,
filters, selection, centerSelection: true, uniqueItem: null);
}
private static ImmutableArray<CompletionFilterWithState> GetUpdatedFilters(
List<MatchResult<VSCompletionItem>> filteredList,
ImmutableArray<CompletionFilterWithState> filters)
{
// See which filters might be enabled based on the typed code
using var _ = PooledHashSet<CompletionFilter>.GetInstance(out var textFilteredFilters);
textFilteredFilters.AddRange(filteredList.SelectMany(n => n.EditorCompletionItem.Filters));
// When no items are available for a given filter, it becomes unavailable.
// Expanders always appear available as long as it's presented.
return filters.SelectAsArray(n => n.WithAvailability(n.Filter is CompletionExpander ? true : textFilteredFilters.Contains(n.Filter)));
}
/// <summary>
/// Given multiple possible chosen completion items, pick the one that has the
/// best MRU index, or the one with highest MatchPriority if none in MRU.
/// </summary>
private static RoslynCompletionItem GetBestCompletionItemBasedOnMRU(
ImmutableArray<RoslynCompletionItem> chosenItems, ImmutableArray<string> recentItems)
{
Debug.Assert(chosenItems.Length > 0);
// Try to find the chosen item has been most recently used.
var bestItem = chosenItems[0];
for (int i = 1, n = chosenItems.Length; i < n; i++)
{
var chosenItem = chosenItems[i];
var mruIndex1 = GetRecentItemIndex(recentItems, bestItem);
var mruIndex2 = GetRecentItemIndex(recentItems, chosenItem);
if ((mruIndex2 < mruIndex1) ||
(mruIndex2 == mruIndex1 && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem()))
{
bestItem = chosenItem;
}
}
// If our best item appeared in the MRU list, use it
if (GetRecentItemIndex(recentItems, bestItem) <= 0)
{
return bestItem;
}
// Otherwise use the chosen item that has the highest
// matchPriority.
for (int i = 1, n = chosenItems.Length; i < n; i++)
{
var chosenItem = chosenItems[i];
var bestItemPriority = bestItem.Rules.MatchPriority;
var currentItemPriority = chosenItem.Rules.MatchPriority;
if ((currentItemPriority > bestItemPriority) ||
((currentItemPriority == bestItemPriority) && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem()))
{
bestItem = chosenItem;
}
}
return bestItem;
}
private static int GetRecentItemIndex(ImmutableArray<string> recentItems, RoslynCompletionItem item)
{
var index = recentItems.IndexOf(item.FilterText);
return -index;
}
private static RoslynCompletionItem GetOrAddRoslynCompletionItem(VSCompletionItem vsItem)
{
if (!vsItem.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem))
{
roslynItem = RoslynCompletionItem.Create(
displayText: vsItem.DisplayText,
filterText: vsItem.FilterText,
sortText: vsItem.SortText,
displayTextSuffix: vsItem.Suffix);
vsItem.Properties.AddProperty(CompletionSource.RoslynItem, roslynItem);
}
return roslynItem;
}
private static bool TryCreateMatchResult(
CompletionHelper completionHelper,
VSCompletionItem item,
string filterText,
CompletionTriggerKind initialTriggerKind,
CompletionFilterReason filterReason,
ImmutableArray<string> recentItems,
bool highlightMatchingPortions,
int currentIndex,
out MatchResult<VSCompletionItem> matchResult)
{
var roslynItem = GetOrAddRoslynCompletionItem(item);
return CompletionHelper.TryCreateMatchResult(completionHelper, roslynItem, item, filterText, initialTriggerKind, filterReason, recentItems, highlightMatchingPortions, currentIndex, out matchResult);
}
// PERF: Create a singleton to avoid lambda allocation on hot path
private static readonly Func<TextSpan, RoslynCompletionItem, Span> s_highlightSpanGetter
= (span, item) => span.MoveTo(item.DisplayTextPrefix?.Length ?? 0).ToSpan();
private static bool IsHardSelection(
string filterText,
RoslynCompletionItem item,
bool matchedFilterText,
bool useSuggestionMode)
{
if (item == null || useSuggestionMode)
{
return false;
}
// We don't have a builder and we have a best match. Normally this will be hard
// selected, except for a few cases. Specifically, if no filter text has been
// provided, and this is not a preselect match then we will soft select it. This
// happens when the completion list comes up implicitly and there is something in
// the MRU list. In this case we do want to select it, but not with a hard
// selection. Otherwise you can end up with the following problem:
//
// dim i as integer =<space>
//
// Completion will comes up after = with 'integer' selected (Because of MRU). We do
// not want 'space' to commit this.
// If all that has been typed is punctuation, then don't hard select anything.
// It's possible the user is just typing language punctuation and selecting
// anything in the list will interfere. We only allow this if the filter text
// exactly matches something in the list already.
if (filterText.Length > 0 && IsAllPunctuation(filterText) && filterText != item.DisplayText)
{
return false;
}
// If the user hasn't actually typed anything, then don't hard select any item.
// The only exception to this is if the completion provider has requested the
// item be preselected.
if (filterText.Length == 0)
{
// Item didn't want to be hard selected with no filter text.
// So definitely soft select it.
if (item.Rules.SelectionBehavior != CompletionItemSelectionBehavior.HardSelection)
{
return false;
}
// Item did not ask to be preselected. So definitely soft select it.
if (item.Rules.MatchPriority == MatchPriority.Default)
{
return false;
}
}
// The user typed something, or the item asked to be preselected. In
// either case, don't soft select this.
Debug.Assert(filterText.Length > 0 || item.Rules.MatchPriority != MatchPriority.Default);
// If the user moved the caret left after they started typing, the 'best' match may not match at all
// against the full text span that this item would be replacing.
if (!matchedFilterText)
{
return false;
}
// There was either filter text, or this was a preselect match. In either case, we
// can hard select this.
return true;
}
private static bool IsAllPunctuation(string filterText)
{
foreach (var ch in filterText)
{
if (!char.IsPunctuation(ch))
{
return false;
}
}
return true;
}
/// <summary>
/// A potential filter character is something that can filter a completion lists and is
/// *guaranteed* to not be a commit character.
/// </summary>
private static bool IsPotentialFilterCharacter(char c)
{
// TODO(cyrusn): Actually use the right Unicode categories here.
return char.IsLetter(c)
|| char.IsNumber(c)
|| c == '_';
}
}
}
| // 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.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.PatternMatching;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem;
using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion
{
internal class ItemManager : IAsyncCompletionItemManager
{
/// <summary>
/// Used for filtering non-Roslyn data only.
/// </summary>
private readonly CompletionHelper _defaultCompletionHelper;
private readonly RecentItemsManager _recentItemsManager;
/// <summary>
/// For telemetry.
/// </summary>
private readonly object _targetTypeCompletionFilterChosenMarker = new();
internal ItemManager(RecentItemsManager recentItemsManager)
{
// Let us make the completion Helper used for non-Roslyn items case-sensitive.
// We can change this if get requests from partner teams.
_defaultCompletionHelper = new CompletionHelper(isCaseSensitive: true);
_recentItemsManager = recentItemsManager;
}
public Task<ImmutableArray<VSCompletionItem>> SortCompletionListAsync(
IAsyncCompletionSession session,
AsyncCompletionSessionInitialDataSnapshot data,
CancellationToken cancellationToken)
{
if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isTargetTypeFilterEnabled) && isTargetTypeFilterEnabled)
{
AsyncCompletionLogger.LogSessionHasTargetTypeFilterEnabled();
// This method is called exactly once, so use the opportunity to set a baseline for telemetry.
if (data.InitialList.Any(i => i.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)))
{
AsyncCompletionLogger.LogSessionContainsTargetTypeFilter();
}
}
if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTypeImportCompletionEnabled) && isTypeImportCompletionEnabled)
{
AsyncCompletionLogger.LogSessionWithTypeImportCompletionEnabled();
}
// Sort by default comparer of Roslyn CompletionItem
var sortedItems = data.InitialList.OrderBy(GetOrAddRoslynCompletionItem).ToImmutableArray();
return Task.FromResult(sortedItems);
}
public Task<FilteredCompletionModel?> UpdateCompletionListAsync(
IAsyncCompletionSession session,
AsyncCompletionSessionDataSnapshot data,
CancellationToken cancellationToken)
=> Task.FromResult(UpdateCompletionList(session, data, cancellationToken));
// We might need to handle large amount of items with import completion enabled,
// so use a dedicated pool to minimize/avoid array allocations (especially in LOH)
// Set the size of pool to 1 because we don't expect UpdateCompletionListAsync to be
// called concurrently, which essentially makes the pooled list a singleton,
// but we still use ObjectPool for concurrency handling just to be robust.
private static readonly ObjectPool<List<MatchResult<VSCompletionItem>>> s_listOfMatchResultPool
= new(factory: () => new(), size: 1);
private FilteredCompletionModel? UpdateCompletionList(
IAsyncCompletionSession session,
AsyncCompletionSessionDataSnapshot data,
CancellationToken cancellationToken)
{
if (!session.Properties.TryGetProperty(CompletionSource.HasSuggestionItemOptions, out bool hasSuggestedItemOptions))
{
// This is the scenario when the session is created out of Roslyn, in some other provider, e.g. in Debugger.
// For now, the default hasSuggestedItemOptions is false.
hasSuggestedItemOptions = false;
}
hasSuggestedItemOptions |= data.DisplaySuggestionItem;
var filterText = session.ApplicableToSpan.GetText(data.Snapshot);
var reason = data.Trigger.Reason;
var initialRoslynTriggerKind = Helpers.GetRoslynTriggerKind(data.InitialTrigger);
// Check if the user is typing a number. If so, only proceed if it's a number
// directly after a <dot>. That's because it is actually reasonable for completion
// to be brought up after a <dot> and for the user to want to filter completion
// items based on a number that exists in the name of the item. However, when
// we are not after a dot (i.e. we're being brought up after <space> is typed)
// then we don't want to filter things. Consider the user writing:
//
// dim i =<space>
//
// We'll bring up the completion list here (as VB has completion on <space>).
// If the user then types '3', we don't want to match against Int32.
if (filterText.Length > 0 && char.IsNumber(filterText[0]))
{
if (!IsAfterDot(data.Snapshot, session.ApplicableToSpan))
{
// Dismiss the session.
return null;
}
}
// We need to filter if
// 1. a non-empty strict subset of filters are selected
// 2. a non-empty set of expanders are unselected
var nonExpanderFilterStates = data.SelectedFilters.WhereAsArray(f => !(f.Filter is CompletionExpander));
var selectedNonExpanderFilters = nonExpanderFilterStates.SelectAsArray(f => f.IsSelected, f => f.Filter);
var needToFilter = selectedNonExpanderFilters.Length > 0 && selectedNonExpanderFilters.Length < nonExpanderFilterStates.Length;
var unselectedExpanders = data.SelectedFilters.SelectAsArray(f => !f.IsSelected && f.Filter is CompletionExpander, f => f.Filter);
var needToFilterExpanded = unselectedExpanders.Length > 0;
if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled)
{
// Telemetry: Want to know % of sessions with the "Target type matches" filter where that filter is actually enabled
if (needToFilter &&
!session.Properties.ContainsProperty(_targetTypeCompletionFilterChosenMarker) &&
selectedNonExpanderFilters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches))
{
AsyncCompletionLogger.LogTargetTypeFilterChosenInSession();
// Make sure we only record one enabling of the filter per session
session.Properties.AddProperty(_targetTypeCompletionFilterChosenMarker, _targetTypeCompletionFilterChosenMarker);
}
}
var filterReason = Helpers.GetFilterReason(data.Trigger);
// We prefer using the original snapshot, which should always be available from items provided by Roslyn's CompletionSource.
// Only use data.Snapshot in the theoretically possible but rare case when all items we are handling are from some non-Roslyn CompletionSource.
var snapshotForDocument = TryGetInitialTriggerLocation(data, out var intialTriggerLocation)
? intialTriggerLocation.Snapshot
: data.Snapshot;
var document = snapshotForDocument?.TextBuffer.AsTextContainer().GetOpenDocumentInCurrentContext();
var completionService = document?.GetLanguageService<CompletionService>();
var completionRules = completionService?.GetRules() ?? CompletionRules.Default;
var completionHelper = document != null ? CompletionHelper.GetHelper(document) : _defaultCompletionHelper;
// DismissIfLastCharacterDeleted should be applied only when started with Insertion, and then Deleted all characters typed.
// This conforms with the original VS 2010 behavior.
if (initialRoslynTriggerKind == CompletionTriggerKind.Insertion &&
data.Trigger.Reason == CompletionTriggerReason.Backspace &&
completionRules.DismissIfLastCharacterDeleted &&
session.ApplicableToSpan.GetText(data.Snapshot).Length == 0)
{
// Dismiss the session
return null;
}
var options = document?.Project.Solution.Options;
var highlightMatchingPortions = options?.GetOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, document?.Project.Language) ?? false;
// Nothing to highlight if user hasn't typed anything yet.
highlightMatchingPortions = highlightMatchingPortions && filterText.Length > 0;
// Use a monotonically increasing integer to keep track the original alphabetical order of each item.
var currentIndex = 0;
var initialListOfItemsToBeIncluded = s_listOfMatchResultPool.Allocate();
try
{
// Filter items based on the selected filters and matching.
foreach (var item in data.InitialSortedList)
{
cancellationToken.ThrowIfCancellationRequested();
if (needToFilter && ShouldBeFilteredOutOfCompletionList(item, selectedNonExpanderFilters))
{
continue;
}
if (needToFilterExpanded && ShouldBeFilteredOutOfExpandedCompletionList(item, unselectedExpanders))
{
continue;
}
if (TryCreateMatchResult(
completionHelper,
item,
filterText,
initialRoslynTriggerKind,
filterReason,
_recentItemsManager.RecentItems,
highlightMatchingPortions: highlightMatchingPortions,
currentIndex,
out var matchResult))
{
initialListOfItemsToBeIncluded.Add(matchResult);
currentIndex++;
}
}
if (initialListOfItemsToBeIncluded.Count == 0)
{
return HandleAllItemsFilteredOut(reason, data.SelectedFilters, completionRules);
}
// Sort the items by pattern matching results.
// Note that we want to preserve the original alphabetical order for items with same pattern match score,
// but `List<T>.Sort` isn't stable. Therefore we have to add a monotonically increasing integer
// to `MatchResult` to achieve this.
initialListOfItemsToBeIncluded.Sort(MatchResult<VSCompletionItem>.SortingComparer);
var showCompletionItemFilters = options?.GetOption(CompletionOptions.ShowCompletionItemFilters, document?.Project.Language) ?? true;
var updatedFilters = showCompletionItemFilters
? GetUpdatedFilters(initialListOfItemsToBeIncluded, data.SelectedFilters)
: ImmutableArray<CompletionFilterWithState>.Empty;
// If this was deletion, then we control the entire behavior of deletion ourselves.
if (initialRoslynTriggerKind == CompletionTriggerKind.Deletion)
{
return HandleDeletionTrigger(reason, initialListOfItemsToBeIncluded, filterText, updatedFilters, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper);
}
Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod;
if (completionService == null)
{
filterMethod = (itemsWithPatternMatches, text) => CompletionService.FilterItems(completionHelper, itemsWithPatternMatches, text);
}
else
{
filterMethod = (itemsWithPatternMatches, text) => completionService.FilterItems(document, itemsWithPatternMatches, text);
}
return HandleNormalFiltering(
filterMethod,
filterText,
updatedFilters,
filterReason,
data.Trigger.Character,
initialListOfItemsToBeIncluded,
hasSuggestedItemOptions,
highlightMatchingPortions,
completionHelper);
}
finally
{
// Don't call ClearAndFree, which resets the capacity to a default value.
initialListOfItemsToBeIncluded.Clear();
s_listOfMatchResultPool.Free(initialListOfItemsToBeIncluded);
}
static bool TryGetInitialTriggerLocation(AsyncCompletionSessionDataSnapshot data, out SnapshotPoint intialTriggerLocation)
{
var firstItem = data.InitialSortedList.FirstOrDefault(static item => item.Properties.ContainsProperty(CompletionSource.TriggerLocation));
if (firstItem != null)
{
return firstItem.Properties.TryGetProperty(CompletionSource.TriggerLocation, out intialTriggerLocation);
}
intialTriggerLocation = default;
return false;
}
static bool ShouldBeFilteredOutOfCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> activeNonExpanderFilters)
{
if (item.Filters.Any(filter => activeNonExpanderFilters.Contains(filter)))
{
return false;
}
return true;
}
static bool ShouldBeFilteredOutOfExpandedCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> unselectedExpanders)
{
var associatedWithUnselectedExpander = false;
foreach (var itemFilter in item.Filters)
{
if (itemFilter is CompletionExpander)
{
if (!unselectedExpanders.Contains(itemFilter))
{
// If any of the associated expander is selected, the item should be included in the expanded list.
return false;
}
associatedWithUnselectedExpander = true;
}
}
// at this point, the item either:
// 1. has no expander filter, therefore should be included
// 2. or, all associated expanders are unselected, therefore should be excluded
return associatedWithUnselectedExpander;
}
}
private static bool IsAfterDot(ITextSnapshot snapshot, ITrackingSpan applicableToSpan)
{
var position = applicableToSpan.GetStartPoint(snapshot).Position;
return position > 0 && snapshot[position - 1] == '.';
}
private FilteredCompletionModel? HandleNormalFiltering(
Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod,
string filterText,
ImmutableArray<CompletionFilterWithState> filters,
CompletionFilterReason filterReason,
char typeChar,
List<MatchResult<VSCompletionItem>> itemsInList,
bool hasSuggestedItemOptions,
bool highlightMatchingPortions,
CompletionHelper completionHelper)
{
// Not deletion. Defer to the language to decide which item it thinks best
// matches the text typed so far.
// Ask the language to determine which of the *matched* items it wants to select.
var matchingItems = itemsInList.Where(r => r.MatchedFilterText)
.SelectAsArray(t => (t.RoslynCompletionItem, t.PatternMatch));
var chosenItems = filterMethod(matchingItems, filterText);
int selectedItemIndex;
VSCompletionItem? uniqueItem = null;
MatchResult<VSCompletionItem> bestOrFirstMatchResult;
if (chosenItems.Length == 0)
{
// We do not have matches: pick the one with longest common prefix or the first item from the list.
selectedItemIndex = 0;
bestOrFirstMatchResult = itemsInList[0];
var longestCommonPrefixLength = bestOrFirstMatchResult.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText);
for (var i = 1; i < itemsInList.Count; ++i)
{
var item = itemsInList[i];
var commonPrefixLength = item.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText);
if (commonPrefixLength > longestCommonPrefixLength)
{
selectedItemIndex = i;
bestOrFirstMatchResult = item;
longestCommonPrefixLength = commonPrefixLength;
}
}
}
else
{
var recentItems = _recentItemsManager.RecentItems;
// Of the items the service returned, pick the one most recently committed
var bestItem = GetBestCompletionItemBasedOnMRU(chosenItems, recentItems);
// Determine if we should consider this item 'unique' or not. A unique item
// will be automatically committed if the user hits the 'invoke completion'
// without bringing up the completion list. An item is unique if it was the
// only item to match the text typed so far, and there was at least some text
// typed. i.e. if we have "Console.$$" we don't want to commit something
// like "WriteLine" since no filter text has actually been provided. However,
// if "Console.WriteL$$" is typed, then we do want "WriteLine" to be committed.
selectedItemIndex = itemsInList.IndexOf(i => Equals(i.RoslynCompletionItem, bestItem));
bestOrFirstMatchResult = itemsInList[selectedItemIndex];
var deduplicatedListCount = matchingItems.Count(r => !r.RoslynCompletionItem.IsPreferredItem());
if (deduplicatedListCount == 1 &&
filterText.Length > 0)
{
uniqueItem = itemsInList[selectedItemIndex].EditorCompletionItem;
}
}
// Check that it is a filter symbol. We can be called for a non-filter symbol.
// If inserting a non-filter character (neither IsPotentialFilterCharacter, nor Helpers.IsFilterCharacter), we should dismiss completion
// except cases where this is the first symbol typed for the completion session (string.IsNullOrEmpty(filterText) or string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase)).
// In the latter case, we should keep the completion because it was confirmed just before in InitializeCompletion.
if (filterReason == CompletionFilterReason.Insertion &&
!string.IsNullOrEmpty(filterText) &&
!string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase) &&
!IsPotentialFilterCharacter(typeChar) &&
!Helpers.IsFilterCharacter(bestOrFirstMatchResult.RoslynCompletionItem, typeChar, filterText))
{
return null;
}
var isHardSelection = IsHardSelection(
filterText, bestOrFirstMatchResult.RoslynCompletionItem, bestOrFirstMatchResult.MatchedFilterText, hasSuggestedItemOptions);
var updateSelectionHint = isHardSelection ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected;
return new FilteredCompletionModel(
GetHighlightedList(itemsInList, filterText, highlightMatchingPortions, completionHelper), selectedItemIndex, filters,
updateSelectionHint, centerSelection: true, uniqueItem);
}
private static FilteredCompletionModel? HandleDeletionTrigger(
CompletionTriggerReason filterTriggerKind,
List<MatchResult<VSCompletionItem>> matchResults,
string filterText,
ImmutableArray<CompletionFilterWithState> filters,
bool hasSuggestedItemOptions,
bool highlightMatchingSpans,
CompletionHelper completionHelper)
{
var matchingItems = matchResults.Where(r => r.MatchedFilterText);
if (filterTriggerKind == CompletionTriggerReason.Insertion &&
!matchingItems.Any())
{
// The user has typed something, but nothing in the actual list matched what
// they were typing. In this case, we want to dismiss completion entirely.
// The thought process is as follows: we aggressively brought up completion
// to help them when they typed delete (in case they wanted to pick another
// item). However, they're typing something that doesn't seem to match at all
// The completion list is just distracting at this point.
return null;
}
MatchResult<VSCompletionItem>? bestMatchResult = null;
var moreThanOneMatchWithSamePriority = false;
foreach (var currentMatchResult in matchingItems)
{
if (bestMatchResult == null)
{
// We had no best result yet, so this is now our best result.
bestMatchResult = currentMatchResult;
}
else
{
var match = currentMatchResult.CompareTo(bestMatchResult.Value, filterText);
if (match > 0)
{
moreThanOneMatchWithSamePriority = false;
bestMatchResult = currentMatchResult;
}
else if (match == 0)
{
moreThanOneMatchWithSamePriority = true;
}
}
}
int index;
bool hardSelect;
// If we had a matching item, then pick the best of the matching items and
// choose that one to be hard selected. If we had no actual matching items
// (which can happen if the user deletes down to a single character and we
// include everything), then we just soft select the first item.
if (bestMatchResult != null)
{
// Only hard select this result if it's a prefix match
// We need to do this so that
// * deleting and retyping a dot in a member access does not change the
// text that originally appeared before the dot
// * deleting through a word from the end keeps that word selected
// This also preserves the behavior the VB had through Dev12.
hardSelect = !hasSuggestedItemOptions && bestMatchResult.Value.EditorCompletionItem.FilterText.StartsWith(filterText, StringComparison.CurrentCultureIgnoreCase);
index = matchResults.IndexOf(bestMatchResult.Value);
}
else
{
index = 0;
hardSelect = false;
}
return new FilteredCompletionModel(
GetHighlightedList(matchResults, filterText, highlightMatchingSpans, completionHelper), index, filters,
hardSelect ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected,
centerSelection: true,
uniqueItem: moreThanOneMatchWithSamePriority ? null : bestMatchResult.GetValueOrDefault().EditorCompletionItem);
}
private static ImmutableArray<CompletionItemWithHighlight> GetHighlightedList(
List<MatchResult<VSCompletionItem>> matchResults,
string filterText,
bool highlightMatchingPortions,
CompletionHelper completionHelper)
{
return matchResults.SelectAsArray(matchResult =>
{
var highlightedSpans = GetHighlightedSpans(matchResult, completionHelper, filterText, highlightMatchingPortions);
return new CompletionItemWithHighlight(matchResult.EditorCompletionItem, highlightedSpans);
});
static ImmutableArray<Span> GetHighlightedSpans(
MatchResult<VSCompletionItem> matchResult,
CompletionHelper completionHelper,
string filterText,
bool highlightMatchingPortions)
{
if (highlightMatchingPortions)
{
if (matchResult.RoslynCompletionItem.HasDifferentFilterText)
{
// The PatternMatch in MatchResult is calculated based on Roslyn item's FilterText,
// which can be used to calculate highlighted span for VSCompletion item's DisplayText w/o doing the matching again.
// However, if the Roslyn item's FilterText is different from its DisplayText,
// we need to do the match against the display text of the VS item directly to get the highlighted spans.
return completionHelper.GetHighlightedSpans(
matchResult.EditorCompletionItem.DisplayText, filterText, CultureInfo.CurrentCulture).SelectAsArray(s => s.ToSpan());
}
var patternMatch = matchResult.PatternMatch;
if (patternMatch.HasValue)
{
// Since VS item's display text is created as Prefix + DisplayText + Suffix,
// we can calculate the highlighted span by adding an offset that is the length of the Prefix.
return patternMatch.Value.MatchedSpans.SelectAsArray(s_highlightSpanGetter, matchResult.RoslynCompletionItem);
}
}
// If there's no match for Roslyn item's filter text which is identical to its display text,
// then we can safely assume there'd be no matching to VS item's display text.
return ImmutableArray<Span>.Empty;
}
}
private static FilteredCompletionModel? HandleAllItemsFilteredOut(
CompletionTriggerReason triggerReason,
ImmutableArray<CompletionFilterWithState> filters,
CompletionRules completionRules)
{
if (triggerReason == CompletionTriggerReason.Insertion)
{
// If the user was just typing, and the list went to empty *and* this is a
// language that wants to dismiss on empty, then just return a null model
// to stop the completion session.
if (completionRules.DismissIfEmpty)
{
return null;
}
}
// If the user has turned on some filtering states, and we filtered down to
// nothing, then we do want the UI to show that to them. That way the user
// can turn off filters they don't want and get the right set of items.
// If we are going to filter everything out, then just preserve the existing
// model (and all the previously filtered items), but switch over to soft
// selection.
var selection = UpdateSelectionHint.SoftSelected;
return new FilteredCompletionModel(
ImmutableArray<CompletionItemWithHighlight>.Empty, selectedItemIndex: 0,
filters, selection, centerSelection: true, uniqueItem: null);
}
private static ImmutableArray<CompletionFilterWithState> GetUpdatedFilters(
List<MatchResult<VSCompletionItem>> filteredList,
ImmutableArray<CompletionFilterWithState> filters)
{
// See which filters might be enabled based on the typed code
using var _ = PooledHashSet<CompletionFilter>.GetInstance(out var textFilteredFilters);
textFilteredFilters.AddRange(filteredList.SelectMany(n => n.EditorCompletionItem.Filters));
// When no items are available for a given filter, it becomes unavailable.
// Expanders always appear available as long as it's presented.
return filters.SelectAsArray(n => n.WithAvailability(n.Filter is CompletionExpander ? true : textFilteredFilters.Contains(n.Filter)));
}
/// <summary>
/// Given multiple possible chosen completion items, pick the one that has the
/// best MRU index, or the one with highest MatchPriority if none in MRU.
/// </summary>
private static RoslynCompletionItem GetBestCompletionItemBasedOnMRU(
ImmutableArray<RoslynCompletionItem> chosenItems, ImmutableArray<string> recentItems)
{
Debug.Assert(chosenItems.Length > 0);
// Try to find the chosen item has been most recently used.
var bestItem = chosenItems[0];
for (int i = 1, n = chosenItems.Length; i < n; i++)
{
var chosenItem = chosenItems[i];
var mruIndex1 = GetRecentItemIndex(recentItems, bestItem);
var mruIndex2 = GetRecentItemIndex(recentItems, chosenItem);
if ((mruIndex2 < mruIndex1) ||
(mruIndex2 == mruIndex1 && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem()))
{
bestItem = chosenItem;
}
}
// If our best item appeared in the MRU list, use it
if (GetRecentItemIndex(recentItems, bestItem) <= 0)
{
return bestItem;
}
// Otherwise use the chosen item that has the highest
// matchPriority.
for (int i = 1, n = chosenItems.Length; i < n; i++)
{
var chosenItem = chosenItems[i];
var bestItemPriority = bestItem.Rules.MatchPriority;
var currentItemPriority = chosenItem.Rules.MatchPriority;
if ((currentItemPriority > bestItemPriority) ||
((currentItemPriority == bestItemPriority) && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem()))
{
bestItem = chosenItem;
}
}
return bestItem;
}
private static int GetRecentItemIndex(ImmutableArray<string> recentItems, RoslynCompletionItem item)
{
var index = recentItems.IndexOf(item.FilterText);
return -index;
}
private static RoslynCompletionItem GetOrAddRoslynCompletionItem(VSCompletionItem vsItem)
{
if (!vsItem.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem))
{
roslynItem = RoslynCompletionItem.Create(
displayText: vsItem.DisplayText,
filterText: vsItem.FilterText,
sortText: vsItem.SortText,
displayTextSuffix: vsItem.Suffix);
vsItem.Properties.AddProperty(CompletionSource.RoslynItem, roslynItem);
}
return roslynItem;
}
private static bool TryCreateMatchResult(
CompletionHelper completionHelper,
VSCompletionItem item,
string filterText,
CompletionTriggerKind initialTriggerKind,
CompletionFilterReason filterReason,
ImmutableArray<string> recentItems,
bool highlightMatchingPortions,
int currentIndex,
out MatchResult<VSCompletionItem> matchResult)
{
var roslynItem = GetOrAddRoslynCompletionItem(item);
return CompletionHelper.TryCreateMatchResult(completionHelper, roslynItem, item, filterText, initialTriggerKind, filterReason, recentItems, highlightMatchingPortions, currentIndex, out matchResult);
}
// PERF: Create a singleton to avoid lambda allocation on hot path
private static readonly Func<TextSpan, RoslynCompletionItem, Span> s_highlightSpanGetter
= (span, item) => span.MoveTo(item.DisplayTextPrefix?.Length ?? 0).ToSpan();
private static bool IsHardSelection(
string filterText,
RoslynCompletionItem item,
bool matchedFilterText,
bool useSuggestionMode)
{
if (item == null || useSuggestionMode)
{
return false;
}
// We don't have a builder and we have a best match. Normally this will be hard
// selected, except for a few cases. Specifically, if no filter text has been
// provided, and this is not a preselect match then we will soft select it. This
// happens when the completion list comes up implicitly and there is something in
// the MRU list. In this case we do want to select it, but not with a hard
// selection. Otherwise you can end up with the following problem:
//
// dim i as integer =<space>
//
// Completion will comes up after = with 'integer' selected (Because of MRU). We do
// not want 'space' to commit this.
// If all that has been typed is punctuation, then don't hard select anything.
// It's possible the user is just typing language punctuation and selecting
// anything in the list will interfere. We only allow this if the filter text
// exactly matches something in the list already.
if (filterText.Length > 0 && IsAllPunctuation(filterText) && filterText != item.DisplayText)
{
return false;
}
// If the user hasn't actually typed anything, then don't hard select any item.
// The only exception to this is if the completion provider has requested the
// item be preselected.
if (filterText.Length == 0)
{
// Item didn't want to be hard selected with no filter text.
// So definitely soft select it.
if (item.Rules.SelectionBehavior != CompletionItemSelectionBehavior.HardSelection)
{
return false;
}
// Item did not ask to be preselected. So definitely soft select it.
if (item.Rules.MatchPriority == MatchPriority.Default)
{
return false;
}
}
// The user typed something, or the item asked to be preselected. In
// either case, don't soft select this.
Debug.Assert(filterText.Length > 0 || item.Rules.MatchPriority != MatchPriority.Default);
// If the user moved the caret left after they started typing, the 'best' match may not match at all
// against the full text span that this item would be replacing.
if (!matchedFilterText)
{
return false;
}
// There was either filter text, or this was a preselect match. In either case, we
// can hard select this.
return true;
}
private static bool IsAllPunctuation(string filterText)
{
foreach (var ch in filterText)
{
if (!char.IsPunctuation(ch))
{
return false;
}
}
return true;
}
/// <summary>
/// A potential filter character is something that can filter a completion lists and is
/// *guaranteed* to not be a commit character.
/// </summary>
private static bool IsPotentialFilterCharacter(char c)
{
// TODO(cyrusn): Actually use the right Unicode categories here.
return char.IsLetter(c)
|| char.IsNumber(c)
|| c == '_';
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/CSharp/Portable/CodeGen/EmitStatement.cs | // 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.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CSharp.Binder;
namespace Microsoft.CodeAnalysis.CSharp.CodeGen
{
internal partial class CodeGenerator
{
private void EmitStatement(BoundStatement statement)
{
switch (statement.Kind)
{
case BoundKind.Block:
EmitBlock((BoundBlock)statement);
break;
case BoundKind.Scope:
EmitScope((BoundScope)statement);
break;
case BoundKind.SequencePoint:
this.EmitSequencePointStatement((BoundSequencePoint)statement);
break;
case BoundKind.SequencePointWithSpan:
this.EmitSequencePointStatement((BoundSequencePointWithSpan)statement);
break;
case BoundKind.SavePreviousSequencePoint:
this.EmitSavePreviousSequencePoint((BoundSavePreviousSequencePoint)statement);
break;
case BoundKind.RestorePreviousSequencePoint:
this.EmitRestorePreviousSequencePoint((BoundRestorePreviousSequencePoint)statement);
break;
case BoundKind.StepThroughSequencePoint:
this.EmitStepThroughSequencePoint((BoundStepThroughSequencePoint)statement);
break;
case BoundKind.ExpressionStatement:
EmitExpression(((BoundExpressionStatement)statement).Expression, false);
break;
case BoundKind.StatementList:
EmitStatementList((BoundStatementList)statement);
break;
case BoundKind.ReturnStatement:
EmitReturnStatement((BoundReturnStatement)statement);
break;
case BoundKind.GotoStatement:
EmitGotoStatement((BoundGotoStatement)statement);
break;
case BoundKind.LabelStatement:
EmitLabelStatement((BoundLabelStatement)statement);
break;
case BoundKind.ConditionalGoto:
EmitConditionalGoto((BoundConditionalGoto)statement);
break;
case BoundKind.ThrowStatement:
EmitThrowStatement((BoundThrowStatement)statement);
break;
case BoundKind.TryStatement:
EmitTryStatement((BoundTryStatement)statement);
break;
case BoundKind.SwitchDispatch:
EmitSwitchDispatch((BoundSwitchDispatch)statement);
break;
case BoundKind.StateMachineScope:
EmitStateMachineScope((BoundStateMachineScope)statement);
break;
case BoundKind.NoOpStatement:
EmitNoOpStatement((BoundNoOpStatement)statement);
break;
default:
// Code gen should not be invoked if there are errors.
throw ExceptionUtilities.UnexpectedValue(statement.Kind);
}
#if DEBUG
if (_stackLocals == null || _stackLocals.Count == 0)
{
_builder.AssertStackEmpty();
}
#endif
ReleaseExpressionTemps();
}
private int EmitStatementAndCountInstructions(BoundStatement statement)
{
int n = _builder.InstructionsEmitted;
this.EmitStatement(statement);
return _builder.InstructionsEmitted - n;
}
private void EmitStatementList(BoundStatementList list)
{
for (int i = 0, n = list.Statements.Length; i < n; i++)
{
EmitStatement(list.Statements[i]);
}
}
private void EmitNoOpStatement(BoundNoOpStatement statement)
{
switch (statement.Flavor)
{
case NoOpStatementFlavor.Default:
if (_ilEmitStyle == ILEmitStyle.Debug)
{
_builder.EmitOpCode(ILOpCode.Nop);
}
break;
case NoOpStatementFlavor.AwaitYieldPoint:
Debug.Assert((_asyncYieldPoints == null) == (_asyncResumePoints == null));
if (_asyncYieldPoints == null)
{
_asyncYieldPoints = ArrayBuilder<int>.GetInstance();
_asyncResumePoints = ArrayBuilder<int>.GetInstance();
}
Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count);
_asyncYieldPoints.Add(_builder.AllocateILMarker());
break;
case NoOpStatementFlavor.AwaitResumePoint:
Debug.Assert(_asyncYieldPoints != null);
Debug.Assert(_asyncYieldPoints != null);
_asyncResumePoints.Add(_builder.AllocateILMarker());
Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count);
break;
default:
throw ExceptionUtilities.UnexpectedValue(statement.Flavor);
}
}
private void EmitThrowStatement(BoundThrowStatement node)
{
EmitThrow(node.ExpressionOpt);
}
private void EmitThrow(BoundExpression thrown)
{
if (thrown != null)
{
this.EmitExpression(thrown, true);
var exprType = thrown.Type;
// Expression type will be null for "throw null;".
if (exprType?.TypeKind == TypeKind.TypeParameter)
{
this.EmitBox(exprType, thrown.Syntax);
}
}
_builder.EmitThrow(isRethrow: thrown == null);
}
private void EmitConditionalGoto(BoundConditionalGoto boundConditionalGoto)
{
object label = boundConditionalGoto.Label;
Debug.Assert(label != null);
EmitCondBranch(boundConditionalGoto.Condition, ref label, boundConditionalGoto.JumpIfTrue);
}
// 3.17 The brfalse instruction transfers control to target if value (of type int32, int64, object reference, managed
//pointer, unmanaged pointer or native int) is zero (false). If value is non-zero (true), execution continues at
//the next instruction.
private static bool CanPassToBrfalse(TypeSymbol ts)
{
if (ts.IsEnumType())
{
// valid enums are all primitives
return true;
}
var tc = ts.PrimitiveTypeCode;
switch (tc)
{
case Microsoft.Cci.PrimitiveTypeCode.Float32:
case Microsoft.Cci.PrimitiveTypeCode.Float64:
return false;
case Microsoft.Cci.PrimitiveTypeCode.NotPrimitive:
// if this is a generic type param, verifier will want us to box
// EmitCondBranch knows that
return ts.IsReferenceType;
default:
Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Invalid);
Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Void);
return true;
}
}
private static BoundExpression TryReduce(BoundBinaryOperator condition, ref bool sense)
{
var opKind = condition.OperatorKind.Operator();
Debug.Assert(opKind == BinaryOperatorKind.Equal ||
opKind == BinaryOperatorKind.NotEqual);
BoundExpression nonConstOp;
BoundExpression constOp = (condition.Left.ConstantValue != null) ? condition.Left : null;
if (constOp != null)
{
nonConstOp = condition.Right;
}
else
{
constOp = (condition.Right.ConstantValue != null) ? condition.Right : null;
if (constOp == null)
{
return null;
}
nonConstOp = condition.Left;
}
var nonConstType = nonConstOp.Type;
if (!CanPassToBrfalse(nonConstType))
{
return null;
}
bool isBool = nonConstType.PrimitiveTypeCode == Microsoft.Cci.PrimitiveTypeCode.Boolean;
bool isZero = constOp.ConstantValue.IsDefaultValue;
// bool is special, only it can be compared to true and false...
if (!isBool && !isZero)
{
return null;
}
// if comparing to zero, flip the sense
if (isZero)
{
sense = !sense;
}
// if comparing != flip the sense
if (opKind == BinaryOperatorKind.NotEqual)
{
sense = !sense;
}
return nonConstOp;
}
private const int IL_OP_CODE_ROW_LENGTH = 4;
private static readonly ILOpCode[] s_condJumpOpCodes = new ILOpCode[]
{
// < <= > >=
ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Signed
ILOpCode.Bge, ILOpCode.Bgt, ILOpCode.Ble, ILOpCode.Blt, // Signed Invert
ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un, // Unsigned
ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Unsigned Invert
ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Float
ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Float Invert
};
/// <summary>
/// Produces opcode for a jump that corresponds to given operation and sense.
/// Also produces a reverse opcode - opcode for the same condition with inverted sense.
/// </summary>
private static ILOpCode CodeForJump(BoundBinaryOperator op, bool sense, out ILOpCode revOpCode)
{
int opIdx;
switch (op.OperatorKind.Operator())
{
case BinaryOperatorKind.Equal:
revOpCode = !sense ? ILOpCode.Beq : ILOpCode.Bne_un;
return sense ? ILOpCode.Beq : ILOpCode.Bne_un;
case BinaryOperatorKind.NotEqual:
revOpCode = !sense ? ILOpCode.Bne_un : ILOpCode.Beq;
return sense ? ILOpCode.Bne_un : ILOpCode.Beq;
case BinaryOperatorKind.LessThan:
opIdx = 0;
break;
case BinaryOperatorKind.LessThanOrEqual:
opIdx = 1;
break;
case BinaryOperatorKind.GreaterThan:
opIdx = 2;
break;
case BinaryOperatorKind.GreaterThanOrEqual:
opIdx = 3;
break;
default:
throw ExceptionUtilities.UnexpectedValue(op.OperatorKind.Operator());
}
if (IsUnsignedBinaryOperator(op))
{
opIdx += 2 * IL_OP_CODE_ROW_LENGTH; //unsigned
}
else if (IsFloat(op.OperatorKind))
{
opIdx += 4 * IL_OP_CODE_ROW_LENGTH; //float
}
int revOpIdx = opIdx;
if (!sense)
{
opIdx += IL_OP_CODE_ROW_LENGTH; //invert op
}
else
{
revOpIdx += IL_OP_CODE_ROW_LENGTH; //invert rev
}
revOpCode = s_condJumpOpCodes[revOpIdx];
return s_condJumpOpCodes[opIdx];
}
// generate a jump to dest if (condition == sense) is true
private void EmitCondBranch(BoundExpression condition, ref object dest, bool sense)
{
_recursionDepth++;
if (_recursionDepth > 1)
{
StackGuard.EnsureSufficientExecutionStack(_recursionDepth);
EmitCondBranchCore(condition, ref dest, sense);
}
else
{
EmitCondBranchCoreWithStackGuard(condition, ref dest, sense);
}
_recursionDepth--;
}
private void EmitCondBranchCoreWithStackGuard(BoundExpression condition, ref object dest, bool sense)
{
Debug.Assert(_recursionDepth == 1);
try
{
EmitCondBranchCore(condition, ref dest, sense);
Debug.Assert(_recursionDepth == 1);
}
catch (InsufficientExecutionStackException)
{
_diagnostics.Add(ErrorCode.ERR_InsufficientStack,
BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(condition));
throw new EmitCancelledException();
}
}
private void EmitCondBranchCore(BoundExpression condition, ref object dest, bool sense)
{
oneMoreTime:
ILOpCode ilcode;
if (condition.ConstantValue != null)
{
bool taken = condition.ConstantValue.IsDefaultValue != sense;
if (taken)
{
dest = dest ?? new object();
_builder.EmitBranch(ILOpCode.Br, dest);
}
else
{
// otherwise this branch will never be taken, so just fall through...
}
return;
}
switch (condition.Kind)
{
case BoundKind.BinaryOperator:
var binOp = (BoundBinaryOperator)condition;
bool testBothArgs = sense;
switch (binOp.OperatorKind.OperatorWithLogical())
{
case BinaryOperatorKind.LogicalOr:
testBothArgs = !testBothArgs;
// Fall through
goto case BinaryOperatorKind.LogicalAnd;
case BinaryOperatorKind.LogicalAnd:
if (testBothArgs)
{
// gotoif(a != sense) fallThrough
// gotoif(b == sense) dest
// fallThrough:
object fallThrough = null;
EmitCondBranch(binOp.Left, ref fallThrough, !sense);
EmitCondBranch(binOp.Right, ref dest, sense);
if (fallThrough != null)
{
_builder.MarkLabel(fallThrough);
}
}
else
{
// gotoif(a == sense) labDest
// gotoif(b == sense) labDest
EmitCondBranch(binOp.Left, ref dest, sense);
condition = binOp.Right;
goto oneMoreTime;
}
return;
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
var reduced = TryReduce(binOp, ref sense);
if (reduced != null)
{
condition = reduced;
goto oneMoreTime;
}
// Fall through
goto case BinaryOperatorKind.LessThan;
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.LessThanOrEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.GreaterThanOrEqual:
EmitExpression(binOp.Left, true);
EmitExpression(binOp.Right, true);
ILOpCode revOpCode;
ilcode = CodeForJump(binOp, sense, out revOpCode);
dest = dest ?? new object();
_builder.EmitBranch(ilcode, dest, revOpCode);
return;
}
// none of above.
// then it is regular binary expression - Or, And, Xor ...
goto default;
case BoundKind.LoweredConditionalAccess:
{
var ca = (BoundLoweredConditionalAccess)condition;
var receiver = ca.Receiver;
var receiverType = receiver.Type;
// we need a copy if we deal with nonlocal value (to capture the value)
// or if we deal with stack local (reads are destructive)
var complexCase = !receiverType.IsReferenceType ||
LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) ||
(receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol)) ||
(ca.WhenNullOpt?.IsDefaultValue() == false);
if (complexCase)
{
goto default;
}
if (sense)
{
// gotoif(receiver != null) fallThrough
// gotoif(receiver.Access) dest
// fallThrough:
object fallThrough = null;
EmitCondBranch(receiver, ref fallThrough, sense: false);
// receiver is a reference type, and we only intend to read it
EmitReceiverRef(receiver, AddressKind.ReadOnly);
EmitCondBranch(ca.WhenNotNull, ref dest, sense: true);
if (fallThrough != null)
{
_builder.MarkLabel(fallThrough);
}
}
else
{
// gotoif(receiver == null) labDest
// gotoif(!receiver.Access) labDest
EmitCondBranch(receiver, ref dest, sense: false);
// receiver is a reference type, and we only intend to read it
EmitReceiverRef(receiver, AddressKind.ReadOnly);
condition = ca.WhenNotNull;
goto oneMoreTime;
}
}
return;
case BoundKind.UnaryOperator:
var unOp = (BoundUnaryOperator)condition;
if (unOp.OperatorKind == UnaryOperatorKind.BoolLogicalNegation)
{
sense = !sense;
condition = unOp.Operand;
goto oneMoreTime;
}
goto default;
case BoundKind.IsOperator:
var isOp = (BoundIsOperator)condition;
var operand = isOp.Operand;
EmitExpression(operand, true);
Debug.Assert((object)operand.Type != null);
if (!operand.Type.IsVerifierReference())
{
// box the operand for isinst if it is not a verifier reference
EmitBox(operand.Type, operand.Syntax);
}
_builder.EmitOpCode(ILOpCode.Isinst);
EmitSymbolToken(isOp.TargetType.Type, isOp.TargetType.Syntax);
ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse;
dest = dest ?? new object();
_builder.EmitBranch(ilcode, dest);
return;
case BoundKind.Sequence:
var seq = (BoundSequence)condition;
EmitSequenceCondBranch(seq, ref dest, sense);
return;
default:
EmitExpression(condition, true);
var conditionType = condition.Type;
if (conditionType.IsReferenceType && !conditionType.IsVerifierReference())
{
EmitBox(conditionType, condition.Syntax);
}
ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse;
dest = dest ?? new object();
_builder.EmitBranch(ilcode, dest);
return;
}
}
private void EmitSequenceCondBranch(BoundSequence sequence, ref object dest, bool sense)
{
DefineLocals(sequence);
EmitSideEffects(sequence);
EmitCondBranch(sequence.Value, ref dest, sense);
// sequence is used as a value, can release all locals
FreeLocals(sequence);
}
private void EmitLabelStatement(BoundLabelStatement boundLabelStatement)
{
_builder.MarkLabel(boundLabelStatement.Label);
}
private void EmitGotoStatement(BoundGotoStatement boundGotoStatement)
{
_builder.EmitBranch(ILOpCode.Br, boundGotoStatement.Label);
}
// used by HandleReturn method which tries to inject
// indirect ret sequence as a last statement in the block
// that is the last statement of the current method
// NOTE: it is important that there is no code after this "ret"
// it is desirable, for debug purposes, that this ret is emitted inside top level { }
private bool IsLastBlockInMethod(BoundBlock block)
{
if (_boundBody == block)
{
return true;
}
//sometimes top level node is a statement list containing
//epilogue and then a block. If we are having that block, it will do.
var list = _boundBody as BoundStatementList;
if (list != null && list.Statements.LastOrDefault() == block)
{
return true;
}
return false;
}
private void EmitBlock(BoundBlock block)
{
var hasLocals = !block.Locals.IsEmpty;
if (hasLocals)
{
_builder.OpenLocalScope();
foreach (var local in block.Locals)
{
Debug.Assert(local.RefKind == RefKind.None || local.SynthesizedKind.IsLongLived(),
"A ref local ended up in a block and claims it is shortlived. That is dangerous. Are we sure it is short lived?");
var declaringReferences = local.DeclaringSyntaxReferences;
DefineLocal(local, !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : block.Syntax);
}
}
EmitStatements(block.Statements);
if (_indirectReturnState == IndirectReturnState.Needed &&
IsLastBlockInMethod(block))
{
HandleReturn();
}
if (hasLocals)
{
foreach (var local in block.Locals)
{
FreeLocal(local);
}
_builder.CloseLocalScope();
}
}
private void EmitStatements(ImmutableArray<BoundStatement> statements)
{
foreach (var statement in statements)
{
EmitStatement(statement);
}
}
private void EmitScope(BoundScope block)
{
Debug.Assert(!block.Locals.IsEmpty);
_builder.OpenLocalScope();
foreach (var local in block.Locals)
{
Debug.Assert(local.Name != null);
Debug.Assert(local.SynthesizedKind == SynthesizedLocalKind.UserDefined &&
(local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchSection || local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchExpressionArm));
if (!local.IsConst && !IsStackLocal(local))
{
_builder.AddLocalToScope(_builder.LocalSlotManager.GetLocal(local));
}
}
EmitStatements(block.Statements);
_builder.CloseLocalScope();
}
private void EmitStateMachineScope(BoundStateMachineScope scope)
{
_builder.OpenLocalScope(ScopeType.StateMachineVariable);
foreach (var field in scope.Fields)
{
if (field.SlotIndex >= 0)
{
_builder.DefineUserDefinedStateMachineHoistedLocal(field.SlotIndex);
}
}
EmitStatement(scope.Statement);
_builder.CloseLocalScope();
}
// There are two ways a value can be returned from a function:
// - Using ret opcode
// - Store return value if any to a predefined temp and jump to the epilogue block
// Sometimes ret is not an option (try/catch etc.). We also do this when emitting
// debuggable code. This function is a stub for the logic that decides that.
private bool ShouldUseIndirectReturn()
{
// If the method/lambda body is a block we define a sequence point for the closing brace of the body
// and associate it with the ret instruction. If there is a return statement we need to store the value
// to a long-lived synthesized local since a sequence point requires an empty evaluation stack.
//
// The emitted pattern is:
// <evaluate return statement expression>
// stloc $ReturnValue
// ldloc $ReturnValue // sequence point
// ret
//
// Do not emit this pattern if the method doesn't include user code or doesn't have a block body.
return _ilEmitStyle == ILEmitStyle.Debug && _method.GenerateDebugInfo && _methodBodySyntaxOpt?.IsKind(SyntaxKind.Block) == true ||
_builder.InExceptionHandler;
}
// Compiler generated return mapped to a block is very likely the synthetic return
// that was added at the end of the last block of a void method by analysis.
// This is likely to be the last return in the method, so if we have not yet
// emitted return sequence, it is convenient to do it right here (if we can).
private bool CanHandleReturnLabel(BoundReturnStatement boundReturnStatement)
{
return boundReturnStatement.WasCompilerGenerated &&
(boundReturnStatement.Syntax.IsKind(SyntaxKind.Block) || _method?.IsImplicitConstructor == true) &&
!_builder.InExceptionHandler;
}
private void EmitReturnStatement(BoundReturnStatement boundReturnStatement)
{
var expressionOpt = boundReturnStatement.ExpressionOpt;
if (boundReturnStatement.RefKind == RefKind.None)
{
this.EmitExpression(expressionOpt, true);
}
else
{
// NOTE: passing "ReadOnlyStrict" here.
// we should never return an address of a copy
var unexpectedTemp = this.EmitAddress(expressionOpt, this._method.RefKind == RefKind.RefReadOnly ? AddressKind.ReadOnlyStrict : AddressKind.Writeable);
Debug.Assert(unexpectedTemp == null, "ref-returning a temp?");
}
if (ShouldUseIndirectReturn())
{
if (expressionOpt != null)
{
_builder.EmitLocalStore(LazyReturnTemp);
}
if (_indirectReturnState != IndirectReturnState.Emitted && CanHandleReturnLabel(boundReturnStatement))
{
HandleReturn();
}
else
{
_builder.EmitBranch(ILOpCode.Br, s_returnLabel);
if (_indirectReturnState == IndirectReturnState.NotNeeded)
{
_indirectReturnState = IndirectReturnState.Needed;
}
}
}
else
{
if (_indirectReturnState == IndirectReturnState.Needed && CanHandleReturnLabel(boundReturnStatement))
{
if (expressionOpt != null)
{
_builder.EmitLocalStore(LazyReturnTemp);
}
HandleReturn();
}
else
{
if (expressionOpt != null)
{
// Ensure the return type has been translated. (Necessary
// for cases of untranslated anonymous types.)
_module.Translate(expressionOpt.Type, boundReturnStatement.Syntax, _diagnostics);
}
_builder.EmitRet(expressionOpt == null);
}
}
}
private void EmitTryStatement(BoundTryStatement statement, bool emitCatchesOnly = false)
{
Debug.Assert(!statement.CatchBlocks.IsDefault);
// Stack must be empty at beginning of try block.
_builder.AssertStackEmpty();
// IL requires catches and finally block to be distinct try
// blocks so if the source contained both a catch and
// a finally, nested scopes are emitted.
bool emitNestedScopes = (!emitCatchesOnly &&
(statement.CatchBlocks.Length > 0) &&
(statement.FinallyBlockOpt != null));
_builder.OpenLocalScope(ScopeType.TryCatchFinally);
_builder.OpenLocalScope(ScopeType.Try);
// IL requires catches and finally block to be distinct try
// blocks so if the source contained both a catch and
// a finally, nested scopes are emitted.
_tryNestingLevel++;
if (emitNestedScopes)
{
EmitTryStatement(statement, emitCatchesOnly: true);
}
else
{
EmitBlock(statement.TryBlock);
}
_tryNestingLevel--;
// Close the Try scope
_builder.CloseLocalScope();
if (!emitNestedScopes)
{
foreach (var catchBlock in statement.CatchBlocks)
{
EmitCatchBlock(catchBlock);
}
}
if (!emitCatchesOnly && (statement.FinallyBlockOpt != null))
{
_builder.OpenLocalScope(statement.PreferFaultHandler ? ScopeType.Fault : ScopeType.Finally);
EmitBlock(statement.FinallyBlockOpt);
// close Finally scope
_builder.CloseLocalScope();
// close the whole try statement scope
_builder.CloseLocalScope();
// in a case where we emit surrogate Finally using Fault, we emit code like this
//
// try{
// . . .
// } fault {
// finallyBlock;
// }
// finallyBlock;
//
// This is where the second copy of finallyBlock is emitted.
if (statement.PreferFaultHandler)
{
var finallyClone = FinallyCloner.MakeFinallyClone(statement);
EmitBlock(finallyClone);
}
}
else
{
// close the whole try statement scope
_builder.CloseLocalScope();
}
}
/// <remarks>
/// The interesting part in the following method is the support for exception filters.
/// === Example:
///
/// try
/// {
/// TryBlock
/// }
/// catch (ExceptionType ex) when (Condition)
/// {
/// Handler
/// }
///
/// gets emitted as something like ===>
///
/// Try
/// TryBlock
/// Filter
/// var tmp = Pop() as {ExceptionType}
/// if (tmp == null)
/// {
/// Push 0
/// }
/// else
/// {
/// ex = tmp
/// Push Condition ? 1 : 0
/// }
/// End Filter // leaves 1 or 0 on the stack
/// Catch // gets called after finalization of nested exception frames if condition above produced 1
/// Pop // CLR pushes the exception object again
/// variable ex can be used here
/// Handler
/// EndCatch
///
/// When evaluating `Condition` requires additional statements be executed first, those
/// statements are stored in `catchBlock.ExceptionFilterPrologueOpt` and emitted before the condition.
/// </remarks>
private void EmitCatchBlock(BoundCatchBlock catchBlock)
{
object typeCheckFailedLabel = null;
_builder.AdjustStack(1); // Account for exception on the stack.
// Open appropriate exception handler scope. (Catch or Filter)
// if it is a Filter, emit prologue that checks if the type on the stack
// converts to what we want.
if (catchBlock.ExceptionFilterOpt == null)
{
var exceptionType = ((object)catchBlock.ExceptionTypeOpt != null) ?
_module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics) :
_module.GetSpecialType(SpecialType.System_Object, catchBlock.Syntax, _diagnostics);
_builder.OpenLocalScope(ScopeType.Catch, exceptionType);
RecordAsyncCatchHandlerOffset(catchBlock);
// Dev12 inserts the sequence point on catch clause without a filter, just before
// the exception object is assigned to the variable.
//
// Also in Dev12 the exception variable scope span starts right after the stloc instruction and
// ends right before leave instruction. So when stopped at the sequence point Dev12 inserts,
// the exception variable is not visible.
if (_emitPdbSequencePoints)
{
var syntax = catchBlock.Syntax as CatchClauseSyntax;
if (syntax != null)
{
TextSpan spSpan;
var declaration = syntax.Declaration;
if (declaration == null)
{
spSpan = syntax.CatchKeyword.Span;
}
else
{
spSpan = TextSpan.FromBounds(syntax.SpanStart, syntax.Declaration.Span.End);
}
this.EmitSequencePoint(catchBlock.SyntaxTree, spSpan);
}
}
}
else
{
_builder.OpenLocalScope(ScopeType.Filter);
RecordAsyncCatchHandlerOffset(catchBlock);
// Filtering starts with simulating regular catch through a
// type check. If this is not our type then we are done.
var typeCheckPassedLabel = new object();
typeCheckFailedLabel = new object();
if ((object)catchBlock.ExceptionTypeOpt != null)
{
var exceptionType = _module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics);
_builder.EmitOpCode(ILOpCode.Isinst);
_builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics);
_builder.EmitOpCode(ILOpCode.Dup);
_builder.EmitBranch(ILOpCode.Brtrue, typeCheckPassedLabel);
_builder.EmitOpCode(ILOpCode.Pop);
_builder.EmitIntConstant(0);
_builder.EmitBranch(ILOpCode.Br, typeCheckFailedLabel);
}
else
{
// no formal exception type means we always pass the check
}
_builder.MarkLabel(typeCheckPassedLabel);
}
foreach (var local in catchBlock.Locals)
{
var declaringReferences = local.DeclaringSyntaxReferences;
var localSyntax = !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : catchBlock.Syntax;
DefineLocal(local, localSyntax);
}
var exceptionSourceOpt = catchBlock.ExceptionSourceOpt;
if (exceptionSourceOpt != null)
{
// here we have our exception on the stack in a form of a reference type (O)
// it means that we have to "unbox" it before storing to the local
// if exception's type is a generic type parameter.
if (!exceptionSourceOpt.Type.IsVerifierReference())
{
Debug.Assert(exceptionSourceOpt.Type.IsTypeParameter()); // only expecting type parameters
_builder.EmitOpCode(ILOpCode.Unbox_any);
EmitSymbolToken(exceptionSourceOpt.Type, exceptionSourceOpt.Syntax);
}
BoundExpression exceptionSource = exceptionSourceOpt;
while (exceptionSource.Kind == BoundKind.Sequence)
{
var seq = (BoundSequence)exceptionSource;
Debug.Assert(seq.Locals.IsDefaultOrEmpty);
EmitSideEffects(seq);
exceptionSource = seq.Value;
}
switch (exceptionSource.Kind)
{
case BoundKind.Local:
var exceptionSourceLocal = (BoundLocal)exceptionSource;
Debug.Assert(exceptionSourceLocal.LocalSymbol.RefKind == RefKind.None);
if (!IsStackLocal(exceptionSourceLocal.LocalSymbol))
{
_builder.EmitLocalStore(GetLocal(exceptionSourceLocal));
}
break;
case BoundKind.FieldAccess:
var left = (BoundFieldAccess)exceptionSource;
Debug.Assert(!left.FieldSymbol.IsStatic, "Not supported");
Debug.Assert(!left.ReceiverOpt.Type.IsTypeParameter());
var stateMachineField = left.FieldSymbol as StateMachineFieldSymbol;
if (((object)stateMachineField != null) && (stateMachineField.SlotIndex >= 0))
{
_builder.DefineUserDefinedStateMachineHoistedLocal(stateMachineField.SlotIndex);
}
// When assigning to a field
// we need to push param address below the exception
var temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax);
_builder.EmitLocalStore(temp);
var receiverTemp = EmitReceiverRef(left.ReceiverOpt, AddressKind.Writeable);
Debug.Assert(receiverTemp == null);
_builder.EmitLocalLoad(temp);
FreeTemp(temp);
EmitFieldStore(left);
break;
default:
throw ExceptionUtilities.UnexpectedValue(exceptionSource.Kind);
}
}
else
{
_builder.EmitOpCode(ILOpCode.Pop);
}
if (catchBlock.ExceptionFilterPrologueOpt != null)
{
Debug.Assert(_builder.IsStackEmpty);
EmitStatements(catchBlock.ExceptionFilterPrologueOpt.Statements);
}
// Emit the actual filter expression, if we have one, and normalize
// results.
if (catchBlock.ExceptionFilterOpt != null)
{
EmitCondExpr(catchBlock.ExceptionFilterOpt, true);
// Normalize the return value because values other than 0 or 1
// produce unspecified results.
_builder.EmitIntConstant(0);
_builder.EmitOpCode(ILOpCode.Cgt_un);
_builder.MarkLabel(typeCheckFailedLabel);
// Now we are starting the actual handler
_builder.MarkFilterConditionEnd();
// Pop the exception; it should have already been stored to the
// variable by the filter.
_builder.EmitOpCode(ILOpCode.Pop);
}
EmitBlock(catchBlock.Body);
_builder.CloseLocalScope();
}
private void RecordAsyncCatchHandlerOffset(BoundCatchBlock catchBlock)
{
if (catchBlock.IsSynthesizedAsyncCatchAll)
{
Debug.Assert(_asyncCatchHandlerOffset < 0); // only one expected
_asyncCatchHandlerOffset = _builder.AllocateILMarker();
}
}
private void EmitSwitchDispatch(BoundSwitchDispatch dispatch)
{
// Switch expression must have a valid switch governing type
Debug.Assert((object)dispatch.Expression.Type != null);
Debug.Assert(dispatch.Expression.Type.IsValidV6SwitchGoverningType());
// We must have rewritten nullable switch expression into non-nullable constructs.
Debug.Assert(!dispatch.Expression.Type.IsNullableType());
// This must be used only for nontrivial dispatches.
Debug.Assert(dispatch.Cases.Any());
EmitSwitchHeader(
dispatch.Expression,
dispatch.Cases.Select(p => new KeyValuePair<ConstantValue, object>(p.value, p.label)).ToArray(),
dispatch.DefaultLabel,
dispatch.EqualityMethod);
}
private void EmitSwitchHeader(
BoundExpression expression,
KeyValuePair<ConstantValue, object>[] switchCaseLabels,
LabelSymbol fallThroughLabel,
MethodSymbol equalityMethod)
{
Debug.Assert(expression.ConstantValue == null);
Debug.Assert((object)expression.Type != null &&
expression.Type.IsValidV6SwitchGoverningType());
Debug.Assert(switchCaseLabels.Length > 0);
Debug.Assert(switchCaseLabels != null);
LocalDefinition temp = null;
LocalOrParameter key;
BoundSequence sequence = null;
if (expression.Kind == BoundKind.Sequence)
{
sequence = (BoundSequence)expression;
DefineLocals(sequence);
EmitSideEffects(sequence);
expression = sequence.Value;
}
if (expression.Kind == BoundKind.SequencePointExpression)
{
var sequencePointExpression = (BoundSequencePointExpression)expression;
EmitSequencePoint(sequencePointExpression);
expression = sequencePointExpression.Expression;
}
switch (expression.Kind)
{
case BoundKind.Local:
var local = ((BoundLocal)expression).LocalSymbol;
if (local.RefKind == RefKind.None && !IsStackLocal(local))
{
key = this.GetLocal(local);
break;
}
goto default;
case BoundKind.Parameter:
var parameter = (BoundParameter)expression;
if (parameter.ParameterSymbol.RefKind == RefKind.None)
{
key = ParameterSlot(parameter);
break;
}
goto default;
default:
EmitExpression(expression, true);
temp = AllocateTemp(expression.Type, expression.Syntax);
_builder.EmitLocalStore(temp);
key = temp;
break;
}
// Emit switch jump table
if (expression.Type.SpecialType != SpecialType.System_String)
{
_builder.EmitIntegerSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Type.EnumUnderlyingTypeOrSelf().PrimitiveTypeCode);
}
else
{
this.EmitStringSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Syntax, equalityMethod);
}
if (temp != null)
{
FreeTemp(temp);
}
if (sequence != null)
{
// sequence was used as a value, can release all its locals.
FreeLocals(sequence);
}
}
private void EmitStringSwitchJumpTable(
KeyValuePair<ConstantValue, object>[] switchCaseLabels,
LabelSymbol fallThroughLabel,
LocalOrParameter key,
SyntaxNode syntaxNode,
MethodSymbol equalityMethod)
{
LocalDefinition keyHash = null;
// Condition is necessary, but not sufficient (e.g. might be missing a special or well-known member).
if (SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(_module, switchCaseLabels.Length))
{
Debug.Assert(_module.SupportsPrivateImplClass);
var privateImplClass = _module.GetPrivateImplClass(syntaxNode, _diagnostics);
Cci.IReference stringHashMethodRef = privateImplClass.GetMethod(PrivateImplementationDetails.SynthesizedStringHashFunctionName);
// Heuristics and well-known member availability determine the existence
// of this helper. Rather than reproduce that (language-specific) logic here,
// we simply check for the information we really want - whether the helper is
// available.
if (stringHashMethodRef != null)
{
// static uint ComputeStringHash(string s)
// pop 1 (s)
// push 1 (uint return value)
// stackAdjustment = (pushCount - popCount) = 0
_builder.EmitLoad(key);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0);
_builder.EmitToken(stringHashMethodRef, syntaxNode, _diagnostics);
var UInt32Type = _module.Compilation.GetSpecialType(SpecialType.System_UInt32);
keyHash = AllocateTemp(UInt32Type, syntaxNode);
_builder.EmitLocalStore(keyHash);
}
}
Cci.IReference stringEqualityMethodRef = _module.Translate(equalityMethod, syntaxNode, _diagnostics);
Cci.IMethodReference stringLengthRef = null;
var stringLengthMethod = _module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__Length) as MethodSymbol;
if (stringLengthMethod != null && !stringLengthMethod.HasUseSiteError)
{
stringLengthRef = _module.Translate(stringLengthMethod, syntaxNode, _diagnostics);
}
SwitchStringJumpTableEmitter.EmitStringCompareAndBranch emitStringCondBranchDelegate =
(keyArg, stringConstant, targetLabel) =>
{
if (stringConstant == ConstantValue.Null)
{
// if (key == null)
// goto targetLabel
_builder.EmitLoad(keyArg);
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue);
}
else if (stringConstant.StringValue.Length == 0 && stringLengthRef != null)
{
// if (key != null && key.Length == 0)
// goto targetLabel
object skipToNext = new object();
_builder.EmitLoad(keyArg);
_builder.EmitBranch(ILOpCode.Brfalse, skipToNext, ILOpCode.Brtrue);
_builder.EmitLoad(keyArg);
// Stack: key --> length
_builder.EmitOpCode(ILOpCode.Call, 0);
var diag = DiagnosticBag.GetInstance();
_builder.EmitToken(stringLengthRef, null, diag);
Debug.Assert(diag.IsEmptyWithoutResolution);
diag.Free();
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue);
_builder.MarkLabel(skipToNext);
}
else
{
this.EmitStringCompareAndBranch(key, syntaxNode, stringConstant, targetLabel, stringEqualityMethodRef);
}
};
_builder.EmitStringSwitchJumpTable(
caseLabels: switchCaseLabels,
fallThroughLabel: fallThroughLabel,
key: key,
keyHash: keyHash,
emitStringCondBranchDelegate: emitStringCondBranchDelegate,
computeStringHashcodeDelegate: SynthesizedStringSwitchHashMethod.ComputeStringHash);
if (keyHash != null)
{
FreeTemp(keyHash);
}
}
/// <summary>
/// Delegate to emit string compare call and conditional branch based on the compare result.
/// </summary>
/// <param name="key">Key to compare</param>
/// <param name="syntaxNode">Node for diagnostics.</param>
/// <param name="stringConstant">Case constant to compare the key against</param>
/// <param name="targetLabel">Target label to branch to if key = stringConstant</param>
/// <param name="stringEqualityMethodRef">String equality method</param>
private void EmitStringCompareAndBranch(LocalOrParameter key, SyntaxNode syntaxNode, ConstantValue stringConstant, object targetLabel, Microsoft.Cci.IReference stringEqualityMethodRef)
{
// Emit compare and branch:
// if (key == stringConstant)
// goto targetLabel;
Debug.Assert(stringEqualityMethodRef != null);
#if DEBUG
var assertDiagnostics = DiagnosticBag.GetInstance();
Debug.Assert(stringEqualityMethodRef == _module.Translate((MethodSymbol)_module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__op_Equality), (CSharpSyntaxNode)syntaxNode, assertDiagnostics));
assertDiagnostics.Free();
#endif
// static bool String.Equals(string a, string b)
// pop 2 (a, b)
// push 1 (bool return value)
// stackAdjustment = (pushCount - popCount) = -1
_builder.EmitLoad(key);
_builder.EmitConstantValue(stringConstant);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1);
_builder.EmitToken(stringEqualityMethodRef, syntaxNode, _diagnostics);
// Branch to targetLabel if String.Equals returned true.
_builder.EmitBranch(ILOpCode.Brtrue, targetLabel, ILOpCode.Brfalse);
}
/// <summary>
/// Gets already declared and initialized local.
/// </summary>
private LocalDefinition GetLocal(BoundLocal localExpression)
{
var symbol = localExpression.LocalSymbol;
return GetLocal(symbol);
}
private LocalDefinition GetLocal(LocalSymbol symbol)
{
return _builder.LocalSlotManager.GetLocal(symbol);
}
private LocalDefinition DefineLocal(LocalSymbol local, SyntaxNode syntaxNode)
{
var dynamicTransformFlags = !local.IsCompilerGenerated && local.Type.ContainsDynamic() ?
CSharpCompilation.DynamicTransformsEncoder.Encode(local.Type, RefKind.None, 0) :
ImmutableArray<bool>.Empty;
var tupleElementNames = !local.IsCompilerGenerated && local.Type.ContainsTupleNames() ?
CSharpCompilation.TupleNamesEncoder.Encode(local.Type) :
ImmutableArray<string>.Empty;
if (local.IsConst)
{
Debug.Assert(local.HasConstantValue);
MetadataConstant compileTimeValue = _module.CreateConstant(local.Type, local.ConstantValue, syntaxNode, _diagnostics);
LocalConstantDefinition localConstantDef = new LocalConstantDefinition(
local.Name,
local.Locations.FirstOrDefault() ?? Location.None,
compileTimeValue,
dynamicTransformFlags: dynamicTransformFlags,
tupleElementNames: tupleElementNames);
_builder.AddLocalConstantToScope(localConstantDef);
return null;
}
if (IsStackLocal(local))
{
return null;
}
LocalSlotConstraints constraints;
Cci.ITypeReference translatedType;
if (local.DeclarationKind == LocalDeclarationKind.FixedVariable && local.IsPinned) // Excludes pointer local and string local in fixed string case.
{
Debug.Assert(local.RefKind == RefKind.None);
Debug.Assert(local.TypeWithAnnotations.Type.IsPointerType());
constraints = LocalSlotConstraints.ByRef | LocalSlotConstraints.Pinned;
PointerTypeSymbol pointerType = (PointerTypeSymbol)local.Type;
TypeSymbol pointedAtType = pointerType.PointedAtType;
// We can't declare a reference to void, so if the pointed-at type is void, use native int
// (represented here by IntPtr) instead.
translatedType = pointedAtType.IsVoidType()
? _module.GetSpecialType(SpecialType.System_IntPtr, syntaxNode, _diagnostics)
: _module.Translate(pointedAtType, syntaxNode, _diagnostics);
}
else
{
constraints = (local.IsPinned ? LocalSlotConstraints.Pinned : LocalSlotConstraints.None) |
(local.RefKind != RefKind.None ? LocalSlotConstraints.ByRef : LocalSlotConstraints.None);
translatedType = _module.Translate(local.Type, syntaxNode, _diagnostics);
}
// Even though we don't need the token immediately, we will need it later when signature for the local is emitted.
// Also, requesting the token has side-effect of registering types used, which is critical for embedded types (NoPia, VBCore, etc).
_module.GetFakeSymbolTokenForIL(translatedType, syntaxNode, _diagnostics);
LocalDebugId localId;
var name = GetLocalDebugName(local, out localId);
var localDef = _builder.LocalSlotManager.DeclareLocal(
type: translatedType,
symbol: local,
name: name,
kind: local.SynthesizedKind,
id: localId,
pdbAttributes: local.SynthesizedKind.PdbAttributes(),
constraints: constraints,
dynamicTransformFlags: dynamicTransformFlags,
tupleElementNames: tupleElementNames,
isSlotReusable: local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release));
// If named, add it to the local debug scope.
if (localDef.Name != null &&
!(local.SynthesizedKind == SynthesizedLocalKind.UserDefined &&
// Visibility scope of such locals is represented by BoundScope node.
(local.ScopeDesignatorOpt?.Kind() is SyntaxKind.SwitchSection or SyntaxKind.SwitchExpressionArm)))
{
_builder.AddLocalToScope(localDef);
}
return localDef;
}
/// <summary>
/// Gets the name and id of the local that are going to be generated into the debug metadata.
/// </summary>
private string GetLocalDebugName(ILocalSymbolInternal local, out LocalDebugId localId)
{
localId = LocalDebugId.None;
if (local.IsImportedFromMetadata)
{
return local.Name;
}
var localKind = local.SynthesizedKind;
// only user-defined locals should be named during lowering:
Debug.Assert((local.Name == null) == (localKind != SynthesizedLocalKind.UserDefined));
// Generating debug names for instrumentation payloads should be allowed, as described in https://github.com/dotnet/roslyn/issues/11024.
// For now, skip naming locals generated by instrumentation as they might not have a local syntax offset.
// Locals generated by instrumentation might exist in methods which do not contain a body (auto property initializers).
if (!localKind.IsLongLived() || localKind == SynthesizedLocalKind.InstrumentationPayload)
{
return null;
}
if (_ilEmitStyle == ILEmitStyle.Debug)
{
var syntax = local.GetDeclaratorSyntax();
int syntaxOffset = _method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(syntax), syntax.SyntaxTree);
int ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(localKind, syntaxOffset);
// user-defined locals should have 0 ordinal:
Debug.Assert(ordinal == 0 || localKind != SynthesizedLocalKind.UserDefined);
localId = new LocalDebugId(syntaxOffset, ordinal);
}
return local.Name ?? GeneratedNames.MakeSynthesizedLocalName(localKind, ref _uniqueNameId);
}
private bool IsSlotReusable(LocalSymbol local)
{
return local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release);
}
/// <summary>
/// Releases a local.
/// </summary>
private void FreeLocal(LocalSymbol local)
{
// TODO: releasing named locals is NYI.
if (local.Name == null && IsSlotReusable(local) && !IsStackLocal(local))
{
_builder.LocalSlotManager.FreeLocal(local);
}
}
/// <summary>
/// Allocates a temp without identity.
/// </summary>
private LocalDefinition AllocateTemp(TypeSymbol type, SyntaxNode syntaxNode, LocalSlotConstraints slotConstraints = LocalSlotConstraints.None)
{
return _builder.LocalSlotManager.AllocateSlot(
_module.Translate(type, syntaxNode, _diagnostics),
slotConstraints);
}
/// <summary>
/// Frees a temp.
/// </summary>
private void FreeTemp(LocalDefinition temp)
{
_builder.LocalSlotManager.FreeSlot(temp);
}
/// <summary>
/// Frees an optional temp.
/// </summary>
private void FreeOptTemp(LocalDefinition temp)
{
if (temp != null)
{
FreeTemp(temp);
}
}
/// <summary>
/// Clones all labels used in a finally block.
/// This allows creating an emittable clone of finally.
/// It is safe to do because no branches can go in or out of the finally handler.
/// </summary>
private class FinallyCloner : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
private Dictionary<LabelSymbol, GeneratedLabelSymbol> _labelClones;
private FinallyCloner() { }
/// <summary>
/// The argument is BoundTryStatement (and not a BoundBlock) specifically
/// to support only Finally blocks where it is guaranteed to not have incoming or leaving branches.
/// </summary>
public static BoundBlock MakeFinallyClone(BoundTryStatement node)
{
var cloner = new FinallyCloner();
return (BoundBlock)cloner.Visit(node.FinallyBlockOpt);
}
public override BoundNode VisitLabelStatement(BoundLabelStatement node)
{
return node.Update(GetLabelClone(node.Label));
}
public override BoundNode VisitGotoStatement(BoundGotoStatement node)
{
var labelClone = GetLabelClone(node.Label);
// expressions do not contain labels or branches
BoundExpression caseExpressionOpt = node.CaseExpressionOpt;
// expressions do not contain labels or branches
BoundLabel labelExpressionOpt = node.LabelExpressionOpt;
return node.Update(labelClone, caseExpressionOpt, labelExpressionOpt);
}
public override BoundNode VisitConditionalGoto(BoundConditionalGoto node)
{
var labelClone = GetLabelClone(node.Label);
// expressions do not contain labels or branches
BoundExpression condition = node.Condition;
return node.Update(condition, node.JumpIfTrue, labelClone);
}
public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node)
{
// expressions do not contain labels or branches
BoundExpression expression = node.Expression;
var defaultClone = GetLabelClone(node.DefaultLabel);
var casesBuilder = ArrayBuilder<(ConstantValue, LabelSymbol)>.GetInstance();
foreach (var (value, label) in node.Cases)
{
casesBuilder.Add((value, GetLabelClone(label)));
}
return node.Update(expression, casesBuilder.ToImmutableAndFree(), defaultClone, node.EqualityMethod);
}
public override BoundNode VisitExpressionStatement(BoundExpressionStatement node)
{
// expressions do not contain labels or branches
return node;
}
private GeneratedLabelSymbol GetLabelClone(LabelSymbol label)
{
var labelClones = _labelClones;
if (labelClones == null)
{
_labelClones = labelClones = new Dictionary<LabelSymbol, GeneratedLabelSymbol>();
}
GeneratedLabelSymbol clone;
if (!labelClones.TryGetValue(label, out clone))
{
clone = new GeneratedLabelSymbol("cloned_" + label.Name);
labelClones.Add(label, clone);
}
return clone;
}
}
}
}
| // 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.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CSharp.Binder;
namespace Microsoft.CodeAnalysis.CSharp.CodeGen
{
internal partial class CodeGenerator
{
private void EmitStatement(BoundStatement statement)
{
switch (statement.Kind)
{
case BoundKind.Block:
EmitBlock((BoundBlock)statement);
break;
case BoundKind.Scope:
EmitScope((BoundScope)statement);
break;
case BoundKind.SequencePoint:
this.EmitSequencePointStatement((BoundSequencePoint)statement);
break;
case BoundKind.SequencePointWithSpan:
this.EmitSequencePointStatement((BoundSequencePointWithSpan)statement);
break;
case BoundKind.SavePreviousSequencePoint:
this.EmitSavePreviousSequencePoint((BoundSavePreviousSequencePoint)statement);
break;
case BoundKind.RestorePreviousSequencePoint:
this.EmitRestorePreviousSequencePoint((BoundRestorePreviousSequencePoint)statement);
break;
case BoundKind.StepThroughSequencePoint:
this.EmitStepThroughSequencePoint((BoundStepThroughSequencePoint)statement);
break;
case BoundKind.ExpressionStatement:
EmitExpression(((BoundExpressionStatement)statement).Expression, false);
break;
case BoundKind.StatementList:
EmitStatementList((BoundStatementList)statement);
break;
case BoundKind.ReturnStatement:
EmitReturnStatement((BoundReturnStatement)statement);
break;
case BoundKind.GotoStatement:
EmitGotoStatement((BoundGotoStatement)statement);
break;
case BoundKind.LabelStatement:
EmitLabelStatement((BoundLabelStatement)statement);
break;
case BoundKind.ConditionalGoto:
EmitConditionalGoto((BoundConditionalGoto)statement);
break;
case BoundKind.ThrowStatement:
EmitThrowStatement((BoundThrowStatement)statement);
break;
case BoundKind.TryStatement:
EmitTryStatement((BoundTryStatement)statement);
break;
case BoundKind.SwitchDispatch:
EmitSwitchDispatch((BoundSwitchDispatch)statement);
break;
case BoundKind.StateMachineScope:
EmitStateMachineScope((BoundStateMachineScope)statement);
break;
case BoundKind.NoOpStatement:
EmitNoOpStatement((BoundNoOpStatement)statement);
break;
default:
// Code gen should not be invoked if there are errors.
throw ExceptionUtilities.UnexpectedValue(statement.Kind);
}
#if DEBUG
if (_stackLocals == null || _stackLocals.Count == 0)
{
_builder.AssertStackEmpty();
}
#endif
ReleaseExpressionTemps();
}
private int EmitStatementAndCountInstructions(BoundStatement statement)
{
int n = _builder.InstructionsEmitted;
this.EmitStatement(statement);
return _builder.InstructionsEmitted - n;
}
private void EmitStatementList(BoundStatementList list)
{
for (int i = 0, n = list.Statements.Length; i < n; i++)
{
EmitStatement(list.Statements[i]);
}
}
private void EmitNoOpStatement(BoundNoOpStatement statement)
{
switch (statement.Flavor)
{
case NoOpStatementFlavor.Default:
if (_ilEmitStyle == ILEmitStyle.Debug)
{
_builder.EmitOpCode(ILOpCode.Nop);
}
break;
case NoOpStatementFlavor.AwaitYieldPoint:
Debug.Assert((_asyncYieldPoints == null) == (_asyncResumePoints == null));
if (_asyncYieldPoints == null)
{
_asyncYieldPoints = ArrayBuilder<int>.GetInstance();
_asyncResumePoints = ArrayBuilder<int>.GetInstance();
}
Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count);
_asyncYieldPoints.Add(_builder.AllocateILMarker());
break;
case NoOpStatementFlavor.AwaitResumePoint:
Debug.Assert(_asyncYieldPoints != null);
Debug.Assert(_asyncYieldPoints != null);
_asyncResumePoints.Add(_builder.AllocateILMarker());
Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count);
break;
default:
throw ExceptionUtilities.UnexpectedValue(statement.Flavor);
}
}
private void EmitThrowStatement(BoundThrowStatement node)
{
EmitThrow(node.ExpressionOpt);
}
private void EmitThrow(BoundExpression thrown)
{
if (thrown != null)
{
this.EmitExpression(thrown, true);
var exprType = thrown.Type;
// Expression type will be null for "throw null;".
if (exprType?.TypeKind == TypeKind.TypeParameter)
{
this.EmitBox(exprType, thrown.Syntax);
}
}
_builder.EmitThrow(isRethrow: thrown == null);
}
private void EmitConditionalGoto(BoundConditionalGoto boundConditionalGoto)
{
object label = boundConditionalGoto.Label;
Debug.Assert(label != null);
EmitCondBranch(boundConditionalGoto.Condition, ref label, boundConditionalGoto.JumpIfTrue);
}
// 3.17 The brfalse instruction transfers control to target if value (of type int32, int64, object reference, managed
//pointer, unmanaged pointer or native int) is zero (false). If value is non-zero (true), execution continues at
//the next instruction.
private static bool CanPassToBrfalse(TypeSymbol ts)
{
if (ts.IsEnumType())
{
// valid enums are all primitives
return true;
}
var tc = ts.PrimitiveTypeCode;
switch (tc)
{
case Microsoft.Cci.PrimitiveTypeCode.Float32:
case Microsoft.Cci.PrimitiveTypeCode.Float64:
return false;
case Microsoft.Cci.PrimitiveTypeCode.NotPrimitive:
// if this is a generic type param, verifier will want us to box
// EmitCondBranch knows that
return ts.IsReferenceType;
default:
Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Invalid);
Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Void);
return true;
}
}
private static BoundExpression TryReduce(BoundBinaryOperator condition, ref bool sense)
{
var opKind = condition.OperatorKind.Operator();
Debug.Assert(opKind == BinaryOperatorKind.Equal ||
opKind == BinaryOperatorKind.NotEqual);
BoundExpression nonConstOp;
BoundExpression constOp = (condition.Left.ConstantValue != null) ? condition.Left : null;
if (constOp != null)
{
nonConstOp = condition.Right;
}
else
{
constOp = (condition.Right.ConstantValue != null) ? condition.Right : null;
if (constOp == null)
{
return null;
}
nonConstOp = condition.Left;
}
var nonConstType = nonConstOp.Type;
if (!CanPassToBrfalse(nonConstType))
{
return null;
}
bool isBool = nonConstType.PrimitiveTypeCode == Microsoft.Cci.PrimitiveTypeCode.Boolean;
bool isZero = constOp.ConstantValue.IsDefaultValue;
// bool is special, only it can be compared to true and false...
if (!isBool && !isZero)
{
return null;
}
// if comparing to zero, flip the sense
if (isZero)
{
sense = !sense;
}
// if comparing != flip the sense
if (opKind == BinaryOperatorKind.NotEqual)
{
sense = !sense;
}
return nonConstOp;
}
private const int IL_OP_CODE_ROW_LENGTH = 4;
private static readonly ILOpCode[] s_condJumpOpCodes = new ILOpCode[]
{
// < <= > >=
ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Signed
ILOpCode.Bge, ILOpCode.Bgt, ILOpCode.Ble, ILOpCode.Blt, // Signed Invert
ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un, // Unsigned
ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Unsigned Invert
ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Float
ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Float Invert
};
/// <summary>
/// Produces opcode for a jump that corresponds to given operation and sense.
/// Also produces a reverse opcode - opcode for the same condition with inverted sense.
/// </summary>
private static ILOpCode CodeForJump(BoundBinaryOperator op, bool sense, out ILOpCode revOpCode)
{
int opIdx;
switch (op.OperatorKind.Operator())
{
case BinaryOperatorKind.Equal:
revOpCode = !sense ? ILOpCode.Beq : ILOpCode.Bne_un;
return sense ? ILOpCode.Beq : ILOpCode.Bne_un;
case BinaryOperatorKind.NotEqual:
revOpCode = !sense ? ILOpCode.Bne_un : ILOpCode.Beq;
return sense ? ILOpCode.Bne_un : ILOpCode.Beq;
case BinaryOperatorKind.LessThan:
opIdx = 0;
break;
case BinaryOperatorKind.LessThanOrEqual:
opIdx = 1;
break;
case BinaryOperatorKind.GreaterThan:
opIdx = 2;
break;
case BinaryOperatorKind.GreaterThanOrEqual:
opIdx = 3;
break;
default:
throw ExceptionUtilities.UnexpectedValue(op.OperatorKind.Operator());
}
if (IsUnsignedBinaryOperator(op))
{
opIdx += 2 * IL_OP_CODE_ROW_LENGTH; //unsigned
}
else if (IsFloat(op.OperatorKind))
{
opIdx += 4 * IL_OP_CODE_ROW_LENGTH; //float
}
int revOpIdx = opIdx;
if (!sense)
{
opIdx += IL_OP_CODE_ROW_LENGTH; //invert op
}
else
{
revOpIdx += IL_OP_CODE_ROW_LENGTH; //invert rev
}
revOpCode = s_condJumpOpCodes[revOpIdx];
return s_condJumpOpCodes[opIdx];
}
// generate a jump to dest if (condition == sense) is true
private void EmitCondBranch(BoundExpression condition, ref object dest, bool sense)
{
_recursionDepth++;
if (_recursionDepth > 1)
{
StackGuard.EnsureSufficientExecutionStack(_recursionDepth);
EmitCondBranchCore(condition, ref dest, sense);
}
else
{
EmitCondBranchCoreWithStackGuard(condition, ref dest, sense);
}
_recursionDepth--;
}
private void EmitCondBranchCoreWithStackGuard(BoundExpression condition, ref object dest, bool sense)
{
Debug.Assert(_recursionDepth == 1);
try
{
EmitCondBranchCore(condition, ref dest, sense);
Debug.Assert(_recursionDepth == 1);
}
catch (InsufficientExecutionStackException)
{
_diagnostics.Add(ErrorCode.ERR_InsufficientStack,
BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(condition));
throw new EmitCancelledException();
}
}
private void EmitCondBranchCore(BoundExpression condition, ref object dest, bool sense)
{
oneMoreTime:
ILOpCode ilcode;
if (condition.ConstantValue != null)
{
bool taken = condition.ConstantValue.IsDefaultValue != sense;
if (taken)
{
dest = dest ?? new object();
_builder.EmitBranch(ILOpCode.Br, dest);
}
else
{
// otherwise this branch will never be taken, so just fall through...
}
return;
}
switch (condition.Kind)
{
case BoundKind.BinaryOperator:
var binOp = (BoundBinaryOperator)condition;
bool testBothArgs = sense;
switch (binOp.OperatorKind.OperatorWithLogical())
{
case BinaryOperatorKind.LogicalOr:
testBothArgs = !testBothArgs;
// Fall through
goto case BinaryOperatorKind.LogicalAnd;
case BinaryOperatorKind.LogicalAnd:
if (testBothArgs)
{
// gotoif(a != sense) fallThrough
// gotoif(b == sense) dest
// fallThrough:
object fallThrough = null;
EmitCondBranch(binOp.Left, ref fallThrough, !sense);
EmitCondBranch(binOp.Right, ref dest, sense);
if (fallThrough != null)
{
_builder.MarkLabel(fallThrough);
}
}
else
{
// gotoif(a == sense) labDest
// gotoif(b == sense) labDest
EmitCondBranch(binOp.Left, ref dest, sense);
condition = binOp.Right;
goto oneMoreTime;
}
return;
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
var reduced = TryReduce(binOp, ref sense);
if (reduced != null)
{
condition = reduced;
goto oneMoreTime;
}
// Fall through
goto case BinaryOperatorKind.LessThan;
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.LessThanOrEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.GreaterThanOrEqual:
EmitExpression(binOp.Left, true);
EmitExpression(binOp.Right, true);
ILOpCode revOpCode;
ilcode = CodeForJump(binOp, sense, out revOpCode);
dest = dest ?? new object();
_builder.EmitBranch(ilcode, dest, revOpCode);
return;
}
// none of above.
// then it is regular binary expression - Or, And, Xor ...
goto default;
case BoundKind.LoweredConditionalAccess:
{
var ca = (BoundLoweredConditionalAccess)condition;
var receiver = ca.Receiver;
var receiverType = receiver.Type;
// we need a copy if we deal with nonlocal value (to capture the value)
// or if we deal with stack local (reads are destructive)
var complexCase = !receiverType.IsReferenceType ||
LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) ||
(receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol)) ||
(ca.WhenNullOpt?.IsDefaultValue() == false);
if (complexCase)
{
goto default;
}
if (sense)
{
// gotoif(receiver != null) fallThrough
// gotoif(receiver.Access) dest
// fallThrough:
object fallThrough = null;
EmitCondBranch(receiver, ref fallThrough, sense: false);
// receiver is a reference type, and we only intend to read it
EmitReceiverRef(receiver, AddressKind.ReadOnly);
EmitCondBranch(ca.WhenNotNull, ref dest, sense: true);
if (fallThrough != null)
{
_builder.MarkLabel(fallThrough);
}
}
else
{
// gotoif(receiver == null) labDest
// gotoif(!receiver.Access) labDest
EmitCondBranch(receiver, ref dest, sense: false);
// receiver is a reference type, and we only intend to read it
EmitReceiverRef(receiver, AddressKind.ReadOnly);
condition = ca.WhenNotNull;
goto oneMoreTime;
}
}
return;
case BoundKind.UnaryOperator:
var unOp = (BoundUnaryOperator)condition;
if (unOp.OperatorKind == UnaryOperatorKind.BoolLogicalNegation)
{
sense = !sense;
condition = unOp.Operand;
goto oneMoreTime;
}
goto default;
case BoundKind.IsOperator:
var isOp = (BoundIsOperator)condition;
var operand = isOp.Operand;
EmitExpression(operand, true);
Debug.Assert((object)operand.Type != null);
if (!operand.Type.IsVerifierReference())
{
// box the operand for isinst if it is not a verifier reference
EmitBox(operand.Type, operand.Syntax);
}
_builder.EmitOpCode(ILOpCode.Isinst);
EmitSymbolToken(isOp.TargetType.Type, isOp.TargetType.Syntax);
ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse;
dest = dest ?? new object();
_builder.EmitBranch(ilcode, dest);
return;
case BoundKind.Sequence:
var seq = (BoundSequence)condition;
EmitSequenceCondBranch(seq, ref dest, sense);
return;
default:
EmitExpression(condition, true);
var conditionType = condition.Type;
if (conditionType.IsReferenceType && !conditionType.IsVerifierReference())
{
EmitBox(conditionType, condition.Syntax);
}
ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse;
dest = dest ?? new object();
_builder.EmitBranch(ilcode, dest);
return;
}
}
private void EmitSequenceCondBranch(BoundSequence sequence, ref object dest, bool sense)
{
DefineLocals(sequence);
EmitSideEffects(sequence);
EmitCondBranch(sequence.Value, ref dest, sense);
// sequence is used as a value, can release all locals
FreeLocals(sequence);
}
private void EmitLabelStatement(BoundLabelStatement boundLabelStatement)
{
_builder.MarkLabel(boundLabelStatement.Label);
}
private void EmitGotoStatement(BoundGotoStatement boundGotoStatement)
{
_builder.EmitBranch(ILOpCode.Br, boundGotoStatement.Label);
}
// used by HandleReturn method which tries to inject
// indirect ret sequence as a last statement in the block
// that is the last statement of the current method
// NOTE: it is important that there is no code after this "ret"
// it is desirable, for debug purposes, that this ret is emitted inside top level { }
private bool IsLastBlockInMethod(BoundBlock block)
{
if (_boundBody == block)
{
return true;
}
//sometimes top level node is a statement list containing
//epilogue and then a block. If we are having that block, it will do.
var list = _boundBody as BoundStatementList;
if (list != null && list.Statements.LastOrDefault() == block)
{
return true;
}
return false;
}
private void EmitBlock(BoundBlock block)
{
var hasLocals = !block.Locals.IsEmpty;
if (hasLocals)
{
_builder.OpenLocalScope();
foreach (var local in block.Locals)
{
Debug.Assert(local.RefKind == RefKind.None || local.SynthesizedKind.IsLongLived(),
"A ref local ended up in a block and claims it is shortlived. That is dangerous. Are we sure it is short lived?");
var declaringReferences = local.DeclaringSyntaxReferences;
DefineLocal(local, !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : block.Syntax);
}
}
EmitStatements(block.Statements);
if (_indirectReturnState == IndirectReturnState.Needed &&
IsLastBlockInMethod(block))
{
HandleReturn();
}
if (hasLocals)
{
foreach (var local in block.Locals)
{
FreeLocal(local);
}
_builder.CloseLocalScope();
}
}
private void EmitStatements(ImmutableArray<BoundStatement> statements)
{
foreach (var statement in statements)
{
EmitStatement(statement);
}
}
private void EmitScope(BoundScope block)
{
Debug.Assert(!block.Locals.IsEmpty);
_builder.OpenLocalScope();
foreach (var local in block.Locals)
{
Debug.Assert(local.Name != null);
Debug.Assert(local.SynthesizedKind == SynthesizedLocalKind.UserDefined &&
(local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchSection || local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchExpressionArm));
if (!local.IsConst && !IsStackLocal(local))
{
_builder.AddLocalToScope(_builder.LocalSlotManager.GetLocal(local));
}
}
EmitStatements(block.Statements);
_builder.CloseLocalScope();
}
private void EmitStateMachineScope(BoundStateMachineScope scope)
{
_builder.OpenLocalScope(ScopeType.StateMachineVariable);
foreach (var field in scope.Fields)
{
if (field.SlotIndex >= 0)
{
_builder.DefineUserDefinedStateMachineHoistedLocal(field.SlotIndex);
}
}
EmitStatement(scope.Statement);
_builder.CloseLocalScope();
}
// There are two ways a value can be returned from a function:
// - Using ret opcode
// - Store return value if any to a predefined temp and jump to the epilogue block
// Sometimes ret is not an option (try/catch etc.). We also do this when emitting
// debuggable code. This function is a stub for the logic that decides that.
private bool ShouldUseIndirectReturn()
{
// If the method/lambda body is a block we define a sequence point for the closing brace of the body
// and associate it with the ret instruction. If there is a return statement we need to store the value
// to a long-lived synthesized local since a sequence point requires an empty evaluation stack.
//
// The emitted pattern is:
// <evaluate return statement expression>
// stloc $ReturnValue
// ldloc $ReturnValue // sequence point
// ret
//
// Do not emit this pattern if the method doesn't include user code or doesn't have a block body.
return _ilEmitStyle == ILEmitStyle.Debug && _method.GenerateDebugInfo && _methodBodySyntaxOpt?.IsKind(SyntaxKind.Block) == true ||
_builder.InExceptionHandler;
}
// Compiler generated return mapped to a block is very likely the synthetic return
// that was added at the end of the last block of a void method by analysis.
// This is likely to be the last return in the method, so if we have not yet
// emitted return sequence, it is convenient to do it right here (if we can).
private bool CanHandleReturnLabel(BoundReturnStatement boundReturnStatement)
{
return boundReturnStatement.WasCompilerGenerated &&
(boundReturnStatement.Syntax.IsKind(SyntaxKind.Block) || _method?.IsImplicitConstructor == true) &&
!_builder.InExceptionHandler;
}
private void EmitReturnStatement(BoundReturnStatement boundReturnStatement)
{
var expressionOpt = boundReturnStatement.ExpressionOpt;
if (boundReturnStatement.RefKind == RefKind.None)
{
this.EmitExpression(expressionOpt, true);
}
else
{
// NOTE: passing "ReadOnlyStrict" here.
// we should never return an address of a copy
var unexpectedTemp = this.EmitAddress(expressionOpt, this._method.RefKind == RefKind.RefReadOnly ? AddressKind.ReadOnlyStrict : AddressKind.Writeable);
Debug.Assert(unexpectedTemp == null, "ref-returning a temp?");
}
if (ShouldUseIndirectReturn())
{
if (expressionOpt != null)
{
_builder.EmitLocalStore(LazyReturnTemp);
}
if (_indirectReturnState != IndirectReturnState.Emitted && CanHandleReturnLabel(boundReturnStatement))
{
HandleReturn();
}
else
{
_builder.EmitBranch(ILOpCode.Br, s_returnLabel);
if (_indirectReturnState == IndirectReturnState.NotNeeded)
{
_indirectReturnState = IndirectReturnState.Needed;
}
}
}
else
{
if (_indirectReturnState == IndirectReturnState.Needed && CanHandleReturnLabel(boundReturnStatement))
{
if (expressionOpt != null)
{
_builder.EmitLocalStore(LazyReturnTemp);
}
HandleReturn();
}
else
{
if (expressionOpt != null)
{
// Ensure the return type has been translated. (Necessary
// for cases of untranslated anonymous types.)
_module.Translate(expressionOpt.Type, boundReturnStatement.Syntax, _diagnostics);
}
_builder.EmitRet(expressionOpt == null);
}
}
}
private void EmitTryStatement(BoundTryStatement statement, bool emitCatchesOnly = false)
{
Debug.Assert(!statement.CatchBlocks.IsDefault);
// Stack must be empty at beginning of try block.
_builder.AssertStackEmpty();
// IL requires catches and finally block to be distinct try
// blocks so if the source contained both a catch and
// a finally, nested scopes are emitted.
bool emitNestedScopes = (!emitCatchesOnly &&
(statement.CatchBlocks.Length > 0) &&
(statement.FinallyBlockOpt != null));
_builder.OpenLocalScope(ScopeType.TryCatchFinally);
_builder.OpenLocalScope(ScopeType.Try);
// IL requires catches and finally block to be distinct try
// blocks so if the source contained both a catch and
// a finally, nested scopes are emitted.
_tryNestingLevel++;
if (emitNestedScopes)
{
EmitTryStatement(statement, emitCatchesOnly: true);
}
else
{
EmitBlock(statement.TryBlock);
}
_tryNestingLevel--;
// Close the Try scope
_builder.CloseLocalScope();
if (!emitNestedScopes)
{
foreach (var catchBlock in statement.CatchBlocks)
{
EmitCatchBlock(catchBlock);
}
}
if (!emitCatchesOnly && (statement.FinallyBlockOpt != null))
{
_builder.OpenLocalScope(statement.PreferFaultHandler ? ScopeType.Fault : ScopeType.Finally);
EmitBlock(statement.FinallyBlockOpt);
// close Finally scope
_builder.CloseLocalScope();
// close the whole try statement scope
_builder.CloseLocalScope();
// in a case where we emit surrogate Finally using Fault, we emit code like this
//
// try{
// . . .
// } fault {
// finallyBlock;
// }
// finallyBlock;
//
// This is where the second copy of finallyBlock is emitted.
if (statement.PreferFaultHandler)
{
var finallyClone = FinallyCloner.MakeFinallyClone(statement);
EmitBlock(finallyClone);
}
}
else
{
// close the whole try statement scope
_builder.CloseLocalScope();
}
}
/// <remarks>
/// The interesting part in the following method is the support for exception filters.
/// === Example:
///
/// try
/// {
/// TryBlock
/// }
/// catch (ExceptionType ex) when (Condition)
/// {
/// Handler
/// }
///
/// gets emitted as something like ===>
///
/// Try
/// TryBlock
/// Filter
/// var tmp = Pop() as {ExceptionType}
/// if (tmp == null)
/// {
/// Push 0
/// }
/// else
/// {
/// ex = tmp
/// Push Condition ? 1 : 0
/// }
/// End Filter // leaves 1 or 0 on the stack
/// Catch // gets called after finalization of nested exception frames if condition above produced 1
/// Pop // CLR pushes the exception object again
/// variable ex can be used here
/// Handler
/// EndCatch
///
/// When evaluating `Condition` requires additional statements be executed first, those
/// statements are stored in `catchBlock.ExceptionFilterPrologueOpt` and emitted before the condition.
/// </remarks>
private void EmitCatchBlock(BoundCatchBlock catchBlock)
{
object typeCheckFailedLabel = null;
_builder.AdjustStack(1); // Account for exception on the stack.
// Open appropriate exception handler scope. (Catch or Filter)
// if it is a Filter, emit prologue that checks if the type on the stack
// converts to what we want.
if (catchBlock.ExceptionFilterOpt == null)
{
var exceptionType = ((object)catchBlock.ExceptionTypeOpt != null) ?
_module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics) :
_module.GetSpecialType(SpecialType.System_Object, catchBlock.Syntax, _diagnostics);
_builder.OpenLocalScope(ScopeType.Catch, exceptionType);
RecordAsyncCatchHandlerOffset(catchBlock);
// Dev12 inserts the sequence point on catch clause without a filter, just before
// the exception object is assigned to the variable.
//
// Also in Dev12 the exception variable scope span starts right after the stloc instruction and
// ends right before leave instruction. So when stopped at the sequence point Dev12 inserts,
// the exception variable is not visible.
if (_emitPdbSequencePoints)
{
var syntax = catchBlock.Syntax as CatchClauseSyntax;
if (syntax != null)
{
TextSpan spSpan;
var declaration = syntax.Declaration;
if (declaration == null)
{
spSpan = syntax.CatchKeyword.Span;
}
else
{
spSpan = TextSpan.FromBounds(syntax.SpanStart, syntax.Declaration.Span.End);
}
this.EmitSequencePoint(catchBlock.SyntaxTree, spSpan);
}
}
}
else
{
_builder.OpenLocalScope(ScopeType.Filter);
RecordAsyncCatchHandlerOffset(catchBlock);
// Filtering starts with simulating regular catch through a
// type check. If this is not our type then we are done.
var typeCheckPassedLabel = new object();
typeCheckFailedLabel = new object();
if ((object)catchBlock.ExceptionTypeOpt != null)
{
var exceptionType = _module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics);
_builder.EmitOpCode(ILOpCode.Isinst);
_builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics);
_builder.EmitOpCode(ILOpCode.Dup);
_builder.EmitBranch(ILOpCode.Brtrue, typeCheckPassedLabel);
_builder.EmitOpCode(ILOpCode.Pop);
_builder.EmitIntConstant(0);
_builder.EmitBranch(ILOpCode.Br, typeCheckFailedLabel);
}
else
{
// no formal exception type means we always pass the check
}
_builder.MarkLabel(typeCheckPassedLabel);
}
foreach (var local in catchBlock.Locals)
{
var declaringReferences = local.DeclaringSyntaxReferences;
var localSyntax = !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : catchBlock.Syntax;
DefineLocal(local, localSyntax);
}
var exceptionSourceOpt = catchBlock.ExceptionSourceOpt;
if (exceptionSourceOpt != null)
{
// here we have our exception on the stack in a form of a reference type (O)
// it means that we have to "unbox" it before storing to the local
// if exception's type is a generic type parameter.
if (!exceptionSourceOpt.Type.IsVerifierReference())
{
Debug.Assert(exceptionSourceOpt.Type.IsTypeParameter()); // only expecting type parameters
_builder.EmitOpCode(ILOpCode.Unbox_any);
EmitSymbolToken(exceptionSourceOpt.Type, exceptionSourceOpt.Syntax);
}
BoundExpression exceptionSource = exceptionSourceOpt;
while (exceptionSource.Kind == BoundKind.Sequence)
{
var seq = (BoundSequence)exceptionSource;
Debug.Assert(seq.Locals.IsDefaultOrEmpty);
EmitSideEffects(seq);
exceptionSource = seq.Value;
}
switch (exceptionSource.Kind)
{
case BoundKind.Local:
var exceptionSourceLocal = (BoundLocal)exceptionSource;
Debug.Assert(exceptionSourceLocal.LocalSymbol.RefKind == RefKind.None);
if (!IsStackLocal(exceptionSourceLocal.LocalSymbol))
{
_builder.EmitLocalStore(GetLocal(exceptionSourceLocal));
}
break;
case BoundKind.FieldAccess:
var left = (BoundFieldAccess)exceptionSource;
Debug.Assert(!left.FieldSymbol.IsStatic, "Not supported");
Debug.Assert(!left.ReceiverOpt.Type.IsTypeParameter());
var stateMachineField = left.FieldSymbol as StateMachineFieldSymbol;
if (((object)stateMachineField != null) && (stateMachineField.SlotIndex >= 0))
{
_builder.DefineUserDefinedStateMachineHoistedLocal(stateMachineField.SlotIndex);
}
// When assigning to a field
// we need to push param address below the exception
var temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax);
_builder.EmitLocalStore(temp);
var receiverTemp = EmitReceiverRef(left.ReceiverOpt, AddressKind.Writeable);
Debug.Assert(receiverTemp == null);
_builder.EmitLocalLoad(temp);
FreeTemp(temp);
EmitFieldStore(left);
break;
default:
throw ExceptionUtilities.UnexpectedValue(exceptionSource.Kind);
}
}
else
{
_builder.EmitOpCode(ILOpCode.Pop);
}
if (catchBlock.ExceptionFilterPrologueOpt != null)
{
Debug.Assert(_builder.IsStackEmpty);
EmitStatements(catchBlock.ExceptionFilterPrologueOpt.Statements);
}
// Emit the actual filter expression, if we have one, and normalize
// results.
if (catchBlock.ExceptionFilterOpt != null)
{
EmitCondExpr(catchBlock.ExceptionFilterOpt, true);
// Normalize the return value because values other than 0 or 1
// produce unspecified results.
_builder.EmitIntConstant(0);
_builder.EmitOpCode(ILOpCode.Cgt_un);
_builder.MarkLabel(typeCheckFailedLabel);
// Now we are starting the actual handler
_builder.MarkFilterConditionEnd();
// Pop the exception; it should have already been stored to the
// variable by the filter.
_builder.EmitOpCode(ILOpCode.Pop);
}
EmitBlock(catchBlock.Body);
_builder.CloseLocalScope();
}
private void RecordAsyncCatchHandlerOffset(BoundCatchBlock catchBlock)
{
if (catchBlock.IsSynthesizedAsyncCatchAll)
{
Debug.Assert(_asyncCatchHandlerOffset < 0); // only one expected
_asyncCatchHandlerOffset = _builder.AllocateILMarker();
}
}
private void EmitSwitchDispatch(BoundSwitchDispatch dispatch)
{
// Switch expression must have a valid switch governing type
Debug.Assert((object)dispatch.Expression.Type != null);
Debug.Assert(dispatch.Expression.Type.IsValidV6SwitchGoverningType());
// We must have rewritten nullable switch expression into non-nullable constructs.
Debug.Assert(!dispatch.Expression.Type.IsNullableType());
// This must be used only for nontrivial dispatches.
Debug.Assert(dispatch.Cases.Any());
EmitSwitchHeader(
dispatch.Expression,
dispatch.Cases.Select(p => new KeyValuePair<ConstantValue, object>(p.value, p.label)).ToArray(),
dispatch.DefaultLabel,
dispatch.EqualityMethod);
}
private void EmitSwitchHeader(
BoundExpression expression,
KeyValuePair<ConstantValue, object>[] switchCaseLabels,
LabelSymbol fallThroughLabel,
MethodSymbol equalityMethod)
{
Debug.Assert(expression.ConstantValue == null);
Debug.Assert((object)expression.Type != null &&
expression.Type.IsValidV6SwitchGoverningType());
Debug.Assert(switchCaseLabels.Length > 0);
Debug.Assert(switchCaseLabels != null);
LocalDefinition temp = null;
LocalOrParameter key;
BoundSequence sequence = null;
if (expression.Kind == BoundKind.Sequence)
{
sequence = (BoundSequence)expression;
DefineLocals(sequence);
EmitSideEffects(sequence);
expression = sequence.Value;
}
if (expression.Kind == BoundKind.SequencePointExpression)
{
var sequencePointExpression = (BoundSequencePointExpression)expression;
EmitSequencePoint(sequencePointExpression);
expression = sequencePointExpression.Expression;
}
switch (expression.Kind)
{
case BoundKind.Local:
var local = ((BoundLocal)expression).LocalSymbol;
if (local.RefKind == RefKind.None && !IsStackLocal(local))
{
key = this.GetLocal(local);
break;
}
goto default;
case BoundKind.Parameter:
var parameter = (BoundParameter)expression;
if (parameter.ParameterSymbol.RefKind == RefKind.None)
{
key = ParameterSlot(parameter);
break;
}
goto default;
default:
EmitExpression(expression, true);
temp = AllocateTemp(expression.Type, expression.Syntax);
_builder.EmitLocalStore(temp);
key = temp;
break;
}
// Emit switch jump table
if (expression.Type.SpecialType != SpecialType.System_String)
{
_builder.EmitIntegerSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Type.EnumUnderlyingTypeOrSelf().PrimitiveTypeCode);
}
else
{
this.EmitStringSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Syntax, equalityMethod);
}
if (temp != null)
{
FreeTemp(temp);
}
if (sequence != null)
{
// sequence was used as a value, can release all its locals.
FreeLocals(sequence);
}
}
private void EmitStringSwitchJumpTable(
KeyValuePair<ConstantValue, object>[] switchCaseLabels,
LabelSymbol fallThroughLabel,
LocalOrParameter key,
SyntaxNode syntaxNode,
MethodSymbol equalityMethod)
{
LocalDefinition keyHash = null;
// Condition is necessary, but not sufficient (e.g. might be missing a special or well-known member).
if (SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(_module, switchCaseLabels.Length))
{
Debug.Assert(_module.SupportsPrivateImplClass);
var privateImplClass = _module.GetPrivateImplClass(syntaxNode, _diagnostics);
Cci.IReference stringHashMethodRef = privateImplClass.GetMethod(PrivateImplementationDetails.SynthesizedStringHashFunctionName);
// Heuristics and well-known member availability determine the existence
// of this helper. Rather than reproduce that (language-specific) logic here,
// we simply check for the information we really want - whether the helper is
// available.
if (stringHashMethodRef != null)
{
// static uint ComputeStringHash(string s)
// pop 1 (s)
// push 1 (uint return value)
// stackAdjustment = (pushCount - popCount) = 0
_builder.EmitLoad(key);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0);
_builder.EmitToken(stringHashMethodRef, syntaxNode, _diagnostics);
var UInt32Type = _module.Compilation.GetSpecialType(SpecialType.System_UInt32);
keyHash = AllocateTemp(UInt32Type, syntaxNode);
_builder.EmitLocalStore(keyHash);
}
}
Cci.IReference stringEqualityMethodRef = _module.Translate(equalityMethod, syntaxNode, _diagnostics);
Cci.IMethodReference stringLengthRef = null;
var stringLengthMethod = _module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__Length) as MethodSymbol;
if (stringLengthMethod != null && !stringLengthMethod.HasUseSiteError)
{
stringLengthRef = _module.Translate(stringLengthMethod, syntaxNode, _diagnostics);
}
SwitchStringJumpTableEmitter.EmitStringCompareAndBranch emitStringCondBranchDelegate =
(keyArg, stringConstant, targetLabel) =>
{
if (stringConstant == ConstantValue.Null)
{
// if (key == null)
// goto targetLabel
_builder.EmitLoad(keyArg);
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue);
}
else if (stringConstant.StringValue.Length == 0 && stringLengthRef != null)
{
// if (key != null && key.Length == 0)
// goto targetLabel
object skipToNext = new object();
_builder.EmitLoad(keyArg);
_builder.EmitBranch(ILOpCode.Brfalse, skipToNext, ILOpCode.Brtrue);
_builder.EmitLoad(keyArg);
// Stack: key --> length
_builder.EmitOpCode(ILOpCode.Call, 0);
var diag = DiagnosticBag.GetInstance();
_builder.EmitToken(stringLengthRef, null, diag);
Debug.Assert(diag.IsEmptyWithoutResolution);
diag.Free();
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue);
_builder.MarkLabel(skipToNext);
}
else
{
this.EmitStringCompareAndBranch(key, syntaxNode, stringConstant, targetLabel, stringEqualityMethodRef);
}
};
_builder.EmitStringSwitchJumpTable(
caseLabels: switchCaseLabels,
fallThroughLabel: fallThroughLabel,
key: key,
keyHash: keyHash,
emitStringCondBranchDelegate: emitStringCondBranchDelegate,
computeStringHashcodeDelegate: SynthesizedStringSwitchHashMethod.ComputeStringHash);
if (keyHash != null)
{
FreeTemp(keyHash);
}
}
/// <summary>
/// Delegate to emit string compare call and conditional branch based on the compare result.
/// </summary>
/// <param name="key">Key to compare</param>
/// <param name="syntaxNode">Node for diagnostics.</param>
/// <param name="stringConstant">Case constant to compare the key against</param>
/// <param name="targetLabel">Target label to branch to if key = stringConstant</param>
/// <param name="stringEqualityMethodRef">String equality method</param>
private void EmitStringCompareAndBranch(LocalOrParameter key, SyntaxNode syntaxNode, ConstantValue stringConstant, object targetLabel, Microsoft.Cci.IReference stringEqualityMethodRef)
{
// Emit compare and branch:
// if (key == stringConstant)
// goto targetLabel;
Debug.Assert(stringEqualityMethodRef != null);
#if DEBUG
var assertDiagnostics = DiagnosticBag.GetInstance();
Debug.Assert(stringEqualityMethodRef == _module.Translate((MethodSymbol)_module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__op_Equality), (CSharpSyntaxNode)syntaxNode, assertDiagnostics));
assertDiagnostics.Free();
#endif
// static bool String.Equals(string a, string b)
// pop 2 (a, b)
// push 1 (bool return value)
// stackAdjustment = (pushCount - popCount) = -1
_builder.EmitLoad(key);
_builder.EmitConstantValue(stringConstant);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1);
_builder.EmitToken(stringEqualityMethodRef, syntaxNode, _diagnostics);
// Branch to targetLabel if String.Equals returned true.
_builder.EmitBranch(ILOpCode.Brtrue, targetLabel, ILOpCode.Brfalse);
}
/// <summary>
/// Gets already declared and initialized local.
/// </summary>
private LocalDefinition GetLocal(BoundLocal localExpression)
{
var symbol = localExpression.LocalSymbol;
return GetLocal(symbol);
}
private LocalDefinition GetLocal(LocalSymbol symbol)
{
return _builder.LocalSlotManager.GetLocal(symbol);
}
private LocalDefinition DefineLocal(LocalSymbol local, SyntaxNode syntaxNode)
{
var dynamicTransformFlags = !local.IsCompilerGenerated && local.Type.ContainsDynamic() ?
CSharpCompilation.DynamicTransformsEncoder.Encode(local.Type, RefKind.None, 0) :
ImmutableArray<bool>.Empty;
var tupleElementNames = !local.IsCompilerGenerated && local.Type.ContainsTupleNames() ?
CSharpCompilation.TupleNamesEncoder.Encode(local.Type) :
ImmutableArray<string>.Empty;
if (local.IsConst)
{
Debug.Assert(local.HasConstantValue);
MetadataConstant compileTimeValue = _module.CreateConstant(local.Type, local.ConstantValue, syntaxNode, _diagnostics);
LocalConstantDefinition localConstantDef = new LocalConstantDefinition(
local.Name,
local.Locations.FirstOrDefault() ?? Location.None,
compileTimeValue,
dynamicTransformFlags: dynamicTransformFlags,
tupleElementNames: tupleElementNames);
_builder.AddLocalConstantToScope(localConstantDef);
return null;
}
if (IsStackLocal(local))
{
return null;
}
LocalSlotConstraints constraints;
Cci.ITypeReference translatedType;
if (local.DeclarationKind == LocalDeclarationKind.FixedVariable && local.IsPinned) // Excludes pointer local and string local in fixed string case.
{
Debug.Assert(local.RefKind == RefKind.None);
Debug.Assert(local.TypeWithAnnotations.Type.IsPointerType());
constraints = LocalSlotConstraints.ByRef | LocalSlotConstraints.Pinned;
PointerTypeSymbol pointerType = (PointerTypeSymbol)local.Type;
TypeSymbol pointedAtType = pointerType.PointedAtType;
// We can't declare a reference to void, so if the pointed-at type is void, use native int
// (represented here by IntPtr) instead.
translatedType = pointedAtType.IsVoidType()
? _module.GetSpecialType(SpecialType.System_IntPtr, syntaxNode, _diagnostics)
: _module.Translate(pointedAtType, syntaxNode, _diagnostics);
}
else
{
constraints = (local.IsPinned ? LocalSlotConstraints.Pinned : LocalSlotConstraints.None) |
(local.RefKind != RefKind.None ? LocalSlotConstraints.ByRef : LocalSlotConstraints.None);
translatedType = _module.Translate(local.Type, syntaxNode, _diagnostics);
}
// Even though we don't need the token immediately, we will need it later when signature for the local is emitted.
// Also, requesting the token has side-effect of registering types used, which is critical for embedded types (NoPia, VBCore, etc).
_module.GetFakeSymbolTokenForIL(translatedType, syntaxNode, _diagnostics);
LocalDebugId localId;
var name = GetLocalDebugName(local, out localId);
var localDef = _builder.LocalSlotManager.DeclareLocal(
type: translatedType,
symbol: local,
name: name,
kind: local.SynthesizedKind,
id: localId,
pdbAttributes: local.SynthesizedKind.PdbAttributes(),
constraints: constraints,
dynamicTransformFlags: dynamicTransformFlags,
tupleElementNames: tupleElementNames,
isSlotReusable: local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release));
// If named, add it to the local debug scope.
if (localDef.Name != null &&
!(local.SynthesizedKind == SynthesizedLocalKind.UserDefined &&
// Visibility scope of such locals is represented by BoundScope node.
(local.ScopeDesignatorOpt?.Kind() is SyntaxKind.SwitchSection or SyntaxKind.SwitchExpressionArm)))
{
_builder.AddLocalToScope(localDef);
}
return localDef;
}
/// <summary>
/// Gets the name and id of the local that are going to be generated into the debug metadata.
/// </summary>
private string GetLocalDebugName(ILocalSymbolInternal local, out LocalDebugId localId)
{
localId = LocalDebugId.None;
if (local.IsImportedFromMetadata)
{
return local.Name;
}
var localKind = local.SynthesizedKind;
// only user-defined locals should be named during lowering:
Debug.Assert((local.Name == null) == (localKind != SynthesizedLocalKind.UserDefined));
// Generating debug names for instrumentation payloads should be allowed, as described in https://github.com/dotnet/roslyn/issues/11024.
// For now, skip naming locals generated by instrumentation as they might not have a local syntax offset.
// Locals generated by instrumentation might exist in methods which do not contain a body (auto property initializers).
if (!localKind.IsLongLived() || localKind == SynthesizedLocalKind.InstrumentationPayload)
{
return null;
}
if (_ilEmitStyle == ILEmitStyle.Debug)
{
var syntax = local.GetDeclaratorSyntax();
int syntaxOffset = _method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(syntax), syntax.SyntaxTree);
int ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(localKind, syntaxOffset);
// user-defined locals should have 0 ordinal:
Debug.Assert(ordinal == 0 || localKind != SynthesizedLocalKind.UserDefined);
localId = new LocalDebugId(syntaxOffset, ordinal);
}
return local.Name ?? GeneratedNames.MakeSynthesizedLocalName(localKind, ref _uniqueNameId);
}
private bool IsSlotReusable(LocalSymbol local)
{
return local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release);
}
/// <summary>
/// Releases a local.
/// </summary>
private void FreeLocal(LocalSymbol local)
{
// TODO: releasing named locals is NYI.
if (local.Name == null && IsSlotReusable(local) && !IsStackLocal(local))
{
_builder.LocalSlotManager.FreeLocal(local);
}
}
/// <summary>
/// Allocates a temp without identity.
/// </summary>
private LocalDefinition AllocateTemp(TypeSymbol type, SyntaxNode syntaxNode, LocalSlotConstraints slotConstraints = LocalSlotConstraints.None)
{
return _builder.LocalSlotManager.AllocateSlot(
_module.Translate(type, syntaxNode, _diagnostics),
slotConstraints);
}
/// <summary>
/// Frees a temp.
/// </summary>
private void FreeTemp(LocalDefinition temp)
{
_builder.LocalSlotManager.FreeSlot(temp);
}
/// <summary>
/// Frees an optional temp.
/// </summary>
private void FreeOptTemp(LocalDefinition temp)
{
if (temp != null)
{
FreeTemp(temp);
}
}
/// <summary>
/// Clones all labels used in a finally block.
/// This allows creating an emittable clone of finally.
/// It is safe to do because no branches can go in or out of the finally handler.
/// </summary>
private class FinallyCloner : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
private Dictionary<LabelSymbol, GeneratedLabelSymbol> _labelClones;
private FinallyCloner() { }
/// <summary>
/// The argument is BoundTryStatement (and not a BoundBlock) specifically
/// to support only Finally blocks where it is guaranteed to not have incoming or leaving branches.
/// </summary>
public static BoundBlock MakeFinallyClone(BoundTryStatement node)
{
var cloner = new FinallyCloner();
return (BoundBlock)cloner.Visit(node.FinallyBlockOpt);
}
public override BoundNode VisitLabelStatement(BoundLabelStatement node)
{
return node.Update(GetLabelClone(node.Label));
}
public override BoundNode VisitGotoStatement(BoundGotoStatement node)
{
var labelClone = GetLabelClone(node.Label);
// expressions do not contain labels or branches
BoundExpression caseExpressionOpt = node.CaseExpressionOpt;
// expressions do not contain labels or branches
BoundLabel labelExpressionOpt = node.LabelExpressionOpt;
return node.Update(labelClone, caseExpressionOpt, labelExpressionOpt);
}
public override BoundNode VisitConditionalGoto(BoundConditionalGoto node)
{
var labelClone = GetLabelClone(node.Label);
// expressions do not contain labels or branches
BoundExpression condition = node.Condition;
return node.Update(condition, node.JumpIfTrue, labelClone);
}
public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node)
{
// expressions do not contain labels or branches
BoundExpression expression = node.Expression;
var defaultClone = GetLabelClone(node.DefaultLabel);
var casesBuilder = ArrayBuilder<(ConstantValue, LabelSymbol)>.GetInstance();
foreach (var (value, label) in node.Cases)
{
casesBuilder.Add((value, GetLabelClone(label)));
}
return node.Update(expression, casesBuilder.ToImmutableAndFree(), defaultClone, node.EqualityMethod);
}
public override BoundNode VisitExpressionStatement(BoundExpressionStatement node)
{
// expressions do not contain labels or branches
return node;
}
private GeneratedLabelSymbol GetLabelClone(LabelSymbol label)
{
var labelClones = _labelClones;
if (labelClones == null)
{
_labelClones = labelClones = new Dictionary<LabelSymbol, GeneratedLabelSymbol>();
}
GeneratedLabelSymbol clone;
if (!labelClones.TryGetValue(label, out clone))
{
clone = new GeneratedLabelSymbol("cloned_" + label.Name);
labelClones.Add(label, clone);
}
return clone;
}
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_DelegateCreationExpression.cs | // 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.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node)
{
if (node.Argument.HasDynamicType())
{
var loweredArgument = VisitExpression(node.Argument);
// Creates a delegate whose instance is the delegate that is returned by the call-site and the method is Invoke.
var loweredReceiver = _dynamicFactory.MakeDynamicConversion(loweredArgument, isExplicit: false, isArrayIndex: false, isChecked: false, resultType: node.Type).ToExpression();
return new BoundDelegateCreationExpression(node.Syntax, loweredReceiver, methodOpt: null, isExtensionMethod: false, type: node.Type);
}
if (node.Argument.Kind == BoundKind.MethodGroup)
{
var mg = (BoundMethodGroup)node.Argument;
var method = node.MethodOpt;
Debug.Assert(method is { });
var oldSyntax = _factory.Syntax;
_factory.Syntax = (mg.ReceiverOpt ?? mg).Syntax;
var receiver = (!method.RequiresInstanceReceiver && !node.IsExtensionMethod && !method.IsAbstract) ? _factory.Type(method.ContainingType) : VisitExpression(mg.ReceiverOpt)!;
_factory.Syntax = oldSyntax;
return node.Update(receiver, method, node.IsExtensionMethod, node.Type);
}
return base.VisitDelegateCreationExpression(node)!;
}
}
}
| // 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.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node)
{
if (node.Argument.HasDynamicType())
{
var loweredArgument = VisitExpression(node.Argument);
// Creates a delegate whose instance is the delegate that is returned by the call-site and the method is Invoke.
var loweredReceiver = _dynamicFactory.MakeDynamicConversion(loweredArgument, isExplicit: false, isArrayIndex: false, isChecked: false, resultType: node.Type).ToExpression();
return new BoundDelegateCreationExpression(node.Syntax, loweredReceiver, methodOpt: null, isExtensionMethod: false, type: node.Type);
}
if (node.Argument.Kind == BoundKind.MethodGroup)
{
var mg = (BoundMethodGroup)node.Argument;
var method = node.MethodOpt;
Debug.Assert(method is { });
var oldSyntax = _factory.Syntax;
_factory.Syntax = (mg.ReceiverOpt ?? mg).Syntax;
var receiver = (!method.RequiresInstanceReceiver && !node.IsExtensionMethod && !method.IsAbstract) ? _factory.Type(method.ContainingType) : VisitExpression(mg.ReceiverOpt)!;
_factory.Syntax = oldSyntax;
return node.Update(receiver, method, node.IsExtensionMethod, node.Type);
}
return base.VisitDelegateCreationExpression(node)!;
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/MemberAccessExpressionSyntaxExtensions.vb | ' 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.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Partial Friend Module MemberAccessExpressionSyntaxExtensions
<Extension()>
Public Function IsConstructorInitializer(memberAccess As MemberAccessExpressionSyntax) As Boolean
Return memberAccess.IsThisConstructorInitializer() OrElse memberAccess.IsBaseConstructorInitializer()
End Function
<Extension()>
Public Function IsThisConstructorInitializer(memberAccess As MemberAccessExpressionSyntax) As Boolean
If memberAccess IsNot Nothing Then
If IsFirstStatementInConstructor(memberAccess) Then
If memberAccess.Expression.IsKind(SyntaxKind.MeExpression) OrElse
memberAccess.Expression.IsKind(SyntaxKind.MyClassExpression) Then
If memberAccess.Name.IsKind(SyntaxKind.IdentifierName) Then
Return memberAccess.Name.Identifier.HasMatchingText(SyntaxKind.NewKeyword)
End If
End If
End If
End If
Return False
End Function
<Extension()>
Public Function IsBaseConstructorInitializer(memberAccess As MemberAccessExpressionSyntax) As Boolean
If memberAccess IsNot Nothing Then
If IsFirstStatementInConstructor(memberAccess) Then
If memberAccess.Expression.IsKind(SyntaxKind.MyBaseExpression) Then
If memberAccess.Name.IsKind(SyntaxKind.IdentifierName) Then
Return memberAccess.Name.Identifier.HasMatchingText(SyntaxKind.NewKeyword)
End If
End If
End If
End If
Return False
End Function
Private Function IsFirstStatementInConstructor(memberAccess As MemberAccessExpressionSyntax) As Boolean
Dim isCall As Boolean
Dim statement As SyntaxNode
If TypeOf memberAccess.Parent Is InvocationExpressionSyntax Then
statement = memberAccess.Parent.Parent
isCall = statement IsNot Nothing AndAlso (statement.Kind = SyntaxKind.CallStatement OrElse statement.Kind = SyntaxKind.ExpressionStatement)
Else
statement = memberAccess.Parent
isCall = statement.IsKind(SyntaxKind.CallStatement)
End If
If isCall Then
Return statement.IsParentKind(SyntaxKind.ConstructorBlock) AndAlso
DirectCast(statement.Parent, ConstructorBlockSyntax).Statements.First() Is statement
End If
Return False
End Function
<Extension>
Public Function GetExpressionOfMemberAccessExpression(
memberAccessExpression As MemberAccessExpressionSyntax,
Optional allowImplicitTarget As Boolean = False) As ExpressionSyntax
If memberAccessExpression Is Nothing Then
Return Nothing
End If
If memberAccessExpression.Expression IsNot Nothing Then
Return memberAccessExpression.Expression
End If
' we have a member access expression with a null expression, this may be one of the
' following forms:
'
' 1) new With { .a = 1, .b = .a <-- .a refers to the anonymous type
' 2) With obj : .m <-- .m refers to the obj type
' 3) new T() With { .a = 1, .b = .a <-- 'a refers to the T type
If allowImplicitTarget Then
Dim conditional = memberAccessExpression.GetRootConditionalAccessExpression()
If conditional IsNot Nothing Then
If conditional.Expression Is Nothing Then
' No expression, maybe we're in a with block
Dim withBlock = conditional.GetAncestor(Of WithBlockSyntax)()
If withBlock IsNot Nothing Then
Return withBlock.WithStatement.Expression
End If
End If
Return conditional.Expression
End If
Dim current As SyntaxNode = memberAccessExpression
While current IsNot Nothing
If TypeOf current Is AnonymousObjectCreationExpressionSyntax Then
Return DirectCast(current, ExpressionSyntax)
ElseIf TypeOf current Is WithBlockSyntax Then
Dim withBlock = DirectCast(current, WithBlockSyntax)
If memberAccessExpression IsNot withBlock.WithStatement.Expression Then
Return withBlock.WithStatement.Expression
End If
ElseIf TypeOf current Is ObjectMemberInitializerSyntax AndAlso
TypeOf current.Parent Is ObjectCreationExpressionSyntax Then
Return DirectCast(current.Parent, ExpressionSyntax)
End If
current = current.Parent
End While
End If
Return Nothing
End Function
End Module
End Namespace
| ' 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.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Partial Friend Module MemberAccessExpressionSyntaxExtensions
<Extension()>
Public Function IsConstructorInitializer(memberAccess As MemberAccessExpressionSyntax) As Boolean
Return memberAccess.IsThisConstructorInitializer() OrElse memberAccess.IsBaseConstructorInitializer()
End Function
<Extension()>
Public Function IsThisConstructorInitializer(memberAccess As MemberAccessExpressionSyntax) As Boolean
If memberAccess IsNot Nothing Then
If IsFirstStatementInConstructor(memberAccess) Then
If memberAccess.Expression.IsKind(SyntaxKind.MeExpression) OrElse
memberAccess.Expression.IsKind(SyntaxKind.MyClassExpression) Then
If memberAccess.Name.IsKind(SyntaxKind.IdentifierName) Then
Return memberAccess.Name.Identifier.HasMatchingText(SyntaxKind.NewKeyword)
End If
End If
End If
End If
Return False
End Function
<Extension()>
Public Function IsBaseConstructorInitializer(memberAccess As MemberAccessExpressionSyntax) As Boolean
If memberAccess IsNot Nothing Then
If IsFirstStatementInConstructor(memberAccess) Then
If memberAccess.Expression.IsKind(SyntaxKind.MyBaseExpression) Then
If memberAccess.Name.IsKind(SyntaxKind.IdentifierName) Then
Return memberAccess.Name.Identifier.HasMatchingText(SyntaxKind.NewKeyword)
End If
End If
End If
End If
Return False
End Function
Private Function IsFirstStatementInConstructor(memberAccess As MemberAccessExpressionSyntax) As Boolean
Dim isCall As Boolean
Dim statement As SyntaxNode
If TypeOf memberAccess.Parent Is InvocationExpressionSyntax Then
statement = memberAccess.Parent.Parent
isCall = statement IsNot Nothing AndAlso (statement.Kind = SyntaxKind.CallStatement OrElse statement.Kind = SyntaxKind.ExpressionStatement)
Else
statement = memberAccess.Parent
isCall = statement.IsKind(SyntaxKind.CallStatement)
End If
If isCall Then
Return statement.IsParentKind(SyntaxKind.ConstructorBlock) AndAlso
DirectCast(statement.Parent, ConstructorBlockSyntax).Statements.First() Is statement
End If
Return False
End Function
<Extension>
Public Function GetExpressionOfMemberAccessExpression(
memberAccessExpression As MemberAccessExpressionSyntax,
Optional allowImplicitTarget As Boolean = False) As ExpressionSyntax
If memberAccessExpression Is Nothing Then
Return Nothing
End If
If memberAccessExpression.Expression IsNot Nothing Then
Return memberAccessExpression.Expression
End If
' we have a member access expression with a null expression, this may be one of the
' following forms:
'
' 1) new With { .a = 1, .b = .a <-- .a refers to the anonymous type
' 2) With obj : .m <-- .m refers to the obj type
' 3) new T() With { .a = 1, .b = .a <-- 'a refers to the T type
If allowImplicitTarget Then
Dim conditional = memberAccessExpression.GetRootConditionalAccessExpression()
If conditional IsNot Nothing Then
If conditional.Expression Is Nothing Then
' No expression, maybe we're in a with block
Dim withBlock = conditional.GetAncestor(Of WithBlockSyntax)()
If withBlock IsNot Nothing Then
Return withBlock.WithStatement.Expression
End If
End If
Return conditional.Expression
End If
Dim current As SyntaxNode = memberAccessExpression
While current IsNot Nothing
If TypeOf current Is AnonymousObjectCreationExpressionSyntax Then
Return DirectCast(current, ExpressionSyntax)
ElseIf TypeOf current Is WithBlockSyntax Then
Dim withBlock = DirectCast(current, WithBlockSyntax)
If memberAccessExpression IsNot withBlock.WithStatement.Expression Then
Return withBlock.WithStatement.Expression
End If
ElseIf TypeOf current Is ObjectMemberInitializerSyntax AndAlso
TypeOf current.Parent Is ObjectCreationExpressionSyntax Then
Return DirectCast(current.Parent, ExpressionSyntax)
End If
current = current.Parent
End While
End If
Return Nothing
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Features/VisualBasic/Portable/Completion/CompletionProviders/EmbeddedLanguageCompletionProvider.vb | ' 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.
Imports System.Composition
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
<ExportCompletionProvider(NameOf(EmbeddedLanguageCompletionProvider), LanguageNames.VisualBasic)>
<ExtensionOrder(After:=NameOf(InternalsVisibleToCompletionProvider))>
<[Shared]>
Friend Class EmbeddedLanguageCompletionProvider
Inherits AbstractEmbeddedLanguageCompletionProvider
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(<ImportMany> languageServices As IEnumerable(Of Lazy(Of ILanguageService, LanguageServiceMetadata)))
MyBase.New(languageServices, LanguageNames.VisualBasic)
End Sub
End Class
End Namespace
| ' 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.
Imports System.Composition
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
<ExportCompletionProvider(NameOf(EmbeddedLanguageCompletionProvider), LanguageNames.VisualBasic)>
<ExtensionOrder(After:=NameOf(InternalsVisibleToCompletionProvider))>
<[Shared]>
Friend Class EmbeddedLanguageCompletionProvider
Inherits AbstractEmbeddedLanguageCompletionProvider
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(<ImportMany> languageServices As IEnumerable(Of Lazy(Of ILanguageService, LanguageServiceMetadata)))
MyBase.New(languageServices, LanguageNames.VisualBasic)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/CompilationExtensions.cs | // 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.CodeAnalysis.Shared.Extensions
{
internal static class CompilationExtensions
{
/// <summary>
/// Gets a type by its metadata name to use for code analysis within a <see cref="Compilation"/>. This method
/// attempts to find the "best" symbol to use for code analysis, which is the symbol matching the first of the
/// following rules.
///
/// <list type="number">
/// <item><description>
/// If only one type with the given name is found within the compilation and its referenced assemblies, that
/// type is returned regardless of accessibility.
/// </description></item>
/// <item><description>
/// If the current <paramref name="compilation"/> defines the symbol, that symbol is returned.
/// </description></item>
/// <item><description>
/// If exactly one referenced assembly defines the symbol in a manner that makes it visible to the current
/// <paramref name="compilation"/>, that symbol is returned.
/// </description></item>
/// <item><description>
/// Otherwise, this method returns <see langword="null"/>.
/// </description></item>
/// </list>
/// </summary>
/// <param name="compilation">The <see cref="Compilation"/> to consider for analysis.</param>
/// <param name="fullyQualifiedMetadataName">The fully-qualified metadata type name to find.</param>
/// <returns>The symbol to use for code analysis; otherwise, <see langword="null"/>.</returns>
public static INamedTypeSymbol? GetBestTypeByMetadataName(this Compilation compilation, string fullyQualifiedMetadataName)
{
// Try to get the unique type with this name, ignoring accessibility
var type = compilation.GetTypeByMetadataName(fullyQualifiedMetadataName);
// Otherwise, try to get the unique type with this name originally defined in 'compilation'
type ??= compilation.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName);
// Otherwise, try to get the unique accessible type with this name from a reference
if (type is null)
{
foreach (var module in compilation.Assembly.Modules)
{
foreach (var referencedAssembly in module.ReferencedAssemblySymbols)
{
var currentType = referencedAssembly.GetTypeByMetadataName(fullyQualifiedMetadataName);
if (currentType is null)
continue;
switch (currentType.GetResultantVisibility())
{
case Utilities.SymbolVisibility.Public:
case Utilities.SymbolVisibility.Internal when referencedAssembly.GivesAccessTo(compilation.Assembly):
break;
default:
continue;
}
if (type is object)
{
// Multiple visible types with the same metadata name are present
return null;
}
type = currentType;
}
}
}
return type;
}
}
}
| // 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.CodeAnalysis.Shared.Extensions
{
internal static class CompilationExtensions
{
/// <summary>
/// Gets a type by its metadata name to use for code analysis within a <see cref="Compilation"/>. This method
/// attempts to find the "best" symbol to use for code analysis, which is the symbol matching the first of the
/// following rules.
///
/// <list type="number">
/// <item><description>
/// If only one type with the given name is found within the compilation and its referenced assemblies, that
/// type is returned regardless of accessibility.
/// </description></item>
/// <item><description>
/// If the current <paramref name="compilation"/> defines the symbol, that symbol is returned.
/// </description></item>
/// <item><description>
/// If exactly one referenced assembly defines the symbol in a manner that makes it visible to the current
/// <paramref name="compilation"/>, that symbol is returned.
/// </description></item>
/// <item><description>
/// Otherwise, this method returns <see langword="null"/>.
/// </description></item>
/// </list>
/// </summary>
/// <param name="compilation">The <see cref="Compilation"/> to consider for analysis.</param>
/// <param name="fullyQualifiedMetadataName">The fully-qualified metadata type name to find.</param>
/// <returns>The symbol to use for code analysis; otherwise, <see langword="null"/>.</returns>
public static INamedTypeSymbol? GetBestTypeByMetadataName(this Compilation compilation, string fullyQualifiedMetadataName)
{
// Try to get the unique type with this name, ignoring accessibility
var type = compilation.GetTypeByMetadataName(fullyQualifiedMetadataName);
// Otherwise, try to get the unique type with this name originally defined in 'compilation'
type ??= compilation.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName);
// Otherwise, try to get the unique accessible type with this name from a reference
if (type is null)
{
foreach (var module in compilation.Assembly.Modules)
{
foreach (var referencedAssembly in module.ReferencedAssemblySymbols)
{
var currentType = referencedAssembly.GetTypeByMetadataName(fullyQualifiedMetadataName);
if (currentType is null)
continue;
switch (currentType.GetResultantVisibility())
{
case Utilities.SymbolVisibility.Public:
case Utilities.SymbolVisibility.Internal when referencedAssembly.GivesAccessTo(compilation.Assembly):
break;
default:
continue;
}
if (type is object)
{
// Multiple visible types with the same metadata name are present
return null;
}
type = currentType;
}
}
}
return type;
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxTriviaListExtensions.cs | // 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;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SyntaxTriviaListExtensions
{
public static SyntaxTrivia? FirstOrNull(this SyntaxTriviaList triviaList, Func<SyntaxTrivia, bool> predicate)
{
foreach (var trivia in triviaList)
{
if (predicate(trivia))
{
return trivia;
}
}
return null;
}
public static SyntaxTrivia LastOrDefault(this SyntaxTriviaList triviaList)
=> triviaList.Any() ? triviaList.Last() : default;
}
}
| // 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;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SyntaxTriviaListExtensions
{
public static SyntaxTrivia? FirstOrNull(this SyntaxTriviaList triviaList, Func<SyntaxTrivia, bool> predicate)
{
foreach (var trivia in triviaList)
{
if (predicate(trivia))
{
return trivia;
}
}
return null;
}
public static SyntaxTrivia LastOrDefault(this SyntaxTriviaList triviaList)
=> triviaList.Any() ? triviaList.Last() : default;
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/VisualBasic/Test/Emit/AssemblyAttributes.vb | ' 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.
Imports Xunit
| ' 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.
Imports Xunit
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/VisualBasic/Portable/Symbols/Source/ImplementsHelper.vb | ' 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.
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Methods, Properties, and Events all have implements clauses and need to handle interface
''' implementation. This module has helper methods and extensions for sharing by multiple
''' symbol types.
''' </summary>
''' <remarks></remarks>
Friend Module ImplementsHelper
' Given a property, method, or event symbol, get the explicitly implemented symbols
Public Function GetExplicitInterfaceImplementations(member As Symbol) As ImmutableArray(Of Symbol)
Select Case member.Kind
Case SymbolKind.Method
Return StaticCast(Of Symbol).From(DirectCast(member, MethodSymbol).ExplicitInterfaceImplementations)
Case SymbolKind.Property
Return StaticCast(Of Symbol).From(DirectCast(member, PropertySymbol).ExplicitInterfaceImplementations)
Case SymbolKind.Event
Return StaticCast(Of Symbol).From(DirectCast(member, EventSymbol).ExplicitInterfaceImplementations)
Case Else
Return ImmutableArray(Of Symbol).Empty
End Select
End Function
' Given an implementing symbol, and an implemented symbol, get the location of the
' syntax in the implements clause that matches that implemented symbol. Should only use for
' symbols from source.
'
' Used for error reporting.
Public Function GetImplementingLocation(sourceSym As Symbol, implementedSym As Symbol) As Location
Debug.Assert(GetExplicitInterfaceImplementations(sourceSym).Contains(implementedSym))
Dim sourceMethod = TryCast(sourceSym, SourceMethodSymbol)
If sourceMethod IsNot Nothing Then
Return sourceMethod.GetImplementingLocation(DirectCast(implementedSym, MethodSymbol))
End If
Dim sourceProperty = TryCast(sourceSym, SourcePropertySymbol)
If sourceProperty IsNot Nothing Then
Return sourceProperty.GetImplementingLocation(DirectCast(implementedSym, PropertySymbol))
End If
Dim sourceEvent = TryCast(sourceSym, SourceEventSymbol)
If sourceEvent IsNot Nothing Then
Return sourceEvent.GetImplementingLocation(DirectCast(implementedSym, EventSymbol))
End If
' Should always pass source symbol into this function
Throw ExceptionUtilities.Unreachable
End Function
' Given an implements clause syntax on an implementing symbol, and an implemented symbol, find and return the particular name
' syntax in the implements clause that matches that implemented symbol, or Nothing if none match.
'
' Used for error reporting.
Public Function FindImplementingSyntax(Of TSymbol As Symbol)(implementsClause As ImplementsClauseSyntax,
implementingSym As TSymbol,
implementedSym As TSymbol,
container As SourceMemberContainerTypeSymbol,
binder As Binder) As QualifiedNameSyntax
Debug.Assert(implementedSym IsNot Nothing)
Dim dummyResultKind As LookupResultKind
' Bind each syntax again and compare them.
For Each implementedMethodSyntax As QualifiedNameSyntax In implementsClause.InterfaceMembers
' don't care about diagnostics
Dim implementedMethod As TSymbol = FindExplicitlyImplementedMember(implementingSym, container, implementedMethodSyntax, binder, BindingDiagnosticBag.Discarded, Nothing, dummyResultKind)
If implementedMethod = implementedSym Then
Return implementedMethodSyntax
End If
Next
Return Nothing
End Function
' Given a symbol in the process of being constructed, bind the Implements clause
' on it and diagnose any errors. Returns the list of implemented members.
Public Function ProcessImplementsClause(Of TSymbol As Symbol)(implementsClause As ImplementsClauseSyntax,
implementingSym As TSymbol,
container As SourceMemberContainerTypeSymbol,
binder As Binder,
diagBag As BindingDiagnosticBag) As ImmutableArray(Of TSymbol)
Debug.Assert(implementsClause IsNot Nothing)
If container.IsInterface Then
' Members in interfaces cannot have an implements clause (each member has its own error code)
Dim errorid As ERRID
If implementingSym.Kind = SymbolKind.Method Then
errorid = ERRID.ERR_BadInterfaceMethodFlags1
ElseIf implementingSym.Kind = SymbolKind.Property Then
errorid = ERRID.ERR_BadInterfacePropertyFlags1
Else
errorid = ERRID.ERR_InterfaceCantUseEventSpecifier1
End If
Binder.ReportDiagnostic(diagBag, implementsClause, errorid, implementsClause.ImplementsKeyword.ToString())
Return ImmutableArray(Of TSymbol).Empty
ElseIf container.IsModuleType Then
' Methods in Std Modules can't implement interfaces
Binder.ReportDiagnostic(diagBag,
implementsClause.ImplementsKeyword,
ERRID.ERR_ModuleMemberCantImplement)
Return ImmutableArray(Of TSymbol).Empty
Else
' Process the IMPLEMENTS lists
Dim implementedMembers As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance()
Dim dummyResultKind As LookupResultKind
Dim firstImplementedMemberIsWindowsRuntimeEvent As ThreeState = ThreeState.Unknown
Dim implementingSymIsEvent = (implementingSym.Kind = SymbolKind.Event)
For Each implementedMemberSyntax As QualifiedNameSyntax In implementsClause.InterfaceMembers
Dim implementedMember As TSymbol = FindExplicitlyImplementedMember(implementingSym, container, implementedMemberSyntax, binder, diagBag, Nothing, dummyResultKind)
If implementedMember IsNot Nothing Then
implementedMembers.Add(implementedMember)
' Process Obsolete attribute on implements clause
Binder.ReportDiagnosticsIfObsolete(diagBag, implementingSym, implementedMember, implementsClause)
If implementingSymIsEvent Then
Debug.Assert(implementedMember.Kind = SymbolKind.Event)
If Not firstImplementedMemberIsWindowsRuntimeEvent.HasValue() Then
firstImplementedMemberIsWindowsRuntimeEvent = TryCast(implementedMember, EventSymbol).IsWindowsRuntimeEvent.ToThreeState()
Else
Dim currIsWinRT As Boolean = TryCast(implementedMember, EventSymbol).IsWindowsRuntimeEvent
Dim firstIsWinRT As Boolean = firstImplementedMemberIsWindowsRuntimeEvent.Value()
If currIsWinRT <> firstIsWinRT Then
Binder.ReportDiagnostic(diagBag,
implementedMemberSyntax,
ERRID.ERR_MixingWinRTAndNETEvents,
CustomSymbolDisplayFormatter.ShortErrorName(implementingSym),
CustomSymbolDisplayFormatter.QualifiedName(If(firstIsWinRT, implementedMembers(0), implementedMember)),
CustomSymbolDisplayFormatter.QualifiedName(If(firstIsWinRT, implementedMember, implementedMembers(0))))
End If
End If
End If
End If
Next
Return implementedMembers.ToImmutableAndFree()
End If
End Function
''' <summary>
''' Find the implemented method denoted by "implementedMemberSyntax" that matches implementingSym.
''' Returns the implemented method, or Nothing if none.
'''
''' Also stores into "candidateSymbols" (if not Nothing) and resultKind the symbols and result kind that
''' should be used for semantic model purposes.
''' </summary>
Public Function FindExplicitlyImplementedMember(Of TSymbol As Symbol)(implementingSym As TSymbol,
containingType As NamedTypeSymbol,
implementedMemberSyntax As QualifiedNameSyntax,
binder As Binder,
diagBag As BindingDiagnosticBag,
candidateSymbols As ArrayBuilder(Of Symbol),
ByRef resultKind As LookupResultKind) As TSymbol
resultKind = LookupResultKind.Good
Dim interfaceName As NameSyntax = implementedMemberSyntax.Left
Dim implementedMethodName As String = implementedMemberSyntax.Right.Identifier.ValueText
Dim interfaceType As TypeSymbol = binder.BindTypeSyntax(interfaceName, diagBag)
If interfaceType.IsInterfaceType() Then
Dim errorReported As Boolean = False ' was an error already reported?
Dim interfaceNamedType As NamedTypeSymbol = DirectCast(interfaceType, NamedTypeSymbol)
If Not containingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics(interfaceNamedType).Contains(interfaceNamedType) Then
' Class doesn't implement the interface that was named
Binder.ReportDiagnostic(diagBag, interfaceName, ERRID.ERR_InterfaceNotImplemented1,
interfaceType)
resultKind = LookupResultKind.NotReferencable
errorReported = True
' continue on...
End If
' Do lookup of the specified name in the interface (note it could be in a base interface thereof)
Dim lookup As LookupResult = LookupResult.GetInstance()
Dim foundMember As TSymbol = Nothing ' the correctly matching method we found
' NOTE(cyrusn): We pass 'IgnoreAccessibility' here to provide a better experience
' for the IDE. For correct code it won't matter (as interface members are always
' public in correct code). However, in incorrect code it makes sure we can hook up
' the implements clause to a private member.
Dim options As LookupOptions = LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreAccessibility Or LookupOptions.IgnoreExtensionMethods
If implementingSym.Kind = SymbolKind.Event Then
options = CType(options Or LookupOptions.EventsOnly, LookupOptions)
End If
Dim useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagBag)
binder.LookupMember(lookup, interfaceType, implementedMethodName, -1, options, useSiteInfo)
If lookup.IsAmbiguous Then
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_AmbiguousImplementsMember3,
implementedMethodName,
implementedMethodName)
If candidateSymbols IsNot Nothing Then
candidateSymbols.AddRange(DirectCast(lookup.Diagnostic, AmbiguousSymbolDiagnostic).AmbiguousSymbols)
End If
resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.Ambiguous)
errorReported = True
ElseIf lookup.IsGood Then
' Check each method found to see if it matches signature of methodSym
Dim candidates As ArrayBuilder(Of TSymbol) = Nothing
For Each possibleMatch In lookup.Symbols
Dim possibleMatchMember = TryCast(possibleMatch, TSymbol)
If possibleMatchMember IsNot Nothing AndAlso
possibleMatchMember.ContainingType.IsInterface AndAlso
MembersAreMatchingForPurposesOfInterfaceImplementation(implementingSym, possibleMatchMember) Then
If candidates Is Nothing Then
candidates = ArrayBuilder(Of TSymbol).GetInstance()
End If
candidates.Add(possibleMatchMember)
End If
Next
Dim candidatesCount As Integer = If(candidates IsNot Nothing, candidates.Count, 0)
' If we have more than one candidate, eliminate candidates from least derived interfaces
If candidatesCount > 1 Then
For i As Integer = 0 To candidates.Count - 2
Dim first As TSymbol = candidates(i)
If first Is Nothing Then
Continue For ' has been eliminated already
End If
For j As Integer = i + 1 To candidates.Count - 1
Dim second As TSymbol = candidates(j)
If second Is Nothing Then
Continue For ' has been eliminated already
End If
If second.ContainingType.ImplementsInterface(first.ContainingType, comparer:=Nothing, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
candidates(i) = Nothing
candidatesCount -= 1
GoTo Next_i
ElseIf first.ContainingType.ImplementsInterface(second.ContainingType, comparer:=Nothing, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
candidates(j) = Nothing
candidatesCount -= 1
End If
Next
Next_i:
Next
End If
' If we still have more than one candidate, they are either from the same type (type substitution can create two methods with same signature),
' or from unrelated base interfaces
If candidatesCount > 1 Then
For i As Integer = 0 To candidates.Count - 2
Dim first As TSymbol = candidates(i)
If first Is Nothing Then
Continue For ' has been eliminated already
End If
If foundMember Is Nothing Then
foundMember = first
End If
For j As Integer = i + 1 To candidates.Count - 1
Dim second As TSymbol = candidates(j)
If second Is Nothing Then
Continue For ' has been eliminated already
End If
If TypeSymbol.Equals(first.ContainingType, second.ContainingType, TypeCompareKind.ConsiderEverything) Then
' type substitution can create two methods with same signature in the same type
' report ambiguity
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_AmbiguousImplements3,
CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(first.ContainingType),
implementedMethodName,
CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(first.ContainingType),
first,
second)
errorReported = True
resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.OverloadResolutionFailure)
GoTo DoneWithErrorReporting
End If
Next
Next
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_AmbiguousImplementsMember3,
implementedMethodName,
implementedMethodName)
resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.Ambiguous)
errorReported = True
DoneWithErrorReporting:
If candidateSymbols IsNot Nothing Then
candidateSymbols.AddRange(lookup.Symbols)
End If
ElseIf candidatesCount = 1 Then
For i As Integer = 0 To candidates.Count - 1
Dim first As TSymbol = candidates(i)
If first Is Nothing Then
Continue For ' has been eliminated already
End If
foundMember = first
Exit For
Next
Else
Debug.Assert(candidatesCount = 0)
' No matching members. Remember non-matching members for semantic model questions.
If candidateSymbols IsNot Nothing Then
candidateSymbols.AddRange(lookup.Symbols)
End If
resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.OverloadResolutionFailure)
End If
If candidates IsNot Nothing Then
candidates.Free()
End If
If foundMember IsNot Nothing Then
Dim coClassContext As Boolean = interfaceNamedType.CoClassType IsNot Nothing
If coClassContext AndAlso (implementingSym.Kind = SymbolKind.Event) <> (foundMember.Kind = SymbolKind.Event) Then
' Following Dev11 implementation: in COM Interface context if the implementing symbol
' is an event and the found candidate is not (or vice versa) we just pretend we didn't
' find anything and fall back to the default error
foundMember = Nothing
End If
If Not errorReported Then
' Further verification of found method.
foundMember = ValidateImplementedMember(implementingSym, foundMember, implementedMemberSyntax, binder, diagBag, interfaceType, implementedMethodName, errorReported)
End If
If foundMember IsNot Nothing Then
' Record found member for semantic model questions.
If candidateSymbols IsNot Nothing Then
candidateSymbols.Add(foundMember)
End If
resultKind = LookupResult.WorseResultKind(resultKind, lookup.Kind)
If Not binder.IsAccessible(foundMember, useSiteInfo) Then
resultKind = LookupResult.WorseResultKind(resultKind, LookupResultKind.Inaccessible) ' we specified IgnoreAccessibility above.
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, binder.GetInaccessibleErrorInfo(foundMember))
ElseIf foundMember.Kind = SymbolKind.Property Then
Dim [property] = DirectCast(DirectCast(foundMember, Symbol), PropertySymbol)
Dim accessorToCheck As MethodSymbol = [property].GetMethod
If accessorToCheck Is Nothing OrElse
accessorToCheck.DeclaredAccessibility = [property].DeclaredAccessibility OrElse
Not accessorToCheck.RequiresImplementation() Then
accessorToCheck = [property].SetMethod
End If
If accessorToCheck IsNot Nothing AndAlso
accessorToCheck.DeclaredAccessibility <> [property].DeclaredAccessibility AndAlso
accessorToCheck.RequiresImplementation() AndAlso
Not binder.IsAccessible(accessorToCheck, useSiteInfo) Then
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, binder.GetInaccessibleErrorInfo(accessorToCheck))
End If
End If
End If
End If
End If
diagBag.Add(interfaceName, useSiteInfo)
lookup.Free()
If foundMember Is Nothing And Not errorReported Then
' Didn't find a method (or it was otherwise bad in some way)
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_IdentNotMemberOfInterface4,
CustomSymbolDisplayFormatter.ShortErrorName(implementingSym), implementedMethodName,
implementingSym.GetKindText(),
CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(interfaceType))
End If
Return foundMember
ElseIf interfaceType.TypeKind = TypeKind.Error Then
' BindType already reported an error, so don't report another one
Return Nothing
Else
' type is some other type rather than an interface
Binder.ReportDiagnostic(diagBag, interfaceName, ERRID.ERR_BadImplementsType)
Return Nothing
End If
End Function
''' <summary>
''' Does 'implementingSym' match 'implementedSym' well enough to be considered a match for interface implementation?
''' </summary>
Private Function MembersAreMatchingForPurposesOfInterfaceImplementation(implementingSym As Symbol,
implementedSym As Symbol) As Boolean
Return MembersAreMatching(implementingSym, implementedSym, Not SymbolComparisonResults.MismatchesForExplicitInterfaceImplementations, EventSignatureComparer.ExplicitEventImplementationComparer)
End Function
Private Function MembersHaveMatchingTupleNames(implementingSym As Symbol,
implementedSym As Symbol) As Boolean
Return MembersAreMatching(implementingSym, implementedSym, SymbolComparisonResults.TupleNamesMismatch, EventSignatureComparer.ExplicitEventImplementationWithTupleNamesComparer)
End Function
Private Function MembersAreMatching(implementingSym As Symbol,
implementedSym As Symbol,
comparisons As SymbolComparisonResults,
eventComparer As EventSignatureComparer) As Boolean
Debug.Assert(implementingSym.Kind = implementedSym.Kind)
Select Case implementingSym.Kind
Case SymbolKind.Method
Dim results = MethodSignatureComparer.DetailedCompare(DirectCast(implementedSym, MethodSymbol), DirectCast(implementingSym, MethodSymbol),
comparisons,
comparisons)
Return (results = 0)
Case SymbolKind.Property
Dim results = PropertySignatureComparer.DetailedCompare(DirectCast(implementedSym, PropertySymbol), DirectCast(implementingSym, PropertySymbol),
comparisons,
comparisons)
Return (results = 0)
Case SymbolKind.Event
Return eventComparer.Equals(DirectCast(implementedSym, EventSymbol), DirectCast(implementingSym, EventSymbol))
Case Else
Throw ExceptionUtilities.UnexpectedValue(implementingSym.Kind)
End Select
End Function
''' <summary>
''' Perform additional validate of implementedSym and issue diagnostics.
''' Return "implementedSym" if the symbol table should record implementedSym as the implemented
''' symbol (even if diagnostics were issues). Returns Nothing if the code should not treat
''' implementedSym as the implemented symbol.
''' </summary>
Private Function ValidateImplementedMember(Of TSymbol As Symbol)(implementingSym As TSymbol,
implementedSym As TSymbol,
implementedMemberSyntax As QualifiedNameSyntax,
binder As Binder,
diagBag As BindingDiagnosticBag,
interfaceType As TypeSymbol,
implementedMethodName As String,
ByRef errorReported As Boolean) As TSymbol
If Not implementedSym.RequiresImplementation() Then
' TODO: Perhaps give ERR_CantImplementNonVirtual3 like Dev10. But, this message seems more
' TODO: confusing than useful, so for now, just treat it like a method that doesn't exist.
Return Nothing
End If
' Validate that implementing property implements all accessors of the implemented property
If implementedSym.Kind = SymbolKind.Property Then
Dim implementedProperty As PropertySymbol = TryCast(implementedSym, PropertySymbol)
Dim implementedPropertyGetMethod As MethodSymbol = implementedProperty.GetMethod
If Not implementedPropertyGetMethod?.RequiresImplementation() Then
implementedPropertyGetMethod = Nothing
End If
Dim implementedPropertySetMethod As MethodSymbol = implementedProperty.SetMethod
If Not implementedPropertySetMethod?.RequiresImplementation() Then
implementedPropertySetMethod = Nothing
End If
Dim implementingProperty As PropertySymbol = TryCast(implementingSym, PropertySymbol)
If (implementedPropertyGetMethod IsNot Nothing AndAlso implementingProperty.GetMethod Is Nothing) OrElse
(implementedPropertySetMethod IsNot Nothing AndAlso implementingProperty.SetMethod Is Nothing) Then
' "'{0}' cannot be implemented by a {1} property."
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_PropertyDoesntImplementAllAccessors,
implementedProperty,
implementingProperty.GetPropertyKindText())
errorReported = True
ElseIf ((implementedPropertyGetMethod Is Nothing) Xor (implementedPropertySetMethod Is Nothing)) AndAlso
implementingProperty.GetMethod IsNot Nothing AndAlso implementingProperty.SetMethod IsNot Nothing Then
errorReported = errorReported Or
Not InternalSyntax.Parser.CheckFeatureAvailability(diagBag, implementedMemberSyntax.GetLocation(),
DirectCast(implementedMemberSyntax.SyntaxTree, VisualBasicSyntaxTree).Options.LanguageVersion,
InternalSyntax.Feature.ImplementingReadonlyOrWriteonlyPropertyWithReadwrite)
End If
If implementedPropertySetMethod?.IsInitOnly <> implementingProperty.SetMethod?.IsInitOnly Then
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_PropertyDoesntImplementInitOnly,
implementedProperty)
errorReported = True
End If
End If
If implementedSym IsNot Nothing AndAlso implementingSym.ContainsTupleNames() AndAlso
Not MembersHaveMatchingTupleNames(implementingSym, implementedSym) Then
' it is ok to implement with no tuple names, for compatibility with VB 14, but otherwise names should match
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_ImplementingInterfaceWithDifferentTupleNames5,
CustomSymbolDisplayFormatter.ShortErrorName(implementingSym),
implementingSym.GetKindText(),
implementedMethodName,
CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(interfaceType),
implementingSym,
implementedSym)
errorReported = True
End If
' TODO: If implementing event, check that delegate types are consistent, or maybe set the delegate type. See Dev10 compiler
' TODO: in ImplementsSemantics.cpp, Bindable::BindImplements.
' Method type parameter constraints are validated later, in ValidateImplementedMethodConstraints,
' after the ExplicitInterfaceImplementations property has been set on the implementing method.
Return implementedSym
End Function
''' <summary>
''' Validate method type parameter constraints. This is handled outside
''' of ValidateImplementedMember because that method is invoked
''' while computing the ExplicitInterfaceImplementations value on the
''' implementing method, but method type parameters rely on the value
''' of ExplicitInterfaceImplementations to determine constraints correctly.
''' </summary>
Public Sub ValidateImplementedMethodConstraints(implementingMethod As SourceMethodSymbol,
implementedMethod As MethodSymbol,
diagBag As BindingDiagnosticBag)
If Not MethodSignatureComparer.HaveSameConstraints(implementedMethod, implementingMethod) Then
' "'{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints."
Dim loc = implementingMethod.GetImplementingLocation(implementedMethod)
diagBag.Add(
ErrorFactory.ErrorInfo(ERRID.ERR_ImplementsWithConstraintMismatch3, implementingMethod, implementedMethod.ContainingType, implementedMethod),
loc)
End If
End Sub
''' <summary>
''' Performs interface mapping to determine which symbol in this type or a base type
''' actually implements a particular interface member.
''' </summary>
''' <typeparam name="TSymbol">MethodSymbol or PropertySymbol or EventSymbol (an interface member).</typeparam>
''' <param name="interfaceMember">A non-null member on an interface type.</param>
''' <param name="implementingType">The type implementing the interface member.</param>
''' <param name="comparer">A comparer for comparing signatures of TSymbol according to metadata implementation rules.</param>
''' <returns>The implementing member or Nothing, if there isn't one.</returns>
Public Function ComputeImplementationForInterfaceMember(Of TSymbol As Symbol)(interfaceMember As TSymbol,
implementingType As TypeSymbol,
comparer As IEqualityComparer(Of TSymbol)) As TSymbol
Debug.Assert(TypeOf interfaceMember Is PropertySymbol OrElse
TypeOf interfaceMember Is MethodSymbol OrElse
TypeOf interfaceMember Is EventSymbol)
Dim interfaceType As NamedTypeSymbol = interfaceMember.ContainingType
Debug.Assert(interfaceType IsNot Nothing AndAlso interfaceType.IsInterface)
Dim seenMDTypeDeclaringInterface As Boolean = False
Dim currType As TypeSymbol = implementingType
' Go up the inheritance chain, looking for an implementation of the member.
While currType IsNot Nothing
' First, check for explicit interface implementation.
Dim currTypeExplicitImpl As MultiDictionary(Of Symbol, Symbol).ValueSet = currType.ExplicitInterfaceImplementationMap(interfaceMember)
If currTypeExplicitImpl.Count = 1 Then
Return DirectCast(currTypeExplicitImpl.Single(), TSymbol)
ElseIf currTypeExplicitImpl.Count > 1 Then
Return Nothing
End If
' VB only supports explicit interface implementation, but for the purpose of finding implementation, we must
' check implicit implementation for members from metadata. We only want to consider metadata implementations
' if a metadata implementation (or a derived metadata implementation) actually implements the given interface
' (not a derived interface), since this is the metadata rule from Partition II, section 12.2.
'
' Consider:
' Interface IGoo ' from metadata
' Sub Goo()
' Class A ' from metadata
' Public Sub Goo()
' Class B: Inherits A: Implements IGoo ' from metadata
' Class C: Inherits B ' from metadata
' Public Shadows Sub Goo()
' Class D: Inherits C: Implements IGoo ' from source
' In this case, A.Goo is the correct implementation of IGoo.Goo within D.
' NOTE: Ideally, we'd like to distinguish between the "current" compilation and other assemblies
' (including other compilations), rather than source and metadata, but there are two reasons that
' that won't work in this case:
' 1) We really don't want consumers of the API to have to pass in the current compilation when
' they ask questions about interface implementation.
' 2) NamedTypeSymbol.Interfaces does not round-trip in the presence of implicit interface
' implementations. As in dev11, we drop interfaces from the interface list if any of their
' members are implemented in a base type (so that CLR implicit implementation will pick the
' same method as the VB language).
If Not currType.Dangerous_IsFromSomeCompilationIncludingRetargeting AndAlso
currType.InterfacesNoUseSiteDiagnostics.Contains(interfaceType, EqualsIgnoringComparer.InstanceCLRSignatureCompare) Then
seenMDTypeDeclaringInterface = True
End If
If seenMDTypeDeclaringInterface Then
'check for implicit impls (name must match)
Dim currTypeImplicitImpl As TSymbol
currTypeImplicitImpl = FindImplicitImplementationDeclaredInType(interfaceMember, currType, comparer)
If currTypeImplicitImpl IsNot Nothing Then
Return currTypeImplicitImpl
End If
End If
currType = currType.BaseTypeNoUseSiteDiagnostics
End While
Return Nothing
End Function
''' <summary>
''' Search the declared methods of a type for one that could be an implicit implementation
''' of a given interface method (depending on interface declarations). It is assumed that the implementing
''' type is not a source type.
''' </summary>
''' <typeparam name="TSymbol">MethodSymbol or PropertySymbol or EventSymbol (an interface member).</typeparam>
''' <param name="interfaceMember">The interface member being implemented.</param>
''' <param name="currType">The type on which we are looking for a declared implementation of the interface method.</param>
''' <param name="comparer">A comparer for comparing signatures of TSymbol according to metadata implementation rules.</param>
Private Function FindImplicitImplementationDeclaredInType(Of TSymbol As Symbol)(interfaceMember As TSymbol,
currType As TypeSymbol,
comparer As IEqualityComparer(Of TSymbol)) As TSymbol '
Debug.Assert(Not currType.Dangerous_IsFromSomeCompilationIncludingRetargeting)
For Each member In currType.GetMembers(interfaceMember.Name)
If member.DeclaredAccessibility = Accessibility.Public AndAlso
Not member.IsShared AndAlso
TypeOf member Is TSymbol AndAlso
comparer.Equals(interfaceMember, DirectCast(member, TSymbol)) Then
Return DirectCast(member, TSymbol)
End If
Next
Return Nothing
End Function
''' <summary>
''' Given a set of explicit interface implementations that are undergoing substitution, return the substituted versions.
''' </summary>
''' <typeparam name="TSymbol">Type of the interface members (Method, Property, Event)</typeparam>
''' <param name="unsubstitutedImplementations">The ROA of members that are being implemented</param>
''' <param name="substitution">The type substitution</param>
''' <returns>The substituted members.</returns>
Public Function SubstituteExplicitInterfaceImplementations(Of TSymbol As Symbol)(unsubstitutedImplementations As ImmutableArray(Of TSymbol),
substitution As TypeSubstitution) As ImmutableArray(Of TSymbol)
If unsubstitutedImplementations.Length = 0 Then
Return ImmutableArray(Of TSymbol).Empty
Else
Dim substitutedImplementations(0 To unsubstitutedImplementations.Length - 1) As TSymbol
For i As Integer = 0 To unsubstitutedImplementations.Length - 1
Dim unsubstitutedMember As TSymbol = unsubstitutedImplementations(i)
Dim unsubstitutedInterfaceType = unsubstitutedMember.ContainingType
substitutedImplementations(i) = unsubstitutedImplementations(i) ' default: no substitution necessary
If unsubstitutedInterfaceType.IsGenericType Then
Dim substitutedInterfaceType = TryCast(unsubstitutedInterfaceType.InternalSubstituteTypeParameters(substitution).AsTypeSymbolOnly(), SubstitutedNamedType)
If substitutedInterfaceType IsNot Nothing Then
' Get the substituted version of the member
substitutedImplementations(i) = DirectCast(substitutedInterfaceType.GetMemberForDefinition(unsubstitutedMember.OriginalDefinition), TSymbol)
End If
End If
Next
Return ImmutableArray.Create(Of TSymbol)(substitutedImplementations)
End If
End Function
End Module
End Namespace
| ' 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.
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Methods, Properties, and Events all have implements clauses and need to handle interface
''' implementation. This module has helper methods and extensions for sharing by multiple
''' symbol types.
''' </summary>
''' <remarks></remarks>
Friend Module ImplementsHelper
' Given a property, method, or event symbol, get the explicitly implemented symbols
Public Function GetExplicitInterfaceImplementations(member As Symbol) As ImmutableArray(Of Symbol)
Select Case member.Kind
Case SymbolKind.Method
Return StaticCast(Of Symbol).From(DirectCast(member, MethodSymbol).ExplicitInterfaceImplementations)
Case SymbolKind.Property
Return StaticCast(Of Symbol).From(DirectCast(member, PropertySymbol).ExplicitInterfaceImplementations)
Case SymbolKind.Event
Return StaticCast(Of Symbol).From(DirectCast(member, EventSymbol).ExplicitInterfaceImplementations)
Case Else
Return ImmutableArray(Of Symbol).Empty
End Select
End Function
' Given an implementing symbol, and an implemented symbol, get the location of the
' syntax in the implements clause that matches that implemented symbol. Should only use for
' symbols from source.
'
' Used for error reporting.
Public Function GetImplementingLocation(sourceSym As Symbol, implementedSym As Symbol) As Location
Debug.Assert(GetExplicitInterfaceImplementations(sourceSym).Contains(implementedSym))
Dim sourceMethod = TryCast(sourceSym, SourceMethodSymbol)
If sourceMethod IsNot Nothing Then
Return sourceMethod.GetImplementingLocation(DirectCast(implementedSym, MethodSymbol))
End If
Dim sourceProperty = TryCast(sourceSym, SourcePropertySymbol)
If sourceProperty IsNot Nothing Then
Return sourceProperty.GetImplementingLocation(DirectCast(implementedSym, PropertySymbol))
End If
Dim sourceEvent = TryCast(sourceSym, SourceEventSymbol)
If sourceEvent IsNot Nothing Then
Return sourceEvent.GetImplementingLocation(DirectCast(implementedSym, EventSymbol))
End If
' Should always pass source symbol into this function
Throw ExceptionUtilities.Unreachable
End Function
' Given an implements clause syntax on an implementing symbol, and an implemented symbol, find and return the particular name
' syntax in the implements clause that matches that implemented symbol, or Nothing if none match.
'
' Used for error reporting.
Public Function FindImplementingSyntax(Of TSymbol As Symbol)(implementsClause As ImplementsClauseSyntax,
implementingSym As TSymbol,
implementedSym As TSymbol,
container As SourceMemberContainerTypeSymbol,
binder As Binder) As QualifiedNameSyntax
Debug.Assert(implementedSym IsNot Nothing)
Dim dummyResultKind As LookupResultKind
' Bind each syntax again and compare them.
For Each implementedMethodSyntax As QualifiedNameSyntax In implementsClause.InterfaceMembers
' don't care about diagnostics
Dim implementedMethod As TSymbol = FindExplicitlyImplementedMember(implementingSym, container, implementedMethodSyntax, binder, BindingDiagnosticBag.Discarded, Nothing, dummyResultKind)
If implementedMethod = implementedSym Then
Return implementedMethodSyntax
End If
Next
Return Nothing
End Function
' Given a symbol in the process of being constructed, bind the Implements clause
' on it and diagnose any errors. Returns the list of implemented members.
Public Function ProcessImplementsClause(Of TSymbol As Symbol)(implementsClause As ImplementsClauseSyntax,
implementingSym As TSymbol,
container As SourceMemberContainerTypeSymbol,
binder As Binder,
diagBag As BindingDiagnosticBag) As ImmutableArray(Of TSymbol)
Debug.Assert(implementsClause IsNot Nothing)
If container.IsInterface Then
' Members in interfaces cannot have an implements clause (each member has its own error code)
Dim errorid As ERRID
If implementingSym.Kind = SymbolKind.Method Then
errorid = ERRID.ERR_BadInterfaceMethodFlags1
ElseIf implementingSym.Kind = SymbolKind.Property Then
errorid = ERRID.ERR_BadInterfacePropertyFlags1
Else
errorid = ERRID.ERR_InterfaceCantUseEventSpecifier1
End If
Binder.ReportDiagnostic(diagBag, implementsClause, errorid, implementsClause.ImplementsKeyword.ToString())
Return ImmutableArray(Of TSymbol).Empty
ElseIf container.IsModuleType Then
' Methods in Std Modules can't implement interfaces
Binder.ReportDiagnostic(diagBag,
implementsClause.ImplementsKeyword,
ERRID.ERR_ModuleMemberCantImplement)
Return ImmutableArray(Of TSymbol).Empty
Else
' Process the IMPLEMENTS lists
Dim implementedMembers As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance()
Dim dummyResultKind As LookupResultKind
Dim firstImplementedMemberIsWindowsRuntimeEvent As ThreeState = ThreeState.Unknown
Dim implementingSymIsEvent = (implementingSym.Kind = SymbolKind.Event)
For Each implementedMemberSyntax As QualifiedNameSyntax In implementsClause.InterfaceMembers
Dim implementedMember As TSymbol = FindExplicitlyImplementedMember(implementingSym, container, implementedMemberSyntax, binder, diagBag, Nothing, dummyResultKind)
If implementedMember IsNot Nothing Then
implementedMembers.Add(implementedMember)
' Process Obsolete attribute on implements clause
Binder.ReportDiagnosticsIfObsolete(diagBag, implementingSym, implementedMember, implementsClause)
If implementingSymIsEvent Then
Debug.Assert(implementedMember.Kind = SymbolKind.Event)
If Not firstImplementedMemberIsWindowsRuntimeEvent.HasValue() Then
firstImplementedMemberIsWindowsRuntimeEvent = TryCast(implementedMember, EventSymbol).IsWindowsRuntimeEvent.ToThreeState()
Else
Dim currIsWinRT As Boolean = TryCast(implementedMember, EventSymbol).IsWindowsRuntimeEvent
Dim firstIsWinRT As Boolean = firstImplementedMemberIsWindowsRuntimeEvent.Value()
If currIsWinRT <> firstIsWinRT Then
Binder.ReportDiagnostic(diagBag,
implementedMemberSyntax,
ERRID.ERR_MixingWinRTAndNETEvents,
CustomSymbolDisplayFormatter.ShortErrorName(implementingSym),
CustomSymbolDisplayFormatter.QualifiedName(If(firstIsWinRT, implementedMembers(0), implementedMember)),
CustomSymbolDisplayFormatter.QualifiedName(If(firstIsWinRT, implementedMember, implementedMembers(0))))
End If
End If
End If
End If
Next
Return implementedMembers.ToImmutableAndFree()
End If
End Function
''' <summary>
''' Find the implemented method denoted by "implementedMemberSyntax" that matches implementingSym.
''' Returns the implemented method, or Nothing if none.
'''
''' Also stores into "candidateSymbols" (if not Nothing) and resultKind the symbols and result kind that
''' should be used for semantic model purposes.
''' </summary>
Public Function FindExplicitlyImplementedMember(Of TSymbol As Symbol)(implementingSym As TSymbol,
containingType As NamedTypeSymbol,
implementedMemberSyntax As QualifiedNameSyntax,
binder As Binder,
diagBag As BindingDiagnosticBag,
candidateSymbols As ArrayBuilder(Of Symbol),
ByRef resultKind As LookupResultKind) As TSymbol
resultKind = LookupResultKind.Good
Dim interfaceName As NameSyntax = implementedMemberSyntax.Left
Dim implementedMethodName As String = implementedMemberSyntax.Right.Identifier.ValueText
Dim interfaceType As TypeSymbol = binder.BindTypeSyntax(interfaceName, diagBag)
If interfaceType.IsInterfaceType() Then
Dim errorReported As Boolean = False ' was an error already reported?
Dim interfaceNamedType As NamedTypeSymbol = DirectCast(interfaceType, NamedTypeSymbol)
If Not containingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics(interfaceNamedType).Contains(interfaceNamedType) Then
' Class doesn't implement the interface that was named
Binder.ReportDiagnostic(diagBag, interfaceName, ERRID.ERR_InterfaceNotImplemented1,
interfaceType)
resultKind = LookupResultKind.NotReferencable
errorReported = True
' continue on...
End If
' Do lookup of the specified name in the interface (note it could be in a base interface thereof)
Dim lookup As LookupResult = LookupResult.GetInstance()
Dim foundMember As TSymbol = Nothing ' the correctly matching method we found
' NOTE(cyrusn): We pass 'IgnoreAccessibility' here to provide a better experience
' for the IDE. For correct code it won't matter (as interface members are always
' public in correct code). However, in incorrect code it makes sure we can hook up
' the implements clause to a private member.
Dim options As LookupOptions = LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreAccessibility Or LookupOptions.IgnoreExtensionMethods
If implementingSym.Kind = SymbolKind.Event Then
options = CType(options Or LookupOptions.EventsOnly, LookupOptions)
End If
Dim useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagBag)
binder.LookupMember(lookup, interfaceType, implementedMethodName, -1, options, useSiteInfo)
If lookup.IsAmbiguous Then
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_AmbiguousImplementsMember3,
implementedMethodName,
implementedMethodName)
If candidateSymbols IsNot Nothing Then
candidateSymbols.AddRange(DirectCast(lookup.Diagnostic, AmbiguousSymbolDiagnostic).AmbiguousSymbols)
End If
resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.Ambiguous)
errorReported = True
ElseIf lookup.IsGood Then
' Check each method found to see if it matches signature of methodSym
Dim candidates As ArrayBuilder(Of TSymbol) = Nothing
For Each possibleMatch In lookup.Symbols
Dim possibleMatchMember = TryCast(possibleMatch, TSymbol)
If possibleMatchMember IsNot Nothing AndAlso
possibleMatchMember.ContainingType.IsInterface AndAlso
MembersAreMatchingForPurposesOfInterfaceImplementation(implementingSym, possibleMatchMember) Then
If candidates Is Nothing Then
candidates = ArrayBuilder(Of TSymbol).GetInstance()
End If
candidates.Add(possibleMatchMember)
End If
Next
Dim candidatesCount As Integer = If(candidates IsNot Nothing, candidates.Count, 0)
' If we have more than one candidate, eliminate candidates from least derived interfaces
If candidatesCount > 1 Then
For i As Integer = 0 To candidates.Count - 2
Dim first As TSymbol = candidates(i)
If first Is Nothing Then
Continue For ' has been eliminated already
End If
For j As Integer = i + 1 To candidates.Count - 1
Dim second As TSymbol = candidates(j)
If second Is Nothing Then
Continue For ' has been eliminated already
End If
If second.ContainingType.ImplementsInterface(first.ContainingType, comparer:=Nothing, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
candidates(i) = Nothing
candidatesCount -= 1
GoTo Next_i
ElseIf first.ContainingType.ImplementsInterface(second.ContainingType, comparer:=Nothing, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
candidates(j) = Nothing
candidatesCount -= 1
End If
Next
Next_i:
Next
End If
' If we still have more than one candidate, they are either from the same type (type substitution can create two methods with same signature),
' or from unrelated base interfaces
If candidatesCount > 1 Then
For i As Integer = 0 To candidates.Count - 2
Dim first As TSymbol = candidates(i)
If first Is Nothing Then
Continue For ' has been eliminated already
End If
If foundMember Is Nothing Then
foundMember = first
End If
For j As Integer = i + 1 To candidates.Count - 1
Dim second As TSymbol = candidates(j)
If second Is Nothing Then
Continue For ' has been eliminated already
End If
If TypeSymbol.Equals(first.ContainingType, second.ContainingType, TypeCompareKind.ConsiderEverything) Then
' type substitution can create two methods with same signature in the same type
' report ambiguity
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_AmbiguousImplements3,
CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(first.ContainingType),
implementedMethodName,
CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(first.ContainingType),
first,
second)
errorReported = True
resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.OverloadResolutionFailure)
GoTo DoneWithErrorReporting
End If
Next
Next
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_AmbiguousImplementsMember3,
implementedMethodName,
implementedMethodName)
resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.Ambiguous)
errorReported = True
DoneWithErrorReporting:
If candidateSymbols IsNot Nothing Then
candidateSymbols.AddRange(lookup.Symbols)
End If
ElseIf candidatesCount = 1 Then
For i As Integer = 0 To candidates.Count - 1
Dim first As TSymbol = candidates(i)
If first Is Nothing Then
Continue For ' has been eliminated already
End If
foundMember = first
Exit For
Next
Else
Debug.Assert(candidatesCount = 0)
' No matching members. Remember non-matching members for semantic model questions.
If candidateSymbols IsNot Nothing Then
candidateSymbols.AddRange(lookup.Symbols)
End If
resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.OverloadResolutionFailure)
End If
If candidates IsNot Nothing Then
candidates.Free()
End If
If foundMember IsNot Nothing Then
Dim coClassContext As Boolean = interfaceNamedType.CoClassType IsNot Nothing
If coClassContext AndAlso (implementingSym.Kind = SymbolKind.Event) <> (foundMember.Kind = SymbolKind.Event) Then
' Following Dev11 implementation: in COM Interface context if the implementing symbol
' is an event and the found candidate is not (or vice versa) we just pretend we didn't
' find anything and fall back to the default error
foundMember = Nothing
End If
If Not errorReported Then
' Further verification of found method.
foundMember = ValidateImplementedMember(implementingSym, foundMember, implementedMemberSyntax, binder, diagBag, interfaceType, implementedMethodName, errorReported)
End If
If foundMember IsNot Nothing Then
' Record found member for semantic model questions.
If candidateSymbols IsNot Nothing Then
candidateSymbols.Add(foundMember)
End If
resultKind = LookupResult.WorseResultKind(resultKind, lookup.Kind)
If Not binder.IsAccessible(foundMember, useSiteInfo) Then
resultKind = LookupResult.WorseResultKind(resultKind, LookupResultKind.Inaccessible) ' we specified IgnoreAccessibility above.
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, binder.GetInaccessibleErrorInfo(foundMember))
ElseIf foundMember.Kind = SymbolKind.Property Then
Dim [property] = DirectCast(DirectCast(foundMember, Symbol), PropertySymbol)
Dim accessorToCheck As MethodSymbol = [property].GetMethod
If accessorToCheck Is Nothing OrElse
accessorToCheck.DeclaredAccessibility = [property].DeclaredAccessibility OrElse
Not accessorToCheck.RequiresImplementation() Then
accessorToCheck = [property].SetMethod
End If
If accessorToCheck IsNot Nothing AndAlso
accessorToCheck.DeclaredAccessibility <> [property].DeclaredAccessibility AndAlso
accessorToCheck.RequiresImplementation() AndAlso
Not binder.IsAccessible(accessorToCheck, useSiteInfo) Then
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, binder.GetInaccessibleErrorInfo(accessorToCheck))
End If
End If
End If
End If
End If
diagBag.Add(interfaceName, useSiteInfo)
lookup.Free()
If foundMember Is Nothing And Not errorReported Then
' Didn't find a method (or it was otherwise bad in some way)
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_IdentNotMemberOfInterface4,
CustomSymbolDisplayFormatter.ShortErrorName(implementingSym), implementedMethodName,
implementingSym.GetKindText(),
CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(interfaceType))
End If
Return foundMember
ElseIf interfaceType.TypeKind = TypeKind.Error Then
' BindType already reported an error, so don't report another one
Return Nothing
Else
' type is some other type rather than an interface
Binder.ReportDiagnostic(diagBag, interfaceName, ERRID.ERR_BadImplementsType)
Return Nothing
End If
End Function
''' <summary>
''' Does 'implementingSym' match 'implementedSym' well enough to be considered a match for interface implementation?
''' </summary>
Private Function MembersAreMatchingForPurposesOfInterfaceImplementation(implementingSym As Symbol,
implementedSym As Symbol) As Boolean
Return MembersAreMatching(implementingSym, implementedSym, Not SymbolComparisonResults.MismatchesForExplicitInterfaceImplementations, EventSignatureComparer.ExplicitEventImplementationComparer)
End Function
Private Function MembersHaveMatchingTupleNames(implementingSym As Symbol,
implementedSym As Symbol) As Boolean
Return MembersAreMatching(implementingSym, implementedSym, SymbolComparisonResults.TupleNamesMismatch, EventSignatureComparer.ExplicitEventImplementationWithTupleNamesComparer)
End Function
Private Function MembersAreMatching(implementingSym As Symbol,
implementedSym As Symbol,
comparisons As SymbolComparisonResults,
eventComparer As EventSignatureComparer) As Boolean
Debug.Assert(implementingSym.Kind = implementedSym.Kind)
Select Case implementingSym.Kind
Case SymbolKind.Method
Dim results = MethodSignatureComparer.DetailedCompare(DirectCast(implementedSym, MethodSymbol), DirectCast(implementingSym, MethodSymbol),
comparisons,
comparisons)
Return (results = 0)
Case SymbolKind.Property
Dim results = PropertySignatureComparer.DetailedCompare(DirectCast(implementedSym, PropertySymbol), DirectCast(implementingSym, PropertySymbol),
comparisons,
comparisons)
Return (results = 0)
Case SymbolKind.Event
Return eventComparer.Equals(DirectCast(implementedSym, EventSymbol), DirectCast(implementingSym, EventSymbol))
Case Else
Throw ExceptionUtilities.UnexpectedValue(implementingSym.Kind)
End Select
End Function
''' <summary>
''' Perform additional validate of implementedSym and issue diagnostics.
''' Return "implementedSym" if the symbol table should record implementedSym as the implemented
''' symbol (even if diagnostics were issues). Returns Nothing if the code should not treat
''' implementedSym as the implemented symbol.
''' </summary>
Private Function ValidateImplementedMember(Of TSymbol As Symbol)(implementingSym As TSymbol,
implementedSym As TSymbol,
implementedMemberSyntax As QualifiedNameSyntax,
binder As Binder,
diagBag As BindingDiagnosticBag,
interfaceType As TypeSymbol,
implementedMethodName As String,
ByRef errorReported As Boolean) As TSymbol
If Not implementedSym.RequiresImplementation() Then
' TODO: Perhaps give ERR_CantImplementNonVirtual3 like Dev10. But, this message seems more
' TODO: confusing than useful, so for now, just treat it like a method that doesn't exist.
Return Nothing
End If
' Validate that implementing property implements all accessors of the implemented property
If implementedSym.Kind = SymbolKind.Property Then
Dim implementedProperty As PropertySymbol = TryCast(implementedSym, PropertySymbol)
Dim implementedPropertyGetMethod As MethodSymbol = implementedProperty.GetMethod
If Not implementedPropertyGetMethod?.RequiresImplementation() Then
implementedPropertyGetMethod = Nothing
End If
Dim implementedPropertySetMethod As MethodSymbol = implementedProperty.SetMethod
If Not implementedPropertySetMethod?.RequiresImplementation() Then
implementedPropertySetMethod = Nothing
End If
Dim implementingProperty As PropertySymbol = TryCast(implementingSym, PropertySymbol)
If (implementedPropertyGetMethod IsNot Nothing AndAlso implementingProperty.GetMethod Is Nothing) OrElse
(implementedPropertySetMethod IsNot Nothing AndAlso implementingProperty.SetMethod Is Nothing) Then
' "'{0}' cannot be implemented by a {1} property."
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_PropertyDoesntImplementAllAccessors,
implementedProperty,
implementingProperty.GetPropertyKindText())
errorReported = True
ElseIf ((implementedPropertyGetMethod Is Nothing) Xor (implementedPropertySetMethod Is Nothing)) AndAlso
implementingProperty.GetMethod IsNot Nothing AndAlso implementingProperty.SetMethod IsNot Nothing Then
errorReported = errorReported Or
Not InternalSyntax.Parser.CheckFeatureAvailability(diagBag, implementedMemberSyntax.GetLocation(),
DirectCast(implementedMemberSyntax.SyntaxTree, VisualBasicSyntaxTree).Options.LanguageVersion,
InternalSyntax.Feature.ImplementingReadonlyOrWriteonlyPropertyWithReadwrite)
End If
If implementedPropertySetMethod?.IsInitOnly <> implementingProperty.SetMethod?.IsInitOnly Then
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_PropertyDoesntImplementInitOnly,
implementedProperty)
errorReported = True
End If
End If
If implementedSym IsNot Nothing AndAlso implementingSym.ContainsTupleNames() AndAlso
Not MembersHaveMatchingTupleNames(implementingSym, implementedSym) Then
' it is ok to implement with no tuple names, for compatibility with VB 14, but otherwise names should match
Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_ImplementingInterfaceWithDifferentTupleNames5,
CustomSymbolDisplayFormatter.ShortErrorName(implementingSym),
implementingSym.GetKindText(),
implementedMethodName,
CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(interfaceType),
implementingSym,
implementedSym)
errorReported = True
End If
' TODO: If implementing event, check that delegate types are consistent, or maybe set the delegate type. See Dev10 compiler
' TODO: in ImplementsSemantics.cpp, Bindable::BindImplements.
' Method type parameter constraints are validated later, in ValidateImplementedMethodConstraints,
' after the ExplicitInterfaceImplementations property has been set on the implementing method.
Return implementedSym
End Function
''' <summary>
''' Validate method type parameter constraints. This is handled outside
''' of ValidateImplementedMember because that method is invoked
''' while computing the ExplicitInterfaceImplementations value on the
''' implementing method, but method type parameters rely on the value
''' of ExplicitInterfaceImplementations to determine constraints correctly.
''' </summary>
Public Sub ValidateImplementedMethodConstraints(implementingMethod As SourceMethodSymbol,
implementedMethod As MethodSymbol,
diagBag As BindingDiagnosticBag)
If Not MethodSignatureComparer.HaveSameConstraints(implementedMethod, implementingMethod) Then
' "'{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints."
Dim loc = implementingMethod.GetImplementingLocation(implementedMethod)
diagBag.Add(
ErrorFactory.ErrorInfo(ERRID.ERR_ImplementsWithConstraintMismatch3, implementingMethod, implementedMethod.ContainingType, implementedMethod),
loc)
End If
End Sub
''' <summary>
''' Performs interface mapping to determine which symbol in this type or a base type
''' actually implements a particular interface member.
''' </summary>
''' <typeparam name="TSymbol">MethodSymbol or PropertySymbol or EventSymbol (an interface member).</typeparam>
''' <param name="interfaceMember">A non-null member on an interface type.</param>
''' <param name="implementingType">The type implementing the interface member.</param>
''' <param name="comparer">A comparer for comparing signatures of TSymbol according to metadata implementation rules.</param>
''' <returns>The implementing member or Nothing, if there isn't one.</returns>
Public Function ComputeImplementationForInterfaceMember(Of TSymbol As Symbol)(interfaceMember As TSymbol,
implementingType As TypeSymbol,
comparer As IEqualityComparer(Of TSymbol)) As TSymbol
Debug.Assert(TypeOf interfaceMember Is PropertySymbol OrElse
TypeOf interfaceMember Is MethodSymbol OrElse
TypeOf interfaceMember Is EventSymbol)
Dim interfaceType As NamedTypeSymbol = interfaceMember.ContainingType
Debug.Assert(interfaceType IsNot Nothing AndAlso interfaceType.IsInterface)
Dim seenMDTypeDeclaringInterface As Boolean = False
Dim currType As TypeSymbol = implementingType
' Go up the inheritance chain, looking for an implementation of the member.
While currType IsNot Nothing
' First, check for explicit interface implementation.
Dim currTypeExplicitImpl As MultiDictionary(Of Symbol, Symbol).ValueSet = currType.ExplicitInterfaceImplementationMap(interfaceMember)
If currTypeExplicitImpl.Count = 1 Then
Return DirectCast(currTypeExplicitImpl.Single(), TSymbol)
ElseIf currTypeExplicitImpl.Count > 1 Then
Return Nothing
End If
' VB only supports explicit interface implementation, but for the purpose of finding implementation, we must
' check implicit implementation for members from metadata. We only want to consider metadata implementations
' if a metadata implementation (or a derived metadata implementation) actually implements the given interface
' (not a derived interface), since this is the metadata rule from Partition II, section 12.2.
'
' Consider:
' Interface IGoo ' from metadata
' Sub Goo()
' Class A ' from metadata
' Public Sub Goo()
' Class B: Inherits A: Implements IGoo ' from metadata
' Class C: Inherits B ' from metadata
' Public Shadows Sub Goo()
' Class D: Inherits C: Implements IGoo ' from source
' In this case, A.Goo is the correct implementation of IGoo.Goo within D.
' NOTE: Ideally, we'd like to distinguish between the "current" compilation and other assemblies
' (including other compilations), rather than source and metadata, but there are two reasons that
' that won't work in this case:
' 1) We really don't want consumers of the API to have to pass in the current compilation when
' they ask questions about interface implementation.
' 2) NamedTypeSymbol.Interfaces does not round-trip in the presence of implicit interface
' implementations. As in dev11, we drop interfaces from the interface list if any of their
' members are implemented in a base type (so that CLR implicit implementation will pick the
' same method as the VB language).
If Not currType.Dangerous_IsFromSomeCompilationIncludingRetargeting AndAlso
currType.InterfacesNoUseSiteDiagnostics.Contains(interfaceType, EqualsIgnoringComparer.InstanceCLRSignatureCompare) Then
seenMDTypeDeclaringInterface = True
End If
If seenMDTypeDeclaringInterface Then
'check for implicit impls (name must match)
Dim currTypeImplicitImpl As TSymbol
currTypeImplicitImpl = FindImplicitImplementationDeclaredInType(interfaceMember, currType, comparer)
If currTypeImplicitImpl IsNot Nothing Then
Return currTypeImplicitImpl
End If
End If
currType = currType.BaseTypeNoUseSiteDiagnostics
End While
Return Nothing
End Function
''' <summary>
''' Search the declared methods of a type for one that could be an implicit implementation
''' of a given interface method (depending on interface declarations). It is assumed that the implementing
''' type is not a source type.
''' </summary>
''' <typeparam name="TSymbol">MethodSymbol or PropertySymbol or EventSymbol (an interface member).</typeparam>
''' <param name="interfaceMember">The interface member being implemented.</param>
''' <param name="currType">The type on which we are looking for a declared implementation of the interface method.</param>
''' <param name="comparer">A comparer for comparing signatures of TSymbol according to metadata implementation rules.</param>
Private Function FindImplicitImplementationDeclaredInType(Of TSymbol As Symbol)(interfaceMember As TSymbol,
currType As TypeSymbol,
comparer As IEqualityComparer(Of TSymbol)) As TSymbol '
Debug.Assert(Not currType.Dangerous_IsFromSomeCompilationIncludingRetargeting)
For Each member In currType.GetMembers(interfaceMember.Name)
If member.DeclaredAccessibility = Accessibility.Public AndAlso
Not member.IsShared AndAlso
TypeOf member Is TSymbol AndAlso
comparer.Equals(interfaceMember, DirectCast(member, TSymbol)) Then
Return DirectCast(member, TSymbol)
End If
Next
Return Nothing
End Function
''' <summary>
''' Given a set of explicit interface implementations that are undergoing substitution, return the substituted versions.
''' </summary>
''' <typeparam name="TSymbol">Type of the interface members (Method, Property, Event)</typeparam>
''' <param name="unsubstitutedImplementations">The ROA of members that are being implemented</param>
''' <param name="substitution">The type substitution</param>
''' <returns>The substituted members.</returns>
Public Function SubstituteExplicitInterfaceImplementations(Of TSymbol As Symbol)(unsubstitutedImplementations As ImmutableArray(Of TSymbol),
substitution As TypeSubstitution) As ImmutableArray(Of TSymbol)
If unsubstitutedImplementations.Length = 0 Then
Return ImmutableArray(Of TSymbol).Empty
Else
Dim substitutedImplementations(0 To unsubstitutedImplementations.Length - 1) As TSymbol
For i As Integer = 0 To unsubstitutedImplementations.Length - 1
Dim unsubstitutedMember As TSymbol = unsubstitutedImplementations(i)
Dim unsubstitutedInterfaceType = unsubstitutedMember.ContainingType
substitutedImplementations(i) = unsubstitutedImplementations(i) ' default: no substitution necessary
If unsubstitutedInterfaceType.IsGenericType Then
Dim substitutedInterfaceType = TryCast(unsubstitutedInterfaceType.InternalSubstituteTypeParameters(substitution).AsTypeSymbolOnly(), SubstitutedNamedType)
If substitutedInterfaceType IsNot Nothing Then
' Get the substituted version of the member
substitutedImplementations(i) = DirectCast(substitutedInterfaceType.GetMemberForDefinition(unsubstitutedMember.OriginalDefinition), TSymbol)
End If
End If
Next
Return ImmutableArray.Create(Of TSymbol)(substitutedImplementations)
End If
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Features/VisualBasic/Portable/Completion/CompletionProviders/ImportCompletionProvider/ExtensionMethodImportCompletionProvider.vb | ' 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.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
<ExportCompletionProvider(NameOf(ExtensionMethodImportCompletionProvider), LanguageNames.VisualBasic)>
<ExtensionOrder(After:=NameOf(TypeImportCompletionProvider))>
<ExtensionOrder(Before:=NameOf(LastBuiltInCompletionProvider))>
<[Shared]>
Friend NotInheritable Class ExtensionMethodImportCompletionProvider
Inherits AbstractExtensionMethodImportCompletionProvider
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides ReadOnly Property GenericSuffix As String
Get
Return "(Of ...)"
End Get
End Property
Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean
Return CompletionUtilities.IsDefaultTriggerCharacterOrParen(text, characterPosition, options)
End Function
Public Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = CompletionUtilities.CommonTriggerCharsAndParen
Protected Overrides Function CreateContextAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of SyntaxContext)
Return ImportCompletionProviderHelper.CreateContextAsync(document, position, cancellationToken)
End Function
Protected Overrides Function GetImportedNamespaces(location As SyntaxNode, semanticModel As SemanticModel, cancellationToken As CancellationToken) As ImmutableArray(Of String)
Return ImportCompletionProviderHelper.GetImportedNamespaces(location, semanticModel)
End Function
Protected Overrides Function IsFinalSemicolonOfUsingOrExtern(directive As SyntaxNode, token As SyntaxToken) As Boolean
Return False
End Function
Protected Overrides Function ShouldProvideParenthesisCompletionAsync(document As Document, item As CompletionItem, commitKey As Char?, cancellationToken As CancellationToken) As Task(Of Boolean)
Return Task.FromResult(False)
End Function
End Class
End Namespace
| ' 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.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
<ExportCompletionProvider(NameOf(ExtensionMethodImportCompletionProvider), LanguageNames.VisualBasic)>
<ExtensionOrder(After:=NameOf(TypeImportCompletionProvider))>
<ExtensionOrder(Before:=NameOf(LastBuiltInCompletionProvider))>
<[Shared]>
Friend NotInheritable Class ExtensionMethodImportCompletionProvider
Inherits AbstractExtensionMethodImportCompletionProvider
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides ReadOnly Property GenericSuffix As String
Get
Return "(Of ...)"
End Get
End Property
Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean
Return CompletionUtilities.IsDefaultTriggerCharacterOrParen(text, characterPosition, options)
End Function
Public Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = CompletionUtilities.CommonTriggerCharsAndParen
Protected Overrides Function CreateContextAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of SyntaxContext)
Return ImportCompletionProviderHelper.CreateContextAsync(document, position, cancellationToken)
End Function
Protected Overrides Function GetImportedNamespaces(location As SyntaxNode, semanticModel As SemanticModel, cancellationToken As CancellationToken) As ImmutableArray(Of String)
Return ImportCompletionProviderHelper.GetImportedNamespaces(location, semanticModel)
End Function
Protected Overrides Function IsFinalSemicolonOfUsingOrExtern(directive As SyntaxNode, token As SyntaxToken) As Boolean
Return False
End Function
Protected Overrides Function ShouldProvideParenthesisCompletionAsync(document As Document, item As CompletionItem, commitKey As Char?, cancellationToken As CancellationToken) As Task(Of Boolean)
Return Task.FromResult(False)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpIntelliSense.cs | // 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.
#nullable disable
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpIntelliSense : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpIntelliSense(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpIntelliSense))
{
}
public override async Task InitializeAsync()
{
await base.InitializeAsync().ConfigureAwait(true);
// Disable import completion.
VisualStudio.Workspace.SetImportCompletionOption(false);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void AtNamespaceLevel(bool showCompletionInArgumentLists)
{
SetUpEditor(@"$$");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys("usi");
VisualStudio.Editor.Verify.CompletionItemsExist("using");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("using$$", assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void SpeculativeTInList(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
class C
{
$$
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys("pub");
VisualStudio.Editor.Verify.CompletionItemsExist("public");
VisualStudio.Editor.SendKeys(' ');
VisualStudio.Editor.Verify.CurrentLineText("public $$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys('t');
VisualStudio.Editor.Verify.CompletionItemsExist("T");
VisualStudio.Editor.SendKeys(' ');
VisualStudio.Editor.SendKeys("Goo<T>() { }");
VisualStudio.Editor.Verify.TextContains(@"
class C
{
public T Goo<T>() { }$$
}",
assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void VerifyCompletionListMembersOnStaticTypesAndCompleteThem(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
public class Program
{
static void Main(string[] args)
{
NavigateTo$$
}
}
public static class NavigateTo
{
public static void Search(string s){ }
public static void Navigate(int i){ }
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys('.');
VisualStudio.Editor.Verify.CompletionItemsExist("Search", "Navigate");
VisualStudio.Editor.SendKeys('S', VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("NavigateTo.Search$$", assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void CtrlAltSpace(bool showCompletionInArgumentLists)
{
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SetUseSuggestionMode(false);
// Note: the completion needs to be unambiguous for the test to be deterministic.
// Otherwise the result might depend on the state of MRU list.
VisualStudio.Editor.SendKeys("names");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" Goo", VirtualKey.Enter);
VisualStudio.Editor.SendKeys('{', VirtualKey.Enter, '}', VirtualKey.Up, VirtualKey.Enter);
VisualStudio.Editor.SendKeys("pu");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" cla");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" Program", VirtualKey.Enter);
VisualStudio.Editor.SendKeys('{', VirtualKey.Enter, '}', VirtualKey.Up, VirtualKey.Enter);
VisualStudio.Editor.SendKeys("pub");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" stati");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" voi");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" Main(string[] args)", VirtualKey.Enter);
VisualStudio.Editor.SendKeys('{', VirtualKey.Enter, '}', VirtualKey.Up, VirtualKey.Enter);
VisualStudio.Editor.SendKeys("System.Console.");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys("writeline();");
VisualStudio.Editor.Verify.CurrentLineText("System.Console.WriteLine();$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Home, Shift(VirtualKey.End), VirtualKey.Delete);
VisualStudio.Editor.SendKeys(new KeyPress(VirtualKey.Space, ShiftState.Ctrl | ShiftState.Alt));
VisualStudio.Editor.SendKeys("System.Console.");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys("writeline();");
VisualStudio.Editor.Verify.CurrentLineText("System.Console.writeline();$$", assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void CtrlAltSpaceOption(bool showCompletionInArgumentLists)
{
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SetUseSuggestionMode(false);
VisualStudio.Editor.SendKeys("names");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" Goo");
VisualStudio.Editor.Verify.CurrentLineText("namespace Goo$$", assertCaretPosition: true);
ClearEditor();
VisualStudio.Editor.SetUseSuggestionMode(true);
VisualStudio.Editor.SendKeys("nam");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" Goo");
VisualStudio.Editor.Verify.CurrentLineText("nam Goo$$", assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void CtrlSpace(bool showCompletionInArgumentLists)
{
SetUpEditor("class c { void M() {$$ } }");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys(Ctrl(VirtualKey.Space));
VisualStudio.Editor.Verify.CompletionItemsExist("System");
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void NavigatingWithDownKey(bool showCompletionInArgumentLists)
{
SetUpEditor("class c { void M() {$$ } }");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys('c');
VisualStudio.Editor.Verify.CurrentCompletionItem("c");
VisualStudio.Editor.Verify.CompletionItemsExist("c");
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentCompletionItem("char");
VisualStudio.Editor.Verify.CompletionItemsExist("char");
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void XmlDocCommentIntelliSense(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
class Class1
{
///$$
void Main(string[] args)
{
}
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys("<s");
VisualStudio.Editor.Verify.CompletionItemsExist("see", "seealso", "summary");
// 🐛 Workaround for https://github.com/dotnet/roslyn/issues/33824
var completionItems = VisualStudio.Editor.GetCompletionItems();
var targetIndex = Array.IndexOf(completionItems, "see");
var currentIndex = Array.IndexOf(completionItems, VisualStudio.Editor.GetCurrentCompletionItem());
if (currentIndex != targetIndex)
{
var key = currentIndex < targetIndex ? VirtualKey.Down : VirtualKey.Up;
var keys = Enumerable.Repeat(key, Math.Abs(currentIndex - targetIndex)).Cast<object>().ToArray();
VisualStudio.Editor.SendKeys(keys);
}
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.Verify.CurrentLineText("///<see cref=\"$$\"/>", assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void XmlTagCompletion(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
/// $$
class C { }
");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys("<summary>");
VisualStudio.Editor.Verify.CurrentLineText("/// <summary>$$</summary>", assertCaretPosition: true);
SetUpEditor(@"
/// <summary>$$
class C { }
");
VisualStudio.Editor.SendKeys("</");
VisualStudio.Editor.Verify.CurrentLineText("/// <summary></summary>$$", assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void SignatureHelpShowsUp(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
class Class1
{
void Main(string[] args)
{
$$
}
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SetUseSuggestionMode(false);
VisualStudio.Editor.SendKeys("Mai");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys("(");
VisualStudio.Editor.Verify.CurrentSignature("void Class1.Main(string[] args)");
VisualStudio.Editor.Verify.CurrentParameter("args", "");
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33825, "https://github.com/dotnet/roslyn/issues/33825")]
public void CompletionUsesTrackingPointsInTheFaceOfAutomaticBraceCompletion(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
class Class1
{
void Main(string[] args)
$$
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SetUseSuggestionMode(false);
VisualStudio.Editor.SendKeys(
'{',
VirtualKey.Enter,
" ");
VisualStudio.Editor.InvokeCompletionList();
VisualStudio.Editor.SendKeys('}');
VisualStudio.Editor.Verify.TextContains(@"
class Class1
{
void Main(string[] args)
{
}$$
}",
assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33823, "https://github.com/dotnet/roslyn/issues/33823")]
public void CommitOnShiftEnter(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
class Class1
{
void Main(string[] args)
{
$$
}
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SetUseSuggestionMode(false);
VisualStudio.Editor.SendKeys(
'M',
Shift(VirtualKey.Enter));
VisualStudio.Editor.Verify.TextContains(@"
class Class1
{
void Main(string[] args)
{
Main
$$
}
}",
assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void LineBreakOnShiftEnter(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
class Class1
{
void Main(string[] args)
{
$$
}
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SetUseSuggestionMode(true);
VisualStudio.Editor.SendKeys(
'M',
Shift(VirtualKey.Enter));
VisualStudio.Editor.Verify.TextContains(@"
class Class1
{
void Main(string[] args)
{
Main
$$
}
}",
assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void CommitOnLeftCurly(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
class Class1
{
$$
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SetUseSuggestionMode(false);
VisualStudio.Editor.SendKeys("int P { g");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys("{");
VisualStudio.Editor.Verify.TextContains(@"
class Class1
{
int P { get { $$} }
}",
assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33822, "https://github.com/dotnet/roslyn/issues/33822")]
public void EnsureTheCaretIsVisibleAfterALongEdit(bool showCompletionInArgumentLists)
{
var visibleColumns = VisualStudio.Editor.GetVisibleColumnCount();
var variableName = new string('a', (int)(0.75 * visibleColumns));
SetUpEditor($@"
public class Program
{{
static void Main(string[] args)
{{
var {variableName} = 0;
{variableName} = $$
}}
}}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
Assert.True(variableName.Length > 0);
VisualStudio.Editor.SendKeys(
VirtualKey.Delete,
"aaa",
VirtualKey.Tab);
var actualText = VisualStudio.Editor.GetText();
Assert.Contains($"{variableName} = {variableName}", actualText);
Assert.True(VisualStudio.Editor.IsCaretOnScreen());
Assert.True(VisualStudio.Editor.GetCaretColumn() > visibleColumns, "This test is inconclusive if the view didn't need to move to keep the caret on screen.");
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void DismissOnSelect(bool showCompletionInArgumentLists)
{
SetUpEditor(@"$$");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys(Ctrl(VirtualKey.Space));
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(Ctrl(VirtualKey.A));
Assert.False(VisualStudio.Editor.IsCompletionActive());
}
}
}
| // 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.
#nullable disable
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpIntelliSense : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpIntelliSense(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpIntelliSense))
{
}
public override async Task InitializeAsync()
{
await base.InitializeAsync().ConfigureAwait(true);
// Disable import completion.
VisualStudio.Workspace.SetImportCompletionOption(false);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void AtNamespaceLevel(bool showCompletionInArgumentLists)
{
SetUpEditor(@"$$");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys("usi");
VisualStudio.Editor.Verify.CompletionItemsExist("using");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("using$$", assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void SpeculativeTInList(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
class C
{
$$
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys("pub");
VisualStudio.Editor.Verify.CompletionItemsExist("public");
VisualStudio.Editor.SendKeys(' ');
VisualStudio.Editor.Verify.CurrentLineText("public $$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys('t');
VisualStudio.Editor.Verify.CompletionItemsExist("T");
VisualStudio.Editor.SendKeys(' ');
VisualStudio.Editor.SendKeys("Goo<T>() { }");
VisualStudio.Editor.Verify.TextContains(@"
class C
{
public T Goo<T>() { }$$
}",
assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void VerifyCompletionListMembersOnStaticTypesAndCompleteThem(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
public class Program
{
static void Main(string[] args)
{
NavigateTo$$
}
}
public static class NavigateTo
{
public static void Search(string s){ }
public static void Navigate(int i){ }
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys('.');
VisualStudio.Editor.Verify.CompletionItemsExist("Search", "Navigate");
VisualStudio.Editor.SendKeys('S', VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("NavigateTo.Search$$", assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void CtrlAltSpace(bool showCompletionInArgumentLists)
{
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SetUseSuggestionMode(false);
// Note: the completion needs to be unambiguous for the test to be deterministic.
// Otherwise the result might depend on the state of MRU list.
VisualStudio.Editor.SendKeys("names");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" Goo", VirtualKey.Enter);
VisualStudio.Editor.SendKeys('{', VirtualKey.Enter, '}', VirtualKey.Up, VirtualKey.Enter);
VisualStudio.Editor.SendKeys("pu");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" cla");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" Program", VirtualKey.Enter);
VisualStudio.Editor.SendKeys('{', VirtualKey.Enter, '}', VirtualKey.Up, VirtualKey.Enter);
VisualStudio.Editor.SendKeys("pub");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" stati");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" voi");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" Main(string[] args)", VirtualKey.Enter);
VisualStudio.Editor.SendKeys('{', VirtualKey.Enter, '}', VirtualKey.Up, VirtualKey.Enter);
VisualStudio.Editor.SendKeys("System.Console.");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys("writeline();");
VisualStudio.Editor.Verify.CurrentLineText("System.Console.WriteLine();$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Home, Shift(VirtualKey.End), VirtualKey.Delete);
VisualStudio.Editor.SendKeys(new KeyPress(VirtualKey.Space, ShiftState.Ctrl | ShiftState.Alt));
VisualStudio.Editor.SendKeys("System.Console.");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys("writeline();");
VisualStudio.Editor.Verify.CurrentLineText("System.Console.writeline();$$", assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void CtrlAltSpaceOption(bool showCompletionInArgumentLists)
{
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SetUseSuggestionMode(false);
VisualStudio.Editor.SendKeys("names");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" Goo");
VisualStudio.Editor.Verify.CurrentLineText("namespace Goo$$", assertCaretPosition: true);
ClearEditor();
VisualStudio.Editor.SetUseSuggestionMode(true);
VisualStudio.Editor.SendKeys("nam");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(" Goo");
VisualStudio.Editor.Verify.CurrentLineText("nam Goo$$", assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void CtrlSpace(bool showCompletionInArgumentLists)
{
SetUpEditor("class c { void M() {$$ } }");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys(Ctrl(VirtualKey.Space));
VisualStudio.Editor.Verify.CompletionItemsExist("System");
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void NavigatingWithDownKey(bool showCompletionInArgumentLists)
{
SetUpEditor("class c { void M() {$$ } }");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys('c');
VisualStudio.Editor.Verify.CurrentCompletionItem("c");
VisualStudio.Editor.Verify.CompletionItemsExist("c");
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentCompletionItem("char");
VisualStudio.Editor.Verify.CompletionItemsExist("char");
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void XmlDocCommentIntelliSense(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
class Class1
{
///$$
void Main(string[] args)
{
}
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys("<s");
VisualStudio.Editor.Verify.CompletionItemsExist("see", "seealso", "summary");
// 🐛 Workaround for https://github.com/dotnet/roslyn/issues/33824
var completionItems = VisualStudio.Editor.GetCompletionItems();
var targetIndex = Array.IndexOf(completionItems, "see");
var currentIndex = Array.IndexOf(completionItems, VisualStudio.Editor.GetCurrentCompletionItem());
if (currentIndex != targetIndex)
{
var key = currentIndex < targetIndex ? VirtualKey.Down : VirtualKey.Up;
var keys = Enumerable.Repeat(key, Math.Abs(currentIndex - targetIndex)).Cast<object>().ToArray();
VisualStudio.Editor.SendKeys(keys);
}
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.Verify.CurrentLineText("///<see cref=\"$$\"/>", assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void XmlTagCompletion(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
/// $$
class C { }
");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys("<summary>");
VisualStudio.Editor.Verify.CurrentLineText("/// <summary>$$</summary>", assertCaretPosition: true);
SetUpEditor(@"
/// <summary>$$
class C { }
");
VisualStudio.Editor.SendKeys("</");
VisualStudio.Editor.Verify.CurrentLineText("/// <summary></summary>$$", assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void SignatureHelpShowsUp(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
class Class1
{
void Main(string[] args)
{
$$
}
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SetUseSuggestionMode(false);
VisualStudio.Editor.SendKeys("Mai");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys("(");
VisualStudio.Editor.Verify.CurrentSignature("void Class1.Main(string[] args)");
VisualStudio.Editor.Verify.CurrentParameter("args", "");
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33825, "https://github.com/dotnet/roslyn/issues/33825")]
public void CompletionUsesTrackingPointsInTheFaceOfAutomaticBraceCompletion(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
class Class1
{
void Main(string[] args)
$$
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SetUseSuggestionMode(false);
VisualStudio.Editor.SendKeys(
'{',
VirtualKey.Enter,
" ");
VisualStudio.Editor.InvokeCompletionList();
VisualStudio.Editor.SendKeys('}');
VisualStudio.Editor.Verify.TextContains(@"
class Class1
{
void Main(string[] args)
{
}$$
}",
assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33823, "https://github.com/dotnet/roslyn/issues/33823")]
public void CommitOnShiftEnter(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
class Class1
{
void Main(string[] args)
{
$$
}
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SetUseSuggestionMode(false);
VisualStudio.Editor.SendKeys(
'M',
Shift(VirtualKey.Enter));
VisualStudio.Editor.Verify.TextContains(@"
class Class1
{
void Main(string[] args)
{
Main
$$
}
}",
assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void LineBreakOnShiftEnter(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
class Class1
{
void Main(string[] args)
{
$$
}
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SetUseSuggestionMode(true);
VisualStudio.Editor.SendKeys(
'M',
Shift(VirtualKey.Enter));
VisualStudio.Editor.Verify.TextContains(@"
class Class1
{
void Main(string[] args)
{
Main
$$
}
}",
assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void CommitOnLeftCurly(bool showCompletionInArgumentLists)
{
SetUpEditor(@"
class Class1
{
$$
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SetUseSuggestionMode(false);
VisualStudio.Editor.SendKeys("int P { g");
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys("{");
VisualStudio.Editor.Verify.TextContains(@"
class Class1
{
int P { get { $$} }
}",
assertCaretPosition: true);
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33822, "https://github.com/dotnet/roslyn/issues/33822")]
public void EnsureTheCaretIsVisibleAfterALongEdit(bool showCompletionInArgumentLists)
{
var visibleColumns = VisualStudio.Editor.GetVisibleColumnCount();
var variableName = new string('a', (int)(0.75 * visibleColumns));
SetUpEditor($@"
public class Program
{{
static void Main(string[] args)
{{
var {variableName} = 0;
{variableName} = $$
}}
}}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
Assert.True(variableName.Length > 0);
VisualStudio.Editor.SendKeys(
VirtualKey.Delete,
"aaa",
VirtualKey.Tab);
var actualText = VisualStudio.Editor.GetText();
Assert.Contains($"{variableName} = {variableName}", actualText);
Assert.True(VisualStudio.Editor.IsCaretOnScreen());
Assert.True(VisualStudio.Editor.GetCaretColumn() > visibleColumns, "This test is inconclusive if the view didn't need to move to keep the caret on screen.");
}
[WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public void DismissOnSelect(bool showCompletionInArgumentLists)
{
SetUpEditor(@"$$");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists);
VisualStudio.Editor.SendKeys(Ctrl(VirtualKey.Space));
Assert.True(VisualStudio.Editor.IsCompletionActive());
VisualStudio.Editor.SendKeys(Ctrl(VirtualKey.A));
Assert.False(VisualStudio.Editor.IsCompletionActive());
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/Test/Resources/Core/SymbolsTests/Versioning/V2/C.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L ;P ! ^$ @ _ @ $ W @ ` H .text d `.rsrc @ @ @.reloc ` @ B @$ H t (
*0
+ * (
*7D6$'K5>UXOHVUVçd՝v\bHd2K,݁l2Ǝ] gi$;WRt9;iޮ6M)xQO BSJB v4.0.30319 l #~ x #Strings #US #GUID ( #Blob G %3 T 4 t 4 P '
X - l '
'
' '
. .
2 <Module> mscorlib C D`1 System Object .ctor Main T System.Runtime.CompilerServices CompilationRelaxationsAttribute RuntimeCompatibilityAttribute C.dll Q2B-d#? z\V4 $ $ RSA1 oO6vk3 $jMҭ2eR cعU[IFo2eު3J߾plV
nY½%R;=3!
K`ay0 TWrapNonExceptionThrows,$ N$ @$ _CorDllMain mscoree.dll % 0 H X@ , ,4 V S _ V E R S I O N _ I N F O ? D V a r F i l e I n f o $ T r a n s l a t i o n S t r i n g F i l e I n f o h 0 0 0 0 0 4 b 0 , F i l e D e s c r i p t i o n 0 F i l e V e r s i o n 2 . 0 . 0 . 0 , I n t e r n a l N a m e C . d l l ( L e g a l C o p y r i g h t 4 O r i g i n a l F i l e n a m e C . d l l 4 P r o d u c t V e r s i o n 2 . 0 . 0 . 0 8 A s s e m b l y V e r s i o n 2 . 0 . 0 . 0 `4 | MZ @ !L!This program cannot be run in DOS mode.
$ PE L ;P ! ^$ @ _ @ $ W @ ` H .text d `.rsrc @ @ @.reloc ` @ B @$ H t (
*0
+ * (
*7D6$'K5>UXOHVUVçd՝v\bHd2K,݁l2Ǝ] gi$;WRt9;iޮ6M)xQO BSJB v4.0.30319 l #~ x #Strings #US #GUID ( #Blob G %3 T 4 t 4 P '
X - l '
'
' '
. .
2 <Module> mscorlib C D`1 System Object .ctor Main T System.Runtime.CompilerServices CompilationRelaxationsAttribute RuntimeCompatibilityAttribute C.dll Q2B-d#? z\V4 $ $ RSA1 oO6vk3 $jMҭ2eR cعU[IFo2eު3J߾plV
nY½%R;=3!
K`ay0 TWrapNonExceptionThrows,$ N$ @$ _CorDllMain mscoree.dll % 0 H X@ , ,4 V S _ V E R S I O N _ I N F O ? D V a r F i l e I n f o $ T r a n s l a t i o n S t r i n g F i l e I n f o h 0 0 0 0 0 4 b 0 , F i l e D e s c r i p t i o n 0 F i l e V e r s i o n 2 . 0 . 0 . 0 , I n t e r n a l N a m e C . d l l ( L e g a l C o p y r i g h t 4 O r i g i n a l F i l e n a m e C . d l l 4 P r o d u c t V e r s i o n 2 . 0 . 0 . 0 8 A s s e m b l y V e r s i o n 2 . 0 . 0 . 0 `4 | -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Features/LanguageServer/Protocol/Handler/Completion/CompletionListCache.cs | // 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 Microsoft.CodeAnalysis.Completion;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Completion
{
/// <summary>
/// Caches completion lists in between calls to CompletionHandler and
/// CompletionResolveHandler. Used to avoid unnecessary recomputation.
/// </summary>
internal class CompletionListCache
{
/// <summary>
/// Maximum number of completion lists allowed in cache. Must be >= 1.
/// </summary>
private const int MaxCacheSize = 3;
/// <summary>
/// Multiple cache requests or updates may be received concurrently.
/// We need this lock to ensure that we aren't making concurrent
/// modifications to _nextResultId or _resultIdToCompletionList.
/// </summary>
private readonly object _accessLock = new object();
#region protected by _accessLock
/// <summary>
/// The next resultId available to use.
/// </summary>
private long _nextResultId;
/// <summary>
/// Keeps track of the resultIds in the cache and their associated
/// completion list.
/// </summary>
private readonly List<CacheEntry> _resultIdToCompletionList = new();
#endregion
/// <summary>
/// Adds a completion list to the cache. If the cache reaches its maximum size, the oldest completion
/// list in the cache is removed.
/// </summary>
/// <returns>
/// The generated resultId associated with the passed in completion list.
/// </returns>
public long UpdateCache(LSP.TextDocumentIdentifier textDocument, CompletionList completionList)
{
lock (_accessLock)
{
// If cache exceeds maximum size, remove the oldest list in the cache
if (_resultIdToCompletionList.Count >= MaxCacheSize)
{
_resultIdToCompletionList.RemoveAt(0);
}
// Getting the generated unique resultId
var resultId = _nextResultId++;
// Add passed in completion list to cache
var cacheEntry = new CacheEntry(resultId, textDocument, completionList);
_resultIdToCompletionList.Add(cacheEntry);
// Return generated resultId so completion list can later be retrieved from cache
return resultId;
}
}
/// <summary>
/// Attempts to return the completion list in the cache associated with the given resultId.
/// Returns null if no match is found.
/// </summary>
public CacheEntry? GetCachedCompletionList(long resultId)
{
lock (_accessLock)
{
foreach (var cacheEntry in _resultIdToCompletionList)
{
if (cacheEntry.ResultId == resultId)
{
// We found a match - return completion list
return cacheEntry;
}
}
// A completion list associated with the given resultId was not found
return null;
}
}
internal TestAccessor GetTestAccessor() => new(this);
internal readonly struct TestAccessor
{
private readonly CompletionListCache _completionListCache;
public static int MaximumCacheSize => MaxCacheSize;
public TestAccessor(CompletionListCache completionListCache)
=> _completionListCache = completionListCache;
public List<CacheEntry> GetCacheContents()
=> _completionListCache._resultIdToCompletionList;
}
public record CacheEntry(long ResultId, LSP.TextDocumentIdentifier TextDocument, CompletionList CompletionList);
}
}
| // 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 Microsoft.CodeAnalysis.Completion;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Completion
{
/// <summary>
/// Caches completion lists in between calls to CompletionHandler and
/// CompletionResolveHandler. Used to avoid unnecessary recomputation.
/// </summary>
internal class CompletionListCache
{
/// <summary>
/// Maximum number of completion lists allowed in cache. Must be >= 1.
/// </summary>
private const int MaxCacheSize = 3;
/// <summary>
/// Multiple cache requests or updates may be received concurrently.
/// We need this lock to ensure that we aren't making concurrent
/// modifications to _nextResultId or _resultIdToCompletionList.
/// </summary>
private readonly object _accessLock = new object();
#region protected by _accessLock
/// <summary>
/// The next resultId available to use.
/// </summary>
private long _nextResultId;
/// <summary>
/// Keeps track of the resultIds in the cache and their associated
/// completion list.
/// </summary>
private readonly List<CacheEntry> _resultIdToCompletionList = new();
#endregion
/// <summary>
/// Adds a completion list to the cache. If the cache reaches its maximum size, the oldest completion
/// list in the cache is removed.
/// </summary>
/// <returns>
/// The generated resultId associated with the passed in completion list.
/// </returns>
public long UpdateCache(LSP.TextDocumentIdentifier textDocument, CompletionList completionList)
{
lock (_accessLock)
{
// If cache exceeds maximum size, remove the oldest list in the cache
if (_resultIdToCompletionList.Count >= MaxCacheSize)
{
_resultIdToCompletionList.RemoveAt(0);
}
// Getting the generated unique resultId
var resultId = _nextResultId++;
// Add passed in completion list to cache
var cacheEntry = new CacheEntry(resultId, textDocument, completionList);
_resultIdToCompletionList.Add(cacheEntry);
// Return generated resultId so completion list can later be retrieved from cache
return resultId;
}
}
/// <summary>
/// Attempts to return the completion list in the cache associated with the given resultId.
/// Returns null if no match is found.
/// </summary>
public CacheEntry? GetCachedCompletionList(long resultId)
{
lock (_accessLock)
{
foreach (var cacheEntry in _resultIdToCompletionList)
{
if (cacheEntry.ResultId == resultId)
{
// We found a match - return completion list
return cacheEntry;
}
}
// A completion list associated with the given resultId was not found
return null;
}
}
internal TestAccessor GetTestAccessor() => new(this);
internal readonly struct TestAccessor
{
private readonly CompletionListCache _completionListCache;
public static int MaximumCacheSize => MaxCacheSize;
public TestAccessor(CompletionListCache completionListCache)
=> _completionListCache = completionListCache;
public List<CacheEntry> GetCacheContents()
=> _completionListCache._resultIdToCompletionList;
}
public record CacheEntry(long ResultId, LSP.TextDocumentIdentifier TextDocument, CompletionList CompletionList);
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/EditorFeatures/CSharpTest2/Recommendations/ElseKeywordRecommenderTests.cs | // 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.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class ElseKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPreprocessor1()
{
await VerifyAbsenceAsync(
@"class C {
#if $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPreprocessorFollowedBySkippedTokens()
{
await VerifyKeywordAsync(
@"#if GOO
#$$
dasd
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterHash()
{
await VerifyKeywordAsync(
@"#$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterHashAndSpace()
{
await VerifyKeywordAsync(
@"# $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterIf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if (true)
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfStatement(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfStatement_BeforeElse(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
{statement}
$$
else"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfNestedIfStatement(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
if (true)
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfNestedIfStatement_BeforeElse(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
if (true)
{statement}
$$
else"));
}
[WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfNestedIfElseStatement(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
if (true)
Console.WriteLine();
else
{statement}
$$"));
}
[WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfNestedIfElseStatement_BeforeElse(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
if (true)
Console.WriteLine();
else
{statement}
$$
else"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestNotAfterIfNestedIfElseElseStatement(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"if (true)
if (true)
Console.WriteLine();
else
Console.WriteLine();
else
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestNotAfterIfStatementElse(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"if (true)
{statement}
else
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestNotAfterIfElseStatement(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"if (true)
Console.WriteLine();
else
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfElseNestedIfStatement(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
Console.WriteLine();
else
if (true)
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfElseNestedIfStatement_BeforeElse(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
Console.WriteLine();
else
if (true)
{statement}
$$
else"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestNotAfterIfElseNestedIfElseStatement(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"if (true)
Console.WriteLine();
else
if (true)
Console.WriteLine();
else
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterWhileIfWhileNestedIfElseStatement(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"while (true)
if (true)
while (true)
if (true)
Console.WriteLine();
else
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterWhileIfWhileNestedIfElseStatement_BeforeElse(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"while (true)
if (true)
while (true)
if (true)
Console.WriteLine();
else
{statement}
$$
else"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestNotAfterWhileIfWhileNestedIfElseElseStatement(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"while (true)
if (true)
while (true)
if (true)
Console.WriteLine();
else
Console.WriteLine();
else
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console")]
[InlineData("Console.")]
[InlineData("Console.WriteLine(")]
[InlineData("Console.WriteLine()")]
[InlineData("{")]
[InlineData("{ Console.WriteLine();")]
[InlineData("while")]
[InlineData("while (true)")]
[InlineData("while (true) {")]
[InlineData("while (true) { { }")]
[InlineData("for (int i = 0;")]
public async Task TestNotAfterIfIncompleteStatement(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"if (true)
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console")]
[InlineData("Console.")]
[InlineData("Console.WriteLine(")]
[InlineData("Console.WriteLine()")]
[InlineData("{")]
[InlineData("{ Console.WriteLine();")]
[InlineData("while")]
[InlineData("while (true)")]
[InlineData("while (true) {")]
[InlineData("while (true) { { }")]
[InlineData("for (int i = 0;")]
public async Task TestNotAfterIfNestedIfIncompleteStatement(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"if (true)
if (true)
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console")]
[InlineData("Console.")]
[InlineData("Console.WriteLine(")]
[InlineData("Console.WriteLine()")]
[InlineData("{")]
[InlineData("{ Console.WriteLine();")]
[InlineData("while")]
[InlineData("while (true)")]
[InlineData("while (true) {")]
[InlineData("while (true) { { }")]
[InlineData("for (int i = 0;")]
public async Task TestNotAfterIfNestedIfElseIncompleteStatement(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"if (true)
if (true)
Console.WriteLine();
else
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfNestedIfIncompleteStatementElseStatement(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
if (true)
Console // Incomplete, but that's fine. This is not the if statement we care about.
else
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfNestedIfIncompleteStatementElseStatement_BeforeElse(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
if (true)
Console // Incomplete, but that's fine. This is not the if statement we care about.
else
{statement}
$$
else"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInsideStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if (true)
Console.WriteLine()$$; // Complete statement, but we're not at the end of it.
"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterSkippedToken()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if (true)
Console.WriteLine();,
$$"));
}
}
}
| // 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.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class ElseKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPreprocessor1()
{
await VerifyAbsenceAsync(
@"class C {
#if $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPreprocessorFollowedBySkippedTokens()
{
await VerifyKeywordAsync(
@"#if GOO
#$$
dasd
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterHash()
{
await VerifyKeywordAsync(
@"#$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterHashAndSpace()
{
await VerifyKeywordAsync(
@"# $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterIf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if (true)
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfStatement(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfStatement_BeforeElse(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
{statement}
$$
else"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfNestedIfStatement(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
if (true)
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfNestedIfStatement_BeforeElse(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
if (true)
{statement}
$$
else"));
}
[WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfNestedIfElseStatement(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
if (true)
Console.WriteLine();
else
{statement}
$$"));
}
[WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfNestedIfElseStatement_BeforeElse(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
if (true)
Console.WriteLine();
else
{statement}
$$
else"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestNotAfterIfNestedIfElseElseStatement(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"if (true)
if (true)
Console.WriteLine();
else
Console.WriteLine();
else
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestNotAfterIfStatementElse(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"if (true)
{statement}
else
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestNotAfterIfElseStatement(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"if (true)
Console.WriteLine();
else
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfElseNestedIfStatement(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
Console.WriteLine();
else
if (true)
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfElseNestedIfStatement_BeforeElse(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
Console.WriteLine();
else
if (true)
{statement}
$$
else"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestNotAfterIfElseNestedIfElseStatement(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"if (true)
Console.WriteLine();
else
if (true)
Console.WriteLine();
else
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterWhileIfWhileNestedIfElseStatement(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"while (true)
if (true)
while (true)
if (true)
Console.WriteLine();
else
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterWhileIfWhileNestedIfElseStatement_BeforeElse(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"while (true)
if (true)
while (true)
if (true)
Console.WriteLine();
else
{statement}
$$
else"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestNotAfterWhileIfWhileNestedIfElseElseStatement(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"while (true)
if (true)
while (true)
if (true)
Console.WriteLine();
else
Console.WriteLine();
else
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console")]
[InlineData("Console.")]
[InlineData("Console.WriteLine(")]
[InlineData("Console.WriteLine()")]
[InlineData("{")]
[InlineData("{ Console.WriteLine();")]
[InlineData("while")]
[InlineData("while (true)")]
[InlineData("while (true) {")]
[InlineData("while (true) { { }")]
[InlineData("for (int i = 0;")]
public async Task TestNotAfterIfIncompleteStatement(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"if (true)
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console")]
[InlineData("Console.")]
[InlineData("Console.WriteLine(")]
[InlineData("Console.WriteLine()")]
[InlineData("{")]
[InlineData("{ Console.WriteLine();")]
[InlineData("while")]
[InlineData("while (true)")]
[InlineData("while (true) {")]
[InlineData("while (true) { { }")]
[InlineData("for (int i = 0;")]
public async Task TestNotAfterIfNestedIfIncompleteStatement(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"if (true)
if (true)
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console")]
[InlineData("Console.")]
[InlineData("Console.WriteLine(")]
[InlineData("Console.WriteLine()")]
[InlineData("{")]
[InlineData("{ Console.WriteLine();")]
[InlineData("while")]
[InlineData("while (true)")]
[InlineData("while (true) {")]
[InlineData("while (true) { { }")]
[InlineData("for (int i = 0;")]
public async Task TestNotAfterIfNestedIfElseIncompleteStatement(string statement)
{
await VerifyAbsenceAsync(AddInsideMethod(
$@"if (true)
if (true)
Console.WriteLine();
else
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfNestedIfIncompleteStatementElseStatement(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
if (true)
Console // Incomplete, but that's fine. This is not the if statement we care about.
else
{statement}
$$"));
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[InlineData("Console.WriteLine();")]
[InlineData("{ }")]
[InlineData("while (true) { }")]
public async Task TestAfterIfNestedIfIncompleteStatementElseStatement_BeforeElse(string statement)
{
await VerifyKeywordAsync(AddInsideMethod(
$@"if (true)
if (true)
Console // Incomplete, but that's fine. This is not the if statement we care about.
else
{statement}
$$
else"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInsideStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if (true)
Console.WriteLine()$$; // Complete statement, but we're not at the end of it.
"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterSkippedToken()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if (true)
Console.WriteLine();,
$$"));
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Analyzers/CSharp/Tests/FileHeaders/FileHeaderTests.cs | // 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier<
Microsoft.CodeAnalysis.CSharp.FileHeaders.CSharpFileHeaderDiagnosticAnalyzer,
Microsoft.CodeAnalysis.CSharp.FileHeaders.CSharpFileHeaderCodeFixProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.FileHeaders
{
public class FileHeaderTests
{
private const string TestSettings = @"
[*.cs]
file_header_template = Copyright (c) SomeCorp. All rights reserved.\nLicensed under the ??? license. See LICENSE file in the project root for full license information.
";
private const string TestSettingsWithEmptyLines = @"
[*.cs]
file_header_template = \nCopyright (c) SomeCorp. All rights reserved.\n\nLicensed under the ??? license. See LICENSE file in the project root for full license information.\n
";
/// <summary>
/// Verifies that the analyzer will not report a diagnostic when the file header is not configured.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[InlineData("")]
[InlineData("file_header_template =")]
[InlineData("file_header_template = unset")]
public async Task TestFileHeaderNotConfiguredAsync(string fileHeaderTemplate)
{
var testCode = @"namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = testCode,
EditorConfig = $@"
[*]
{fileHeaderTemplate}
",
}.RunAsync();
}
/// <summary>
/// Verifies that the analyzer will report a diagnostic when the file is completely missing a header.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestNoFileHeaderAsync()
{
var testCode = @"[||]namespace N
{
}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that the analyzer will report a diagnostic when the file is completely missing a header.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestNoFileHeaderWithUsingDirectiveAsync()
{
var testCode = @"[||]using System;
namespace N
{
}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
using System;
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that the analyzer will report a diagnostic when the file is completely missing a header.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestNoFileHeaderWithBlankLineAndUsingDirectiveAsync()
{
var testCode = @"[||]
using System;
namespace N
{
}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
using System;
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that the analyzer will report a diagnostic when the file is completely missing a header.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestNoFileHeaderWithWhitespaceLineAsync()
{
var testCode = "[||] " + @"
using System;
namespace N
{
}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
using System;
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that the built-in variable <c>fileName</c> works as expected.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestFileNameBuiltInVariableAsync()
{
var editorConfig = @"
[*.cs]
file_header_template = {fileName} Copyright (c) SomeCorp. All rights reserved.\nLicensed under the ??? license. See LICENSE file in the project root for full license information.
";
var testCode = @"[||]namespace N
{
}
";
var fixedCode = @"// Test0.cs Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = editorConfig,
}.RunAsync();
}
/// <summary>
/// Verifies that a valid file header built using single line comments will not produce a diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestValidFileHeaderWithSingleLineCommentsAsync()
{
var testCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = testCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that a valid file header built using multi-line comments will not produce a diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestValidFileHeaderWithMultiLineComments1Async()
{
var testCode = @"/* Copyright (c) SomeCorp. All rights reserved.
* Licensed under the ??? license. See LICENSE file in the project root for full license information.
*/
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = testCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that a valid file header built using multi-line comments will not produce a diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestValidFileHeaderWithMultiLineComments2Async()
{
var testCode = @"/* Copyright (c) SomeCorp. All rights reserved.
Licensed under the ??? license. See LICENSE file in the project root for full license information. */
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = testCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that a valid file header built using unterminated multi-line comments will not produce a diagnostic
/// message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestValidFileHeaderWithMultiLineComments3Async()
{
var testCode = @"/* Copyright (c) SomeCorp. All rights reserved.
Licensed under the ??? license. See LICENSE file in the project root for full license information.
";
await new VerifyCS.Test
{
TestCode = testCode,
ExpectedDiagnostics =
{
// /0/Test0.cs(1,1): error CS1035: End-of-file found, '*/' expected
DiagnosticResult.CompilerError("CS1035").WithSpan(1, 1, 1, 1),
},
FixedCode = testCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that a file header without text / only whitespace will produce the expected diagnostic message.
/// </summary>
/// <param name="comment">The comment text.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[InlineData("[|//|]")]
[InlineData("[|//|] ")]
public async Task TestInvalidFileHeaderWithoutTextAsync(string comment)
{
var testCode = $@"{comment}
namespace Bar
{{
}}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestInvalidFileHeaderWithWrongTextAsync()
{
var testCode = @"[|//|] Copyright (c) OtherCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace Bar
{
}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestInvalidFileHeaderWithWrongText2Async()
{
var testCode = @"[|/*|] Copyright (c) OtherCorp. All rights reserved.
* Licensed under the ??? license. See LICENSE file in the project root for full license information.
*/
namespace Bar
{
}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
/* Copyright (c) OtherCorp. All rights reserved.
* Licensed under the ??? license. See LICENSE file in the project root for full license information.
*/
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
[Theory]
[InlineData("", "")]
[InlineData(" Header", "")]
[InlineData(" Header", " Header")]
public async Task TestValidFileHeaderInRegionAsync(string startLabel, string endLabel)
{
var testCode = $@"#region{startLabel}
// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
#endregion{endLabel}
namespace Bar
{{
}}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = testCode,
EditorConfig = TestSettings,
}.RunAsync();
}
[Theory]
[InlineData("", "")]
[InlineData(" Header", "")]
[InlineData(" Header", " Header")]
public async Task TestInvalidFileHeaderWithWrongTextInRegionAsync(string startLabel, string endLabel)
{
var testCode = $@"#region{startLabel}
[|//|] Copyright (c) OtherCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
#endregion{endLabel}
namespace Bar
{{
}}
";
var fixedCode = $@"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
#region{startLabel}
// Copyright (c) OtherCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
#endregion{endLabel}
namespace Bar
{{
}}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestInvalidFileHeaderWithWrongTextInUnterminatedMultiLineComment1Async()
{
var testCode = @"{|CS1035:|}[|/*|] Copyright (c) OtherCorp. All rights reserved.
* Licensed under the ??? license. See LICENSE file in the project root for full license information.
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
{|CS1035:|}/* Copyright (c) OtherCorp. All rights reserved.
* Licensed under the ??? license. See LICENSE file in the project root for full license information.
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestInvalidFileHeaderWithWrongTextInUnterminatedMultiLineComment2Async()
{
var testCode = @"{|CS1035:|}[|/*|]/
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
{|CS1035:|}/*/
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[InlineData("")]
[InlineData(" ")]
public async Task TestInvalidFileHeaderWithWrongTextAfterBlankLineAsync(string firstLine)
{
var testCode = $@"{firstLine}
[|//|] Copyright (c) OtherCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace Bar
{{
}}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestInvalidFileHeaderWithWrongTextFollowedByCommentAsync()
{
var testCode = @"[|//|] Copyright (c) OtherCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
//using System;
namespace Bar
{
}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
//using System;
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
[Fact]
public async Task TestHeaderMissingRequiredNewLinesAsync()
{
var testCode = @"[|//|] Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace Bar
{
}
";
var fixedCode = @"//
// Copyright (c) SomeCorp. All rights reserved.
//
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
//
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettingsWithEmptyLines,
}.RunAsync();
}
}
}
| // 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier<
Microsoft.CodeAnalysis.CSharp.FileHeaders.CSharpFileHeaderDiagnosticAnalyzer,
Microsoft.CodeAnalysis.CSharp.FileHeaders.CSharpFileHeaderCodeFixProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.FileHeaders
{
public class FileHeaderTests
{
private const string TestSettings = @"
[*.cs]
file_header_template = Copyright (c) SomeCorp. All rights reserved.\nLicensed under the ??? license. See LICENSE file in the project root for full license information.
";
private const string TestSettingsWithEmptyLines = @"
[*.cs]
file_header_template = \nCopyright (c) SomeCorp. All rights reserved.\n\nLicensed under the ??? license. See LICENSE file in the project root for full license information.\n
";
/// <summary>
/// Verifies that the analyzer will not report a diagnostic when the file header is not configured.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[InlineData("")]
[InlineData("file_header_template =")]
[InlineData("file_header_template = unset")]
public async Task TestFileHeaderNotConfiguredAsync(string fileHeaderTemplate)
{
var testCode = @"namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = testCode,
EditorConfig = $@"
[*]
{fileHeaderTemplate}
",
}.RunAsync();
}
/// <summary>
/// Verifies that the analyzer will report a diagnostic when the file is completely missing a header.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestNoFileHeaderAsync()
{
var testCode = @"[||]namespace N
{
}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that the analyzer will report a diagnostic when the file is completely missing a header.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestNoFileHeaderWithUsingDirectiveAsync()
{
var testCode = @"[||]using System;
namespace N
{
}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
using System;
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that the analyzer will report a diagnostic when the file is completely missing a header.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestNoFileHeaderWithBlankLineAndUsingDirectiveAsync()
{
var testCode = @"[||]
using System;
namespace N
{
}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
using System;
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that the analyzer will report a diagnostic when the file is completely missing a header.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestNoFileHeaderWithWhitespaceLineAsync()
{
var testCode = "[||] " + @"
using System;
namespace N
{
}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
using System;
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that the built-in variable <c>fileName</c> works as expected.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestFileNameBuiltInVariableAsync()
{
var editorConfig = @"
[*.cs]
file_header_template = {fileName} Copyright (c) SomeCorp. All rights reserved.\nLicensed under the ??? license. See LICENSE file in the project root for full license information.
";
var testCode = @"[||]namespace N
{
}
";
var fixedCode = @"// Test0.cs Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = editorConfig,
}.RunAsync();
}
/// <summary>
/// Verifies that a valid file header built using single line comments will not produce a diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestValidFileHeaderWithSingleLineCommentsAsync()
{
var testCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = testCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that a valid file header built using multi-line comments will not produce a diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestValidFileHeaderWithMultiLineComments1Async()
{
var testCode = @"/* Copyright (c) SomeCorp. All rights reserved.
* Licensed under the ??? license. See LICENSE file in the project root for full license information.
*/
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = testCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that a valid file header built using multi-line comments will not produce a diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestValidFileHeaderWithMultiLineComments2Async()
{
var testCode = @"/* Copyright (c) SomeCorp. All rights reserved.
Licensed under the ??? license. See LICENSE file in the project root for full license information. */
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = testCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that a valid file header built using unterminated multi-line comments will not produce a diagnostic
/// message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestValidFileHeaderWithMultiLineComments3Async()
{
var testCode = @"/* Copyright (c) SomeCorp. All rights reserved.
Licensed under the ??? license. See LICENSE file in the project root for full license information.
";
await new VerifyCS.Test
{
TestCode = testCode,
ExpectedDiagnostics =
{
// /0/Test0.cs(1,1): error CS1035: End-of-file found, '*/' expected
DiagnosticResult.CompilerError("CS1035").WithSpan(1, 1, 1, 1),
},
FixedCode = testCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that a file header without text / only whitespace will produce the expected diagnostic message.
/// </summary>
/// <param name="comment">The comment text.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[InlineData("[|//|]")]
[InlineData("[|//|] ")]
public async Task TestInvalidFileHeaderWithoutTextAsync(string comment)
{
var testCode = $@"{comment}
namespace Bar
{{
}}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestInvalidFileHeaderWithWrongTextAsync()
{
var testCode = @"[|//|] Copyright (c) OtherCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace Bar
{
}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestInvalidFileHeaderWithWrongText2Async()
{
var testCode = @"[|/*|] Copyright (c) OtherCorp. All rights reserved.
* Licensed under the ??? license. See LICENSE file in the project root for full license information.
*/
namespace Bar
{
}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
/* Copyright (c) OtherCorp. All rights reserved.
* Licensed under the ??? license. See LICENSE file in the project root for full license information.
*/
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
[Theory]
[InlineData("", "")]
[InlineData(" Header", "")]
[InlineData(" Header", " Header")]
public async Task TestValidFileHeaderInRegionAsync(string startLabel, string endLabel)
{
var testCode = $@"#region{startLabel}
// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
#endregion{endLabel}
namespace Bar
{{
}}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = testCode,
EditorConfig = TestSettings,
}.RunAsync();
}
[Theory]
[InlineData("", "")]
[InlineData(" Header", "")]
[InlineData(" Header", " Header")]
public async Task TestInvalidFileHeaderWithWrongTextInRegionAsync(string startLabel, string endLabel)
{
var testCode = $@"#region{startLabel}
[|//|] Copyright (c) OtherCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
#endregion{endLabel}
namespace Bar
{{
}}
";
var fixedCode = $@"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
#region{startLabel}
// Copyright (c) OtherCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
#endregion{endLabel}
namespace Bar
{{
}}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestInvalidFileHeaderWithWrongTextInUnterminatedMultiLineComment1Async()
{
var testCode = @"{|CS1035:|}[|/*|] Copyright (c) OtherCorp. All rights reserved.
* Licensed under the ??? license. See LICENSE file in the project root for full license information.
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
{|CS1035:|}/* Copyright (c) OtherCorp. All rights reserved.
* Licensed under the ??? license. See LICENSE file in the project root for full license information.
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestInvalidFileHeaderWithWrongTextInUnterminatedMultiLineComment2Async()
{
var testCode = @"{|CS1035:|}[|/*|]/
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
{|CS1035:|}/*/
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Theory]
[InlineData("")]
[InlineData(" ")]
public async Task TestInvalidFileHeaderWithWrongTextAfterBlankLineAsync(string firstLine)
{
var testCode = $@"{firstLine}
[|//|] Copyright (c) OtherCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace Bar
{{
}}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
/// <summary>
/// Verifies that an invalid file header built using single line comments will produce the expected diagnostic message.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestInvalidFileHeaderWithWrongTextFollowedByCommentAsync()
{
var testCode = @"[|//|] Copyright (c) OtherCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
//using System;
namespace Bar
{
}
";
var fixedCode = @"// Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
//using System;
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettings,
}.RunAsync();
}
[Fact]
public async Task TestHeaderMissingRequiredNewLinesAsync()
{
var testCode = @"[|//|] Copyright (c) SomeCorp. All rights reserved.
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
namespace Bar
{
}
";
var fixedCode = @"//
// Copyright (c) SomeCorp. All rights reserved.
//
// Licensed under the ??? license. See LICENSE file in the project root for full license information.
//
namespace Bar
{
}
";
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
EditorConfig = TestSettingsWithEmptyLines,
}.RunAsync();
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/CSharp/Portable/Syntax/LocalFunctionStatementSyntax.cs | // 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 Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class LocalFunctionStatementSyntax
{
// Preserved as shipped public API for binary compatibility
public LocalFunctionStatementSyntax Update(SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken)
{
return Update(AttributeLists, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken);
}
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
// Preserved as shipped public API for binary compatibility
public static LocalFunctionStatementSyntax LocalFunctionStatement(SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody)
{
return LocalFunctionStatement(attributeLists: default, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken: default);
}
// Preserved as shipped public API for binary compatibility
public static LocalFunctionStatementSyntax LocalFunctionStatement(SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken)
{
return LocalFunctionStatement(attributeLists: default, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken);
}
}
}
| // 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 Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class LocalFunctionStatementSyntax
{
// Preserved as shipped public API for binary compatibility
public LocalFunctionStatementSyntax Update(SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken)
{
return Update(AttributeLists, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken);
}
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
// Preserved as shipped public API for binary compatibility
public static LocalFunctionStatementSyntax LocalFunctionStatement(SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody)
{
return LocalFunctionStatement(attributeLists: default, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken: default);
}
// Preserved as shipped public API for binary compatibility
public static LocalFunctionStatementSyntax LocalFunctionStatement(SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken)
{
return LocalFunctionStatement(attributeLists: default, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken);
}
}
}
| -1 |
dotnet/roslyn | 55,729 | Warm up ImportCompletion cache in background when opening a document | Closes #37197 | genlu | 2021-08-19T19:35:38Z | 2021-08-30T19:55:34Z | 50833c98fbe69edfabced985a7895bbe9c560793 | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | Warm up ImportCompletion cache in background when opening a document. Closes #37197 | ./src/Compilers/Test/Resources/Core/SymbolsTests/InheritIComparable.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L UfM ! ' @ @ @ X' S @ ` & |