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&lt;string&gt; SemanticModel.LookupNames(CSharpSyntaxNode location, NamespaceOrTypeSymbol container = null, LookupOptions options = LookupOptions.Default, List&lt;string> result = null); /// IList&lt;Symbol&gt; SemanticModel.LookupSymbols(CSharpSyntaxNode location, NamespaceOrTypeSymbol container = null, string name = null, int? arity = null, LookupOptions options = LookupOptions.Default, List&lt;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&lt;string&gt; SemanticModel.LookupNames(CSharpSyntaxNode location, NamespaceOrTypeSymbol container = null, LookupOptions options = LookupOptions.Default, List&lt;string> result = null); /// IList&lt;Symbol&gt; SemanticModel.LookupSymbols(CSharpSyntaxNode location, NamespaceOrTypeSymbol container = null, string name = null, int? arity = null, LookupOptions options = LookupOptions.Default, List&lt;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. $PEL;P!  ^$ @ _@$W@`  H.textd  `.rsrc@@@.reloc ` @B@$H  t ( *0 +*( * 7D6$'K5>UXOHVUVçd՝v\bHd2K,݁l2Ǝ] gi$;WRt9;iޮ6M)xQOBSJB v4.0.30319l #~x#Strings#US#GUID(#BlobG %3 T4t4P ' X -l '  ' '' .. 2<Module>mscorlibCD`1SystemObject.ctorMainTSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeC.dll Q2B-d#?z\V4  $$RSA1oO6vk3$jMҭ2eRcعU[IFo2eު3J߾plV nY½%R;=3! K`ay0TWrapNonExceptionThrows,$N$ @$_CorDllMainmscoree.dll% 0HX@,,4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfoh000004b0,FileDescription 0FileVersion2.0.0.0,InternalNameC.dll(LegalCopyright 4OriginalFilenameC.dll4ProductVersion2.0.0.08Assembly Version2.0.0.0 `4
MZ@ !L!This program cannot be run in DOS mode. $PEL;P!  ^$ @ _@$W@`  H.textd  `.rsrc@@@.reloc ` @B@$H  t ( *0 +*( * 7D6$'K5>UXOHVUVçd՝v\bHd2K,݁l2Ǝ] gi$;WRt9;iޮ6M)xQOBSJB v4.0.30319l #~x#Strings#US#GUID(#BlobG %3 T4t4P ' X -l '  ' '' .. 2<Module>mscorlibCD`1SystemObject.ctorMainTSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeC.dll Q2B-d#?z\V4  $$RSA1oO6vk3$jMҭ2eRcعU[IFo2eު3J߾plV nY½%R;=3! K`ay0TWrapNonExceptionThrows,$N$ @$_CorDllMainmscoree.dll% 0HX@,,4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfoh000004b0,FileDescription 0FileVersion2.0.0.0,InternalNameC.dll(LegalCopyright 4OriginalFilenameC.dll4ProductVersion2.0.0.08Assembly Version2.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. $PELUfM! ' @@ @X'S@` &  H.text  `.rsrc@ @@.reloc `@B'H 0 +*( *( *0 +*( *BSJB v4.0.30319l#~p8#Strings#US#GUIDX#BlobG %3  `YgYsY}Y7$#KzZZ !8 EH MP  c k t   )1A"Q(Y a1q'K7.. <.#.+- P<Module>InheritIComparable.dllBaseTypeSpecifierClassFooAttributeI1TestN1mscorlibSystemObjectIComparableAttributeValueTypeCompareTo.ctorMethodI1.MethodoSystem.Runtime.VersioningTargetFrameworkAttributeSystem.Security.PermissionsSecurityPermissionAttributeSecurityActionSystem.DiagnosticsDebuggableAttributeDebuggingModesSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeInheritIComparableSystem.Runtime.InteropServicesStructLayoutAttributeLayoutKindSystem.SecurityUnverifiableCodeAttribute X+MV>4tz\V4      %  5G.NETFramework,Version=v4.0TFrameworkDisplayName.NET Framework 4TWrapNonExceptionThrows.System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089TSkipVerificationUfM&RSDSMzCNSDC:\Users\v-vilou\Documents\Visual Studio 2010\Projects\ConsoleApplication10\ClassLibrary1\obj\Debug\InheritIComparable.pdb'' '_CorDllMainmscoree.dll% @0HX@tt4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0PInternalNameInheritIComparable.dll(LegalCopyright XOriginalFilenameInheritIComparable.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 7
MZ@ !L!This program cannot be run in DOS mode. $PELUfM! ' @@ @X'S@` &  H.text  `.rsrc@ @@.reloc `@B'H 0 +*( *( *0 +*( *BSJB v4.0.30319l#~p8#Strings#US#GUIDX#BlobG %3  `YgYsY}Y7$#KzZZ !8 EH MP  c k t   )1A"Q(Y a1q'K7.. <.#.+- P<Module>InheritIComparable.dllBaseTypeSpecifierClassFooAttributeI1TestN1mscorlibSystemObjectIComparableAttributeValueTypeCompareTo.ctorMethodI1.MethodoSystem.Runtime.VersioningTargetFrameworkAttributeSystem.Security.PermissionsSecurityPermissionAttributeSecurityActionSystem.DiagnosticsDebuggableAttributeDebuggingModesSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeInheritIComparableSystem.Runtime.InteropServicesStructLayoutAttributeLayoutKindSystem.SecurityUnverifiableCodeAttribute X+MV>4tz\V4      %  5G.NETFramework,Version=v4.0TFrameworkDisplayName.NET Framework 4TWrapNonExceptionThrows.System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089TSkipVerificationUfM&RSDSMzCNSDC:\Users\v-vilou\Documents\Visual Studio 2010\Projects\ConsoleApplication10\ClassLibrary1\obj\Debug\InheritIComparable.pdb'' '_CorDllMainmscoree.dll% @0HX@tt4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0PInternalNameInheritIComparable.dll(LegalCopyright XOriginalFilenameInheritIComparable.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 7
-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/UseIndexOrRangeOperator/UseIndexOperatorTests.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.CSharp; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator.CSharpUseIndexOperatorDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator.CSharpUseIndexOperatorCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseIndexOrRangeOperator { public class UseIndexOperatorTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotInCSharp7() { var source = @" class C { void Goo(string s) { var v = s[s.Length - 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, LanguageVersion = LanguageVersion.CSharp7, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)] public async Task TestWithMissingReference() { var source = @"class {|#0:C|} { {|#1:void|} Goo({|#2:string|} s) { var v = s[s.Length - {|#3:1|}]; } }"; await new VerifyCS.Test { ReferenceAssemblies = new ReferenceAssemblies("custom"), TestCode = source, ExpectedDiagnostics = { // /0/Test0.cs(1,7): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(0).WithArguments("System.Object"), // /0/Test0.cs(1,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments DiagnosticResult.CompilerError("CS1729").WithLocation(0).WithArguments("object", "0"), // /0/Test0.cs(3,5): error CS0518: Predefined type 'System.Void' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(1).WithArguments("System.Void"), // /0/Test0.cs(3,14): error CS0518: Predefined type 'System.String' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(2).WithArguments("System.String"), // /0/Test0.cs(5,30): error CS0518: Predefined type 'System.Int32' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(3).WithArguments("System.Int32"), }, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestSimple() { var source = @" class C { void Goo(string s) { var v = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMultipleDefinitions() { var source = @" class C { void Goo(string s) { var v = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v = s[^1]; } }"; // Adding a dependency with internal definitions of Index and Range should not break the feature var source1 = "namespace System { internal struct Index { } internal struct Range { } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestState = { Sources = { source }, AdditionalProjects = { ["DependencyProject"] = { ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20, Sources = { source1 }, }, }, AdditionalProjectReferences = { "DependencyProject" }, }, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestComplexSubtaction() { var source = @" class C { void Goo(string s) { var v = s[[|s.Length - (1 + 1)|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v = s[^(1 + 1)]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestComplexInstance() { var source = @" using System.Linq; class C { void Goo(string[] ss) { var v = ss.Last()[[|ss.Last().Length - 3|]]; } }"; var fixedSource = @" using System.Linq; class C { void Goo(string[] ss) { var v = ss.Last()[^3]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotWithoutSubtraction1() { var source = @" class C { void Goo(string s) { var v = s[s.Length]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotWithoutSubtraction2() { var source = @" class C { void Goo(string s) { var v = s[s.Length + 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotWithMultipleArgs() { var source = @" struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[int i, int j] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[s.Length - 1, 2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithLength() { var source = @" struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[[|s.Length - 2|]]; } }"; var fixedSource = @" struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[^2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithCount() { var source = @" struct S { public int Count { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[[|s.Count - 2|]]; } }"; var fixedSource = @" struct S { public int Count { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[^2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithNoLengthOrCount() { var source = @" struct S { public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[s.{|CS1061:Count|} - 2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithNoInt32Indexer() { var source = @" struct S { public int Length { get; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[s.Length - 2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithNoIndexIndexer() { var source = @" struct S { public int Count { get; } public int this[int i] { get => 0; } } class C { void Goo(S s) { var v = s[[|s.Count - 2|]]; } }"; var fixedSource = @" struct S { public int Count { get; } public int this[int i] { get => 0; } } class C { void Goo(S s) { var v = s[^2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMethodToMethod() { var source = @" struct S { public int Length { get; } public int Get(int i) => 0; public int Get(System.Index i) => 0; } class C { void Goo(S s) { var v = s.Get([|s.Length - 1|]); } }"; var fixedSource = @" struct S { public int Length { get; } public int Get(int i) => 0; public int Get(System.Index i) => 0; } class C { void Goo(S s) { var v = s.Get(^1); } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMethodToMethodMissingIndexIndexer() { var source = @" struct S { public int Length { get; } public int Get(int i) => 0; } class C { void Goo(S s) { var v = s.Get(s.Length - 1); } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMethodToMethodWithIntIndexer() { var source = @" struct S { public int Length { get; } public int Get(int i) => 0; public int this[int i] { get => 0; } } class C { void Goo(S s) { var v = s.Get(s.Length - 1); } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [WorkItem(36909, "https://github.com/dotnet/roslyn/issues/36909")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMissingWithNoSystemIndex() { var source = @" class C { void Goo(string[] s) { var v = s[s.Length - 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp20, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestArray() { var source = @" class C { void Goo(string[] s) { var v = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string[] s) { var v = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestFixAll1() { var source = @" class C { void Goo(string s) { var v1 = s[[|s.Length - 1|]]; var v2 = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v1 = s[^1]; var v2 = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNestedFixAll1() { var source = @" class C { void Goo(string[] s) { var v1 = s[[|s.Length - 2|]][[|s[[|s.Length - 2|]].Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string[] s) { var v1 = s[^2][^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNestedFixAll2() { var source = @" class C { void Goo(string[] s) { var v1 = s[[|s.Length - 2|]][[|s[[|s.Length - 2|]].Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string[] s) { var v1 = s[^2][^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestSimple_NoIndexIndexer_SupportsIntIndexer() { var source = @" using System.Collections.Generic; class C { void Goo(List<int> s) { var v = s[[|s.Count - 1|]]; } }"; var fixedSource = @" using System.Collections.Generic; class C { void Goo(List<int> s) { var v = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestSimple_NoIndexIndexer_SupportsIntIndexer_Set() { var source = @" using System.Collections.Generic; class C { void Goo(List<int> s) { s[[|s.Count - 1|]] = 1; } }"; var fixedSource = @" using System.Collections.Generic; class C { void Goo(List<int> s) { s[^1] = 1; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task NotOnConstructedIndexer() { var source = @" using System.Collections.Generic; class C { void Goo(Dictionary<int, string> s) { var v = s[s.Count - 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator.CSharpUseIndexOperatorDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator.CSharpUseIndexOperatorCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseIndexOrRangeOperator { public class UseIndexOperatorTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotInCSharp7() { var source = @" class C { void Goo(string s) { var v = s[s.Length - 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, LanguageVersion = LanguageVersion.CSharp7, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)] public async Task TestWithMissingReference() { var source = @"class {|#0:C|} { {|#1:void|} Goo({|#2:string|} s) { var v = s[s.Length - {|#3:1|}]; } }"; await new VerifyCS.Test { ReferenceAssemblies = new ReferenceAssemblies("custom"), TestCode = source, ExpectedDiagnostics = { // /0/Test0.cs(1,7): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(0).WithArguments("System.Object"), // /0/Test0.cs(1,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments DiagnosticResult.CompilerError("CS1729").WithLocation(0).WithArguments("object", "0"), // /0/Test0.cs(3,5): error CS0518: Predefined type 'System.Void' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(1).WithArguments("System.Void"), // /0/Test0.cs(3,14): error CS0518: Predefined type 'System.String' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(2).WithArguments("System.String"), // /0/Test0.cs(5,30): error CS0518: Predefined type 'System.Int32' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(3).WithArguments("System.Int32"), }, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestSimple() { var source = @" class C { void Goo(string s) { var v = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMultipleDefinitions() { var source = @" class C { void Goo(string s) { var v = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v = s[^1]; } }"; // Adding a dependency with internal definitions of Index and Range should not break the feature var source1 = "namespace System { internal struct Index { } internal struct Range { } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestState = { Sources = { source }, AdditionalProjects = { ["DependencyProject"] = { ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20, Sources = { source1 }, }, }, AdditionalProjectReferences = { "DependencyProject" }, }, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestComplexSubtaction() { var source = @" class C { void Goo(string s) { var v = s[[|s.Length - (1 + 1)|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v = s[^(1 + 1)]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestComplexInstance() { var source = @" using System.Linq; class C { void Goo(string[] ss) { var v = ss.Last()[[|ss.Last().Length - 3|]]; } }"; var fixedSource = @" using System.Linq; class C { void Goo(string[] ss) { var v = ss.Last()[^3]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotWithoutSubtraction1() { var source = @" class C { void Goo(string s) { var v = s[s.Length]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotWithoutSubtraction2() { var source = @" class C { void Goo(string s) { var v = s[s.Length + 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotWithMultipleArgs() { var source = @" struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[int i, int j] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[s.Length - 1, 2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithLength() { var source = @" struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[[|s.Length - 2|]]; } }"; var fixedSource = @" struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[^2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithCount() { var source = @" struct S { public int Count { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[[|s.Count - 2|]]; } }"; var fixedSource = @" struct S { public int Count { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[^2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithNoLengthOrCount() { var source = @" struct S { public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[s.{|CS1061:Count|} - 2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithNoInt32Indexer() { var source = @" struct S { public int Length { get; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[s.Length - 2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithNoIndexIndexer() { var source = @" struct S { public int Count { get; } public int this[int i] { get => 0; } } class C { void Goo(S s) { var v = s[[|s.Count - 2|]]; } }"; var fixedSource = @" struct S { public int Count { get; } public int this[int i] { get => 0; } } class C { void Goo(S s) { var v = s[^2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMethodToMethod() { var source = @" struct S { public int Length { get; } public int Get(int i) => 0; public int Get(System.Index i) => 0; } class C { void Goo(S s) { var v = s.Get([|s.Length - 1|]); } }"; var fixedSource = @" struct S { public int Length { get; } public int Get(int i) => 0; public int Get(System.Index i) => 0; } class C { void Goo(S s) { var v = s.Get(^1); } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMethodToMethodMissingIndexIndexer() { var source = @" struct S { public int Length { get; } public int Get(int i) => 0; } class C { void Goo(S s) { var v = s.Get(s.Length - 1); } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMethodToMethodWithIntIndexer() { var source = @" struct S { public int Length { get; } public int Get(int i) => 0; public int this[int i] { get => 0; } } class C { void Goo(S s) { var v = s.Get(s.Length - 1); } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [WorkItem(36909, "https://github.com/dotnet/roslyn/issues/36909")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMissingWithNoSystemIndex() { var source = @" class C { void Goo(string[] s) { var v = s[s.Length - 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp20, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestArray() { var source = @" class C { void Goo(string[] s) { var v = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string[] s) { var v = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestFixAll1() { var source = @" class C { void Goo(string s) { var v1 = s[[|s.Length - 1|]]; var v2 = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v1 = s[^1]; var v2 = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNestedFixAll1() { var source = @" class C { void Goo(string[] s) { var v1 = s[[|s.Length - 2|]][[|s[[|s.Length - 2|]].Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string[] s) { var v1 = s[^2][^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNestedFixAll2() { var source = @" class C { void Goo(string[] s) { var v1 = s[[|s.Length - 2|]][[|s[[|s.Length - 2|]].Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string[] s) { var v1 = s[^2][^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestSimple_NoIndexIndexer_SupportsIntIndexer() { var source = @" using System.Collections.Generic; class C { void Goo(List<int> s) { var v = s[[|s.Count - 1|]]; } }"; var fixedSource = @" using System.Collections.Generic; class C { void Goo(List<int> s) { var v = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestSimple_NoIndexIndexer_SupportsIntIndexer_Set() { var source = @" using System.Collections.Generic; class C { void Goo(List<int> s) { s[[|s.Count - 1|]] = 1; } }"; var fixedSource = @" using System.Collections.Generic; class C { void Goo(List<int> s) { s[^1] = 1; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task NotOnConstructedIndexer() { var source = @" using System.Collections.Generic; class C { void Goo(Dictionary<int, string> s) { var v = s[s.Count - 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.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/VisualStudio/Core/Def/Implementation/Venus/ContainedLanguage.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; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { internal partial class ContainedLanguage { private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; private readonly IDiagnosticAnalyzerService _diagnosticAnalyzerService; private readonly Guid _languageServiceGuid; protected readonly Workspace Workspace; protected readonly IComponentModel ComponentModel; public VisualStudioProject? Project { get; } protected readonly ContainedDocument ContainedDocument; public IVsTextBufferCoordinator BufferCoordinator { get; protected set; } /// <summary> /// The subject (secondary) buffer that contains the C# or VB code. /// </summary> public ITextBuffer SubjectBuffer { get; } /// <summary> /// The underlying buffer that contains C# or VB code. NOTE: This is NOT the "document" buffer /// that is saved to disk. Instead it is the view that the user sees. The normal buffer graph /// in Venus includes 4 buffers: /// <code> /// SurfaceBuffer/Databuffer (projection) /// / | /// Subject Buffer (C#/VB projection) | /// | | /// Inert (generated) C#/VB Buffer Document (aspx) buffer /// </code> /// In normal circumstance, the Subject and Inert C# buffer are identical in content, and the /// Surface and Document are also identical. The Subject Buffer is the one that is part of the /// workspace, that most language operations deal with. The surface buffer is the one that the /// view is created over, and the Document buffer is the one that is saved to disk. /// </summary> public ITextBuffer DataBuffer { get; } // Set when a TextViewFIlter is set. We hold onto this to keep our TagSource objects alive even if Venus // disconnects the subject buffer from the view temporarily (which they do frequently). Otherwise, we have to // re-compute all of the tag data when they re-connect it, and this causes issues like classification // flickering. private readonly ITagAggregator<ITag> _bufferTagAggregator; [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal ContainedLanguage( IVsTextBufferCoordinator bufferCoordinator, IComponentModel componentModel, VisualStudioProject? project, IVsHierarchy hierarchy, uint itemid, VisualStudioProjectTracker? projectTrackerOpt, ProjectId projectId, Guid languageServiceGuid, AbstractFormattingRule? vbHelperFormattingRule = null) : this(bufferCoordinator, componentModel, projectTrackerOpt?.Workspace ?? componentModel.GetService<VisualStudioWorkspace>(), projectId, project, GetFilePathFromHierarchyAndItemId(hierarchy, itemid), languageServiceGuid, vbHelperFormattingRule) { } public static string GetFilePathFromHierarchyAndItemId(IVsHierarchy hierarchy, uint itemid) { if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemid, out var filePath))) { // we couldn't look up the document moniker from an hierarchy for an itemid. // Since we only use this moniker as a key, we could fall back to something else, like the document name. Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy."); if (!hierarchy.TryGetItemName(itemid, out filePath!)) { FatalError.ReportAndPropagate(new InvalidOperationException("Failed to get document moniker for a contained document")); } } return filePath; } internal ContainedLanguage( IVsTextBufferCoordinator bufferCoordinator, IComponentModel componentModel, Workspace workspace, ProjectId projectId, VisualStudioProject? project, string filePath, Guid languageServiceGuid, AbstractFormattingRule? vbHelperFormattingRule = null) { this.BufferCoordinator = bufferCoordinator; this.ComponentModel = componentModel; this.Project = project; _languageServiceGuid = languageServiceGuid; this.Workspace = workspace; _editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>(); _diagnosticAnalyzerService = componentModel.GetService<IDiagnosticAnalyzerService>(); // Get the ITextBuffer for the secondary buffer Marshal.ThrowExceptionForHR(bufferCoordinator.GetSecondaryBuffer(out var secondaryTextLines)); SubjectBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(secondaryTextLines)!; // Get the ITextBuffer for the primary buffer Marshal.ThrowExceptionForHR(bufferCoordinator.GetPrimaryBuffer(out var primaryTextLines)); DataBuffer = _editorAdaptersFactoryService.GetDataBuffer(primaryTextLines)!; // Create our tagger var bufferTagAggregatorFactory = ComponentModel.GetService<IBufferTagAggregatorFactoryService>(); _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator<ITag>(SubjectBuffer); DocumentId documentId; if (this.Project != null) { documentId = this.Project.AddSourceTextContainer( SubjectBuffer.AsTextContainer(), filePath, sourceCodeKind: SourceCodeKind.Regular, folders: default, designTimeOnly: true, documentServiceProvider: new ContainedDocument.DocumentServiceProvider(DataBuffer)); } else { documentId = DocumentId.CreateNewId(projectId, $"{nameof(ContainedDocument)}: {filePath}"); // We must jam a document into an existing workspace, which we'll assume is safe to do with OnDocumentAdded Workspace.OnDocumentAdded(DocumentInfo.Create(documentId, filePath, filePath: filePath)); Workspace.OnDocumentOpened(documentId, SubjectBuffer.AsTextContainer()); } this.ContainedDocument = new ContainedDocument( componentModel.GetService<IThreadingContext>(), documentId, subjectBuffer: SubjectBuffer, dataBuffer: DataBuffer, bufferCoordinator, this.Workspace, project, componentModel, vbHelperFormattingRule); // TODO: Can contained documents be linked or shared? this.DataBuffer.Changed += OnDataBufferChanged; } private void OnDisconnect() { this.DataBuffer.Changed -= OnDataBufferChanged; if (this.Project != null) { this.Project.RemoveSourceTextContainer(SubjectBuffer.AsTextContainer()); } else { // It's possible the host of the workspace might have already removed the entire project if (Workspace.CurrentSolution.ContainsDocument(ContainedDocument.Id)) { Workspace.OnDocumentRemoved(ContainedDocument.Id); } } this.ContainedDocument.Dispose(); if (_bufferTagAggregator != null) { _bufferTagAggregator.Dispose(); } } private void OnDataBufferChanged(object sender, TextContentChangedEventArgs e) { // we don't actually care what has changed in primary buffer. we just want to re-analyze secondary buffer // when primary buffer has changed to update diagnostic positions. _diagnosticAnalyzerService.Reanalyze(this.Workspace, documentIds: SpecializedCollections.SingletonEnumerable(this.ContainedDocument.Id)); } } }
// 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; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { internal partial class ContainedLanguage { private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; private readonly IDiagnosticAnalyzerService _diagnosticAnalyzerService; private readonly Guid _languageServiceGuid; protected readonly Workspace Workspace; protected readonly IComponentModel ComponentModel; public VisualStudioProject? Project { get; } protected readonly ContainedDocument ContainedDocument; public IVsTextBufferCoordinator BufferCoordinator { get; protected set; } /// <summary> /// The subject (secondary) buffer that contains the C# or VB code. /// </summary> public ITextBuffer SubjectBuffer { get; } /// <summary> /// The underlying buffer that contains C# or VB code. NOTE: This is NOT the "document" buffer /// that is saved to disk. Instead it is the view that the user sees. The normal buffer graph /// in Venus includes 4 buffers: /// <code> /// SurfaceBuffer/Databuffer (projection) /// / | /// Subject Buffer (C#/VB projection) | /// | | /// Inert (generated) C#/VB Buffer Document (aspx) buffer /// </code> /// In normal circumstance, the Subject and Inert C# buffer are identical in content, and the /// Surface and Document are also identical. The Subject Buffer is the one that is part of the /// workspace, that most language operations deal with. The surface buffer is the one that the /// view is created over, and the Document buffer is the one that is saved to disk. /// </summary> public ITextBuffer DataBuffer { get; } // Set when a TextViewFIlter is set. We hold onto this to keep our TagSource objects alive even if Venus // disconnects the subject buffer from the view temporarily (which they do frequently). Otherwise, we have to // re-compute all of the tag data when they re-connect it, and this causes issues like classification // flickering. private readonly ITagAggregator<ITag> _bufferTagAggregator; [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal ContainedLanguage( IVsTextBufferCoordinator bufferCoordinator, IComponentModel componentModel, VisualStudioProject? project, IVsHierarchy hierarchy, uint itemid, VisualStudioProjectTracker? projectTrackerOpt, ProjectId projectId, Guid languageServiceGuid, AbstractFormattingRule? vbHelperFormattingRule = null) : this(bufferCoordinator, componentModel, projectTrackerOpt?.Workspace ?? componentModel.GetService<VisualStudioWorkspace>(), projectId, project, GetFilePathFromHierarchyAndItemId(hierarchy, itemid), languageServiceGuid, vbHelperFormattingRule) { } public static string GetFilePathFromHierarchyAndItemId(IVsHierarchy hierarchy, uint itemid) { if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemid, out var filePath))) { // we couldn't look up the document moniker from an hierarchy for an itemid. // Since we only use this moniker as a key, we could fall back to something else, like the document name. Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy."); if (!hierarchy.TryGetItemName(itemid, out filePath!)) { FatalError.ReportAndPropagate(new InvalidOperationException("Failed to get document moniker for a contained document")); } } return filePath; } internal ContainedLanguage( IVsTextBufferCoordinator bufferCoordinator, IComponentModel componentModel, Workspace workspace, ProjectId projectId, VisualStudioProject? project, string filePath, Guid languageServiceGuid, AbstractFormattingRule? vbHelperFormattingRule = null) { this.BufferCoordinator = bufferCoordinator; this.ComponentModel = componentModel; this.Project = project; _languageServiceGuid = languageServiceGuid; this.Workspace = workspace; _editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>(); _diagnosticAnalyzerService = componentModel.GetService<IDiagnosticAnalyzerService>(); // Get the ITextBuffer for the secondary buffer Marshal.ThrowExceptionForHR(bufferCoordinator.GetSecondaryBuffer(out var secondaryTextLines)); SubjectBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(secondaryTextLines)!; // Get the ITextBuffer for the primary buffer Marshal.ThrowExceptionForHR(bufferCoordinator.GetPrimaryBuffer(out var primaryTextLines)); DataBuffer = _editorAdaptersFactoryService.GetDataBuffer(primaryTextLines)!; // Create our tagger var bufferTagAggregatorFactory = ComponentModel.GetService<IBufferTagAggregatorFactoryService>(); _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator<ITag>(SubjectBuffer); DocumentId documentId; if (this.Project != null) { documentId = this.Project.AddSourceTextContainer( SubjectBuffer.AsTextContainer(), filePath, sourceCodeKind: SourceCodeKind.Regular, folders: default, designTimeOnly: true, documentServiceProvider: new ContainedDocument.DocumentServiceProvider(DataBuffer)); } else { documentId = DocumentId.CreateNewId(projectId, $"{nameof(ContainedDocument)}: {filePath}"); // We must jam a document into an existing workspace, which we'll assume is safe to do with OnDocumentAdded Workspace.OnDocumentAdded(DocumentInfo.Create(documentId, filePath, filePath: filePath)); Workspace.OnDocumentOpened(documentId, SubjectBuffer.AsTextContainer()); } this.ContainedDocument = new ContainedDocument( componentModel.GetService<IThreadingContext>(), documentId, subjectBuffer: SubjectBuffer, dataBuffer: DataBuffer, bufferCoordinator, this.Workspace, project, componentModel, vbHelperFormattingRule); // TODO: Can contained documents be linked or shared? this.DataBuffer.Changed += OnDataBufferChanged; } private void OnDisconnect() { this.DataBuffer.Changed -= OnDataBufferChanged; if (this.Project != null) { this.Project.RemoveSourceTextContainer(SubjectBuffer.AsTextContainer()); } else { // It's possible the host of the workspace might have already removed the entire project if (Workspace.CurrentSolution.ContainsDocument(ContainedDocument.Id)) { Workspace.OnDocumentRemoved(ContainedDocument.Id); } } this.ContainedDocument.Dispose(); if (_bufferTagAggregator != null) { _bufferTagAggregator.Dispose(); } } private void OnDataBufferChanged(object sender, TextContentChangedEventArgs e) { // we don't actually care what has changed in primary buffer. we just want to re-analyze secondary buffer // when primary buffer has changed to update diagnostic positions. _diagnosticAnalyzerService.Reanalyze(this.Workspace, documentIds: SpecializedCollections.SingletonEnumerable(this.ContainedDocument.Id)); } } }
-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/ILabelSymbol.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 a label in method body /// </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 ILabelSymbol : ISymbol { /// <summary> /// Gets the immediately containing <see cref="IMethodSymbol"/> of this <see cref="ILocalSymbol"/>. /// </summary> IMethodSymbol ContainingMethod { get; } } }
// 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 a label in method body /// </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 ILabelSymbol : ISymbol { /// <summary> /// Gets the immediately containing <see cref="IMethodSymbol"/> of this <see cref="ILocalSymbol"/>. /// </summary> IMethodSymbol ContainingMethod { get; } } }
-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/DiagnosticAnalyzer/CompilationCompletedEvent.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.Diagnostics { /// <summary> /// The last event placed into a compilation's event queue. /// </summary> internal sealed class CompilationCompletedEvent : CompilationEvent { public CompilationCompletedEvent(Compilation compilation) : base(compilation) { } public override string ToString() { return "CompilationCompletedEvent"; } } }
// 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.Diagnostics { /// <summary> /// The last event placed into a compilation's event queue. /// </summary> internal sealed class CompilationCompletedEvent : CompilationEvent { public CompilationCompletedEvent(Compilation compilation) : base(compilation) { } public override string ToString() { return "CompilationCompletedEvent"; } } }
-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/TypeWithModifiers.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 Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Structure TypeWithModifiers Implements IEquatable(Of TypeWithModifiers) Public ReadOnly Type As TypeSymbol Public ReadOnly CustomModifiers As ImmutableArray(Of CustomModifier) Public Sub New(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier)) Debug.Assert(type IsNot Nothing) Me.Type = type Me.CustomModifiers = customModifiers.NullToEmpty End Sub Public Sub New(type As TypeSymbol) Debug.Assert(type IsNot Nothing) Me.Type = type Me.CustomModifiers = ImmutableArray(Of CustomModifier).Empty End Sub <Obsolete("Use the strongly typed overload.", True)> Public Overrides Function Equals(obj As Object) As Boolean Return TypeOf obj Is TypeWithModifiers AndAlso Equals(DirectCast(obj, TypeWithModifiers)) End Function Public Overloads Function Equals(other As TypeWithModifiers) As Boolean Implements IEquatable(Of TypeWithModifiers).Equals Return Me.IsSameType(other, TypeCompareKind.ConsiderEverything) End Function Friend Function IsSameType(other As TypeWithModifiers, compareKind As TypeCompareKind) As Boolean If Not Me.Type.IsSameType(other.Type, compareKind) Then Return False End If If (compareKind And TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) = 0 Then Return If(Me.CustomModifiers.IsDefault, other.CustomModifiers.IsDefault, Not other.CustomModifiers.IsDefault AndAlso Me.CustomModifiers.SequenceEqual(other.CustomModifiers)) End If Return True End Function Shared Operator =(x As TypeWithModifiers, y As TypeWithModifiers) As Boolean Return x.Equals(y) End Operator Shared Operator <>(x As TypeWithModifiers, y As TypeWithModifiers) As Boolean Return Not x.Equals(y) End Operator Public Overrides Function GetHashCode() As Integer Return Hash.Combine(Me.Type, Hash.CombineValues(Me.CustomModifiers)) End Function Public Function [Is](other As TypeSymbol) As Boolean Return TypeSymbol.Equals(Me.Type, other, TypeCompareKind.ConsiderEverything) AndAlso Me.CustomModifiers.IsEmpty End Function <Obsolete("Use Is method.", True)> Public Overloads Function Equals(other As TypeSymbol) As Boolean Return Me.Is(other) End Function ''' <summary> ''' Extract type under assumption that there should be no custom modifiers. ''' The method asserts otherwise. ''' </summary> ''' <returns></returns> Public Function AsTypeSymbolOnly() As TypeSymbol Debug.Assert(Me.CustomModifiers.IsEmpty) Return Me.Type End Function Public Function InternalSubstituteTypeParameters(substitution As TypeSubstitution) As TypeWithModifiers Dim newCustomModifiers = If(substitution IsNot Nothing, substitution.SubstituteCustomModifiers(Me.CustomModifiers), Me.CustomModifiers) Dim newTypeWithModifiers As TypeWithModifiers = Me.Type.InternalSubstituteTypeParameters(substitution) If Not newTypeWithModifiers.Is(Me.Type) OrElse newCustomModifiers <> Me.CustomModifiers Then Return New TypeWithModifiers(newTypeWithModifiers.Type, newCustomModifiers.Concat(newTypeWithModifiers.CustomModifiers)) Else Return Me ' substitution had no effect on the type or modifiers End If End Function End Structure 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 Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Structure TypeWithModifiers Implements IEquatable(Of TypeWithModifiers) Public ReadOnly Type As TypeSymbol Public ReadOnly CustomModifiers As ImmutableArray(Of CustomModifier) Public Sub New(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier)) Debug.Assert(type IsNot Nothing) Me.Type = type Me.CustomModifiers = customModifiers.NullToEmpty End Sub Public Sub New(type As TypeSymbol) Debug.Assert(type IsNot Nothing) Me.Type = type Me.CustomModifiers = ImmutableArray(Of CustomModifier).Empty End Sub <Obsolete("Use the strongly typed overload.", True)> Public Overrides Function Equals(obj As Object) As Boolean Return TypeOf obj Is TypeWithModifiers AndAlso Equals(DirectCast(obj, TypeWithModifiers)) End Function Public Overloads Function Equals(other As TypeWithModifiers) As Boolean Implements IEquatable(Of TypeWithModifiers).Equals Return Me.IsSameType(other, TypeCompareKind.ConsiderEverything) End Function Friend Function IsSameType(other As TypeWithModifiers, compareKind As TypeCompareKind) As Boolean If Not Me.Type.IsSameType(other.Type, compareKind) Then Return False End If If (compareKind And TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) = 0 Then Return If(Me.CustomModifiers.IsDefault, other.CustomModifiers.IsDefault, Not other.CustomModifiers.IsDefault AndAlso Me.CustomModifiers.SequenceEqual(other.CustomModifiers)) End If Return True End Function Shared Operator =(x As TypeWithModifiers, y As TypeWithModifiers) As Boolean Return x.Equals(y) End Operator Shared Operator <>(x As TypeWithModifiers, y As TypeWithModifiers) As Boolean Return Not x.Equals(y) End Operator Public Overrides Function GetHashCode() As Integer Return Hash.Combine(Me.Type, Hash.CombineValues(Me.CustomModifiers)) End Function Public Function [Is](other As TypeSymbol) As Boolean Return TypeSymbol.Equals(Me.Type, other, TypeCompareKind.ConsiderEverything) AndAlso Me.CustomModifiers.IsEmpty End Function <Obsolete("Use Is method.", True)> Public Overloads Function Equals(other As TypeSymbol) As Boolean Return Me.Is(other) End Function ''' <summary> ''' Extract type under assumption that there should be no custom modifiers. ''' The method asserts otherwise. ''' </summary> ''' <returns></returns> Public Function AsTypeSymbolOnly() As TypeSymbol Debug.Assert(Me.CustomModifiers.IsEmpty) Return Me.Type End Function Public Function InternalSubstituteTypeParameters(substitution As TypeSubstitution) As TypeWithModifiers Dim newCustomModifiers = If(substitution IsNot Nothing, substitution.SubstituteCustomModifiers(Me.CustomModifiers), Me.CustomModifiers) Dim newTypeWithModifiers As TypeWithModifiers = Me.Type.InternalSubstituteTypeParameters(substitution) If Not newTypeWithModifiers.Is(Me.Type) OrElse newCustomModifiers <> Me.CustomModifiers Then Return New TypeWithModifiers(newTypeWithModifiers.Type, newCustomModifiers.Concat(newTypeWithModifiers.CustomModifiers)) Else Return Me ' substitution had no effect on the type or modifiers End If End Function End Structure 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/Structure/MetadataAsSource/DelegateDeclarationStructureTests.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.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining.MetadataAsSource Public Class DelegateDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of DelegateStatementSyntax) Protected Overrides ReadOnly Property WorkspaceKind As String Get Return CodeAnalysis.WorkspaceKind.MetadataAsSource End Get End Property Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New DelegateDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function NoCommentsOrAttributes() As Task Dim code = " Delegate Sub $$Bar() " Await VerifyNoBlockSpansAsync(code) End Function Public Delegate Sub Bar(x As Int16) <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithAttributes() As Task Dim code = " {|hint:{|textspan:<Goo> |}Delegate Sub $$Bar()|} " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAndAttributes() As Task Dim code = " {|hint:{|textspan:' Summary: ' This is a summary. <Goo> |}Delegate Sub $$Bar()|} " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAttributesAndModifiers() As Task Dim code = " {|hint:{|textspan:' Summary: ' This is a summary. <Goo> |}Public Delegate Sub $$Bar()|} " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) 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 Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining.MetadataAsSource Public Class DelegateDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of DelegateStatementSyntax) Protected Overrides ReadOnly Property WorkspaceKind As String Get Return CodeAnalysis.WorkspaceKind.MetadataAsSource End Get End Property Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New DelegateDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function NoCommentsOrAttributes() As Task Dim code = " Delegate Sub $$Bar() " Await VerifyNoBlockSpansAsync(code) End Function Public Delegate Sub Bar(x As Int16) <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithAttributes() As Task Dim code = " {|hint:{|textspan:<Goo> |}Delegate Sub $$Bar()|} " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAndAttributes() As Task Dim code = " {|hint:{|textspan:' Summary: ' This is a summary. <Goo> |}Delegate Sub $$Bar()|} " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAttributesAndModifiers() As Task Dim code = " {|hint:{|textspan:' Summary: ' This is a summary. <Goo> |}Public Delegate Sub $$Bar()|} " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) 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/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentProjectsFinder.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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { /// <summary> /// Provides helper methods for finding dependent projects across a solution that a given symbol can be referenced within. /// </summary> internal static partial class DependentProjectsFinder { public static async Task<ImmutableArray<Project>> GetDependentProjectsAsync( Solution solution, ISymbol symbol, IImmutableSet<Project>? projects, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Namespace) { // namespaces are visible in all projects. return projects != null ? projects.ToImmutableArray() : solution.Projects.ToImmutableArray(); } else { var dependentProjects = await GetDependentProjectsWorkerAsync(solution, symbol, cancellationToken).ConfigureAwait(false); return projects != null ? dependentProjects.WhereAsArray(projects.Contains) : dependentProjects; } } /// <summary> /// This method computes the dependent projects that need to be searched for references of the given <paramref name="symbol"/>. /// This computation depends on the given symbol's visibility: /// 1) Public: Dependent projects include the symbol definition project and all the referencing projects. /// 2) Internal: Dependent projects include the symbol definition project and all the referencing projects that have internals access to the definition project. /// 3) Private: Dependent projects include the symbol definition project and all the referencing submission projects (which are special and can reference private fields of the previous submission). /// /// We perform this computation in two stages: /// 1) Compute all the dependent projects (submission + non-submission) and their InternalsVisibleTo semantics to the definition project. /// 2) Filter the above computed dependent projects based on symbol visibility. /// Dependent projects computed in stage (1) are cached to avoid recomputation. /// </summary> private static async Task<ImmutableArray<Project>> GetDependentProjectsWorkerAsync( Solution solution, ISymbol symbol, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var symbolOrigination = GetSymbolOrigination(solution, symbol, cancellationToken); // If we can't find where the symbol came from, we can't determine what projects to search for references to it. if (symbolOrigination.assembly == null) return ImmutableArray<Project>.Empty; // 1) Compute all the dependent projects (submission + non-submission) and their InternalsVisibleTo semantics to the definition project. var symbolVisibility = symbol.GetResultantVisibility(); var dependentProjects = await ComputeDependentProjectsAsync( solution, symbolOrigination, symbolVisibility, cancellationToken).ConfigureAwait(false); // 2) Filter the above computed dependent projects based on symbol visibility. var filteredProjects = symbolVisibility == SymbolVisibility.Internal ? dependentProjects.WhereAsArray(dp => dp.hasInternalsAccess) : dependentProjects; return filteredProjects.SelectAsArray(t => t.project); } /// <summary> /// Returns a pair of data bout where <paramref name="symbol"/> originates from. It's <see /// cref="IAssemblySymbol"/> for both source and metadata symbols, and an optional <see cref="Project"/> if this /// was a symbol from source. /// </summary> private static (IAssemblySymbol assembly, Project? sourceProject) GetSymbolOrigination( Solution solution, ISymbol symbol, CancellationToken cancellationToken) { var assembly = symbol.OriginalDefinition.ContainingAssembly; return assembly == null ? default : (assembly, solution.GetProject(assembly, cancellationToken)); } private static async Task<ImmutableArray<(Project project, bool hasInternalsAccess)>> ComputeDependentProjectsAsync( Solution solution, (IAssemblySymbol assembly, Project? sourceProject) symbolOrigination, SymbolVisibility visibility, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var dependentProjects = new HashSet<(Project, bool hasInternalsAccess)>(); // If a symbol was defined in source, then it is always visible to the project it // was defined in. if (symbolOrigination.sourceProject != null) dependentProjects.Add((symbolOrigination.sourceProject, hasInternalsAccess: true)); // If it's not private, then we need to find possible references. if (visibility != SymbolVisibility.Private) AddNonSubmissionDependentProjects(solution, symbolOrigination, dependentProjects, cancellationToken); // submission projects are special here. The fields generated inside the Script object is private, but // further submissions can bind to them. await AddSubmissionDependentProjectsAsync(solution, symbolOrigination.sourceProject, dependentProjects, cancellationToken).ConfigureAwait(false); return dependentProjects.ToImmutableArray(); } private static async Task AddSubmissionDependentProjectsAsync( Solution solution, Project? sourceProject, HashSet<(Project project, bool hasInternalsAccess)> dependentProjects, CancellationToken cancellationToken) { if (sourceProject?.IsSubmission != true) return; var projectIdsToReferencingSubmissionIds = new Dictionary<ProjectId, List<ProjectId>>(); // search only submission project foreach (var projectId in solution.ProjectIds) { var project = solution.GetRequiredProject(projectId); if (project.IsSubmission && project.SupportsCompilation) { cancellationToken.ThrowIfCancellationRequested(); // If we are referencing another project, store the link in the other direction // so we walk across it later var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var previous = compilation.ScriptCompilationInfo?.PreviousScriptCompilation; if (previous != null) { var referencedProject = solution.GetProject(previous.Assembly, cancellationToken); if (referencedProject != null) { if (!projectIdsToReferencingSubmissionIds.TryGetValue(referencedProject.Id, out var referencingSubmissions)) { referencingSubmissions = new List<ProjectId>(); projectIdsToReferencingSubmissionIds.Add(referencedProject.Id, referencingSubmissions); } referencingSubmissions.Add(project.Id); } } } } // Submission compilations are special. If we have submissions 0, 1 and 2 chained in // the natural way, and we have a symbol in submission 0, we need to search both 1 // and 2, even though 2 doesn't have a direct reference to 1. Hence we need to take // our current set of projects and find the transitive closure over backwards // submission previous references. var projectIdsToProcess = new Stack<ProjectId>(dependentProjects.Select(dp => dp.project.Id)); while (projectIdsToProcess.Count > 0) { var toProcess = projectIdsToProcess.Pop(); if (projectIdsToReferencingSubmissionIds.TryGetValue(toProcess, out var submissionIds)) { foreach (var pId in submissionIds) { if (!dependentProjects.Any(dp => dp.project.Id == pId)) { dependentProjects.Add((solution.GetRequiredProject(pId), hasInternalsAccess: true)); projectIdsToProcess.Push(pId); } } } } } private static bool IsInternalsVisibleToAttribute(AttributeData attr) { var attrType = attr.AttributeClass; return attrType?.Name == nameof(InternalsVisibleToAttribute) && attrType.ContainingNamespace?.Name == nameof(System.Runtime.CompilerServices) && attrType.ContainingNamespace.ContainingNamespace?.Name == nameof(System.Runtime) && attrType.ContainingNamespace.ContainingNamespace.ContainingNamespace?.Name == nameof(System) && attrType.ContainingNamespace.ContainingNamespace.ContainingNamespace.ContainingNamespace?.IsGlobalNamespace == true; } private static void AddNonSubmissionDependentProjects( Solution solution, (IAssemblySymbol assembly, Project? sourceProject) symbolOrigination, HashSet<(Project project, bool hasInternalsAccess)> dependentProjects, CancellationToken cancellationToken) { if (symbolOrigination.sourceProject?.IsSubmission == true) return; // Set of assembly names that `assembly` has IVT to. Computed on demand once needed. HashSet<string>? internalsVisibleToSet = null; foreach (var project in solution.Projects) { if (!project.SupportsCompilation || !HasReferenceTo(symbolOrigination, project, cancellationToken)) { continue; } // Ok, we have some project that at least references this assembly. Add it to the result, keeping track // if it can see internals or not as well. internalsVisibleToSet ??= GetInternalsVisibleToSet(symbolOrigination.assembly); var hasInternalsAccess = internalsVisibleToSet.Contains(project.AssemblyName); dependentProjects.Add((project, hasInternalsAccess)); } } private static HashSet<string> GetInternalsVisibleToSet(IAssemblySymbol assembly) { var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var attr in assembly.GetAttributes().Where(IsInternalsVisibleToAttribute)) { var typeNameConstant = attr.ConstructorArguments.FirstOrDefault(); if (typeNameConstant.Type == null || typeNameConstant.Type.SpecialType != SpecialType.System_String || !(typeNameConstant.Value is string value)) { continue; } var commaIndex = value.IndexOf(','); var assemblyName = commaIndex >= 0 ? value.Substring(0, commaIndex).Trim() : value; set.Add(assemblyName); } return set; } private static bool HasReferenceTo( (IAssemblySymbol assembly, Project? sourceProject) symbolOrigination, Project project, CancellationToken cancellationToken) { Contract.ThrowIfNull(symbolOrigination.assembly); Contract.ThrowIfNull(project); Contract.ThrowIfFalse(project.SupportsCompilation); // If our symbol was from a project, then just check if this current project has a direct reference to it. if (symbolOrigination.sourceProject != null) return project.ProjectReferences.Any(p => p.ProjectId == symbolOrigination.sourceProject.Id); // Otherwise, if the symbol is from metadata, see if the project's compilation references that metadata assembly. return HasReferenceToAssembly(project, symbolOrigination.assembly.Name, cancellationToken); } private static bool HasReferenceToAssembly(Project project, string assemblyName, CancellationToken cancellationToken) { Contract.ThrowIfFalse(project.SupportsCompilation); if (!project.TryGetCompilation(out var compilation)) { // WORKAROUND: // perf check metadata reference using newly created empty compilation with only metadata references. compilation = project.LanguageServices.CompilationFactory!.CreateCompilation( project.AssemblyName, project.CompilationOptions!); compilation = compilation.AddReferences(project.MetadataReferences); } foreach (var reference in project.MetadataReferences) { cancellationToken.ThrowIfCancellationRequested(); if (compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol symbol && symbol.Name == assemblyName) { return true; } } 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { /// <summary> /// Provides helper methods for finding dependent projects across a solution that a given symbol can be referenced within. /// </summary> internal static partial class DependentProjectsFinder { public static async Task<ImmutableArray<Project>> GetDependentProjectsAsync( Solution solution, ISymbol symbol, IImmutableSet<Project>? projects, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Namespace) { // namespaces are visible in all projects. return projects != null ? projects.ToImmutableArray() : solution.Projects.ToImmutableArray(); } else { var dependentProjects = await GetDependentProjectsWorkerAsync(solution, symbol, cancellationToken).ConfigureAwait(false); return projects != null ? dependentProjects.WhereAsArray(projects.Contains) : dependentProjects; } } /// <summary> /// This method computes the dependent projects that need to be searched for references of the given <paramref name="symbol"/>. /// This computation depends on the given symbol's visibility: /// 1) Public: Dependent projects include the symbol definition project and all the referencing projects. /// 2) Internal: Dependent projects include the symbol definition project and all the referencing projects that have internals access to the definition project. /// 3) Private: Dependent projects include the symbol definition project and all the referencing submission projects (which are special and can reference private fields of the previous submission). /// /// We perform this computation in two stages: /// 1) Compute all the dependent projects (submission + non-submission) and their InternalsVisibleTo semantics to the definition project. /// 2) Filter the above computed dependent projects based on symbol visibility. /// Dependent projects computed in stage (1) are cached to avoid recomputation. /// </summary> private static async Task<ImmutableArray<Project>> GetDependentProjectsWorkerAsync( Solution solution, ISymbol symbol, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var symbolOrigination = GetSymbolOrigination(solution, symbol, cancellationToken); // If we can't find where the symbol came from, we can't determine what projects to search for references to it. if (symbolOrigination.assembly == null) return ImmutableArray<Project>.Empty; // 1) Compute all the dependent projects (submission + non-submission) and their InternalsVisibleTo semantics to the definition project. var symbolVisibility = symbol.GetResultantVisibility(); var dependentProjects = await ComputeDependentProjectsAsync( solution, symbolOrigination, symbolVisibility, cancellationToken).ConfigureAwait(false); // 2) Filter the above computed dependent projects based on symbol visibility. var filteredProjects = symbolVisibility == SymbolVisibility.Internal ? dependentProjects.WhereAsArray(dp => dp.hasInternalsAccess) : dependentProjects; return filteredProjects.SelectAsArray(t => t.project); } /// <summary> /// Returns a pair of data bout where <paramref name="symbol"/> originates from. It's <see /// cref="IAssemblySymbol"/> for both source and metadata symbols, and an optional <see cref="Project"/> if this /// was a symbol from source. /// </summary> private static (IAssemblySymbol assembly, Project? sourceProject) GetSymbolOrigination( Solution solution, ISymbol symbol, CancellationToken cancellationToken) { var assembly = symbol.OriginalDefinition.ContainingAssembly; return assembly == null ? default : (assembly, solution.GetProject(assembly, cancellationToken)); } private static async Task<ImmutableArray<(Project project, bool hasInternalsAccess)>> ComputeDependentProjectsAsync( Solution solution, (IAssemblySymbol assembly, Project? sourceProject) symbolOrigination, SymbolVisibility visibility, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var dependentProjects = new HashSet<(Project, bool hasInternalsAccess)>(); // If a symbol was defined in source, then it is always visible to the project it // was defined in. if (symbolOrigination.sourceProject != null) dependentProjects.Add((symbolOrigination.sourceProject, hasInternalsAccess: true)); // If it's not private, then we need to find possible references. if (visibility != SymbolVisibility.Private) AddNonSubmissionDependentProjects(solution, symbolOrigination, dependentProjects, cancellationToken); // submission projects are special here. The fields generated inside the Script object is private, but // further submissions can bind to them. await AddSubmissionDependentProjectsAsync(solution, symbolOrigination.sourceProject, dependentProjects, cancellationToken).ConfigureAwait(false); return dependentProjects.ToImmutableArray(); } private static async Task AddSubmissionDependentProjectsAsync( Solution solution, Project? sourceProject, HashSet<(Project project, bool hasInternalsAccess)> dependentProjects, CancellationToken cancellationToken) { if (sourceProject?.IsSubmission != true) return; var projectIdsToReferencingSubmissionIds = new Dictionary<ProjectId, List<ProjectId>>(); // search only submission project foreach (var projectId in solution.ProjectIds) { var project = solution.GetRequiredProject(projectId); if (project.IsSubmission && project.SupportsCompilation) { cancellationToken.ThrowIfCancellationRequested(); // If we are referencing another project, store the link in the other direction // so we walk across it later var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var previous = compilation.ScriptCompilationInfo?.PreviousScriptCompilation; if (previous != null) { var referencedProject = solution.GetProject(previous.Assembly, cancellationToken); if (referencedProject != null) { if (!projectIdsToReferencingSubmissionIds.TryGetValue(referencedProject.Id, out var referencingSubmissions)) { referencingSubmissions = new List<ProjectId>(); projectIdsToReferencingSubmissionIds.Add(referencedProject.Id, referencingSubmissions); } referencingSubmissions.Add(project.Id); } } } } // Submission compilations are special. If we have submissions 0, 1 and 2 chained in // the natural way, and we have a symbol in submission 0, we need to search both 1 // and 2, even though 2 doesn't have a direct reference to 1. Hence we need to take // our current set of projects and find the transitive closure over backwards // submission previous references. var projectIdsToProcess = new Stack<ProjectId>(dependentProjects.Select(dp => dp.project.Id)); while (projectIdsToProcess.Count > 0) { var toProcess = projectIdsToProcess.Pop(); if (projectIdsToReferencingSubmissionIds.TryGetValue(toProcess, out var submissionIds)) { foreach (var pId in submissionIds) { if (!dependentProjects.Any(dp => dp.project.Id == pId)) { dependentProjects.Add((solution.GetRequiredProject(pId), hasInternalsAccess: true)); projectIdsToProcess.Push(pId); } } } } } private static bool IsInternalsVisibleToAttribute(AttributeData attr) { var attrType = attr.AttributeClass; return attrType?.Name == nameof(InternalsVisibleToAttribute) && attrType.ContainingNamespace?.Name == nameof(System.Runtime.CompilerServices) && attrType.ContainingNamespace.ContainingNamespace?.Name == nameof(System.Runtime) && attrType.ContainingNamespace.ContainingNamespace.ContainingNamespace?.Name == nameof(System) && attrType.ContainingNamespace.ContainingNamespace.ContainingNamespace.ContainingNamespace?.IsGlobalNamespace == true; } private static void AddNonSubmissionDependentProjects( Solution solution, (IAssemblySymbol assembly, Project? sourceProject) symbolOrigination, HashSet<(Project project, bool hasInternalsAccess)> dependentProjects, CancellationToken cancellationToken) { if (symbolOrigination.sourceProject?.IsSubmission == true) return; // Set of assembly names that `assembly` has IVT to. Computed on demand once needed. HashSet<string>? internalsVisibleToSet = null; foreach (var project in solution.Projects) { if (!project.SupportsCompilation || !HasReferenceTo(symbolOrigination, project, cancellationToken)) { continue; } // Ok, we have some project that at least references this assembly. Add it to the result, keeping track // if it can see internals or not as well. internalsVisibleToSet ??= GetInternalsVisibleToSet(symbolOrigination.assembly); var hasInternalsAccess = internalsVisibleToSet.Contains(project.AssemblyName); dependentProjects.Add((project, hasInternalsAccess)); } } private static HashSet<string> GetInternalsVisibleToSet(IAssemblySymbol assembly) { var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var attr in assembly.GetAttributes().Where(IsInternalsVisibleToAttribute)) { var typeNameConstant = attr.ConstructorArguments.FirstOrDefault(); if (typeNameConstant.Type == null || typeNameConstant.Type.SpecialType != SpecialType.System_String || !(typeNameConstant.Value is string value)) { continue; } var commaIndex = value.IndexOf(','); var assemblyName = commaIndex >= 0 ? value.Substring(0, commaIndex).Trim() : value; set.Add(assemblyName); } return set; } private static bool HasReferenceTo( (IAssemblySymbol assembly, Project? sourceProject) symbolOrigination, Project project, CancellationToken cancellationToken) { Contract.ThrowIfNull(symbolOrigination.assembly); Contract.ThrowIfNull(project); Contract.ThrowIfFalse(project.SupportsCompilation); // If our symbol was from a project, then just check if this current project has a direct reference to it. if (symbolOrigination.sourceProject != null) return project.ProjectReferences.Any(p => p.ProjectId == symbolOrigination.sourceProject.Id); // Otherwise, if the symbol is from metadata, see if the project's compilation references that metadata assembly. return HasReferenceToAssembly(project, symbolOrigination.assembly.Name, cancellationToken); } private static bool HasReferenceToAssembly(Project project, string assemblyName, CancellationToken cancellationToken) { Contract.ThrowIfFalse(project.SupportsCompilation); if (!project.TryGetCompilation(out var compilation)) { // WORKAROUND: // perf check metadata reference using newly created empty compilation with only metadata references. compilation = project.LanguageServices.CompilationFactory!.CreateCompilation( project.AssemblyName, project.CompilationOptions!); compilation = compilation.AddReferences(project.MetadataReferences); } foreach (var reference in project.MetadataReferences) { cancellationToken.ThrowIfCancellationRequested(); if (compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol symbol && symbol.Name == assemblyName) { return true; } } 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/VisualBasic/Highlighting/KeywordHighlighters/XmlCommentHighlighter.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.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class XmlCommentHighlighter Inherits AbstractKeywordHighlighter(Of XmlCommentSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub addHighlights(xmlComment As XmlCommentSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken) With xmlComment If Not .ContainsDiagnostics AndAlso Not .HasAncestor(Of DocumentationCommentTriviaSyntax)() Then highlights.Add(.LessThanExclamationMinusMinusToken.Span) highlights.Add(.MinusMinusGreaterThanToken.Span) End If End With 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.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class XmlCommentHighlighter Inherits AbstractKeywordHighlighter(Of XmlCommentSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub addHighlights(xmlComment As XmlCommentSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken) With xmlComment If Not .ContainsDiagnostics AndAlso Not .HasAncestor(Of DocumentationCommentTriviaSyntax)() Then highlights.Add(.LessThanExclamationMinusMinusToken.Span) highlights.Add(.MinusMinusGreaterThanToken.Span) End If End With 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/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.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.Generic Imports System.Collections.Immutable Imports System.Collections.ObjectModel Imports System.Globalization Imports System.Reflection Imports System.Reflection.Metadata Imports System.Linq Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Imports TypeAttributes = System.Reflection.TypeAttributes Imports FieldAttributes = System.Reflection.FieldAttributes Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ''' <summary> ''' The class to represent all types imported from a PE/module. ''' </summary> ''' <remarks></remarks> Friend Class PENamedTypeSymbol Inherits InstanceTypeSymbol Private ReadOnly _container As NamespaceOrTypeSymbol #Region "Metadata" Private ReadOnly _handle As TypeDefinitionHandle Private ReadOnly _genericParameterHandles As GenericParameterHandleCollection Private ReadOnly _name As String Private ReadOnly _flags As TypeAttributes Private ReadOnly _arity As UShort Private ReadOnly _mangleName As Boolean ' CONSIDER: combine with flags #End Region ''' <summary> ''' A map of types immediately contained within this type ''' grouped by their name (case-insensitively). ''' </summary> Private _lazyNestedTypes As Dictionary(Of String, ImmutableArray(Of PENamedTypeSymbol)) ''' <summary> ''' A set of all the names of the members in this type. ''' </summary> Private _lazyMemberNames As ICollection(Of String) ''' <summary> ''' A map of members immediately contained within this type ''' grouped by their name (case-insensitively). ''' </summary> ''' <remarks></remarks> Private _lazyMembers As Dictionary(Of String, ImmutableArray(Of Symbol)) Private _lazyTypeParameters As ImmutableArray(Of TypeParameterSymbol) Private _lazyEnumUnderlyingType As NamedTypeSymbol Private _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData) Private _lazyConditionalAttributeSymbols As ImmutableArray(Of String) Private _lazyAttributeUsageInfo As AttributeUsageInfo = AttributeUsageInfo.Null Private _lazyCoClassType As TypeSymbol = ErrorTypeSymbol.UnknownResultType ''' <summary> ''' Lazily initialized by TypeKind property. ''' Using Integer type to make sure read/write operations are atomic. ''' </summary> ''' <remarks></remarks> Private _lazyTypeKind As Integer Private _lazyDocComment As Tuple(Of CultureInfo, String) Private _lazyDefaultPropertyName As String Private _lazyCachedUseSiteInfo As CachedUseSiteInfo(Of AssemblySymbol) = CachedUseSiteInfo(Of AssemblySymbol).Uninitialized ' Indicates unknown state. Private _lazyMightContainExtensionMethods As Byte = ThreeState.Unknown Private _lazyHasCodeAnalysisEmbeddedAttribute As Integer = ThreeState.Unknown Private _lazyHasVisualBasicEmbeddedAttribute As Integer = ThreeState.Unknown Private _lazyObsoleteAttributeData As ObsoleteAttributeData = ObsoleteAttributeData.Uninitialized Private _lazyIsExtensibleInterface As ThreeState = ThreeState.Unknown Friend Sub New( moduleSymbol As PEModuleSymbol, containingNamespace As PENamespaceSymbol, handle As TypeDefinitionHandle ) Me.New(moduleSymbol, containingNamespace, 0, handle) End Sub Friend Sub New( moduleSymbol As PEModuleSymbol, containingType As PENamedTypeSymbol, handle As TypeDefinitionHandle ) Me.New(moduleSymbol, containingType, CUShort(containingType.MetadataArity), handle) End Sub Private Sub New( moduleSymbol As PEModuleSymbol, container As NamespaceOrTypeSymbol, containerMetadataArity As UShort, handle As TypeDefinitionHandle ) Debug.Assert(Not handle.IsNil) Debug.Assert(container IsNot Nothing) _handle = handle _container = container Dim makeBad As Boolean = False Dim name As String Try name = moduleSymbol.Module.GetTypeDefNameOrThrow(handle) Catch mrEx As BadImageFormatException name = String.Empty makeBad = True End Try Try _flags = moduleSymbol.Module.GetTypeDefFlagsOrThrow(handle) Catch mrEx As BadImageFormatException makeBad = True End Try Dim metadataArity As Integer Try _genericParameterHandles = moduleSymbol.Module.GetTypeDefGenericParamsOrThrow(handle) metadataArity = _genericParameterHandles.Count Catch mrEx As BadImageFormatException _genericParameterHandles = Nothing metadataArity = 0 makeBad = True End Try ' Figure out arity from the language point of view If metadataArity > containerMetadataArity Then _arity = CType(metadataArity - containerMetadataArity, UShort) End If If _arity = 0 Then _lazyTypeParameters = ImmutableArray(Of TypeParameterSymbol).Empty _name = name _mangleName = False Else ' Unmangle name for a generic type. _name = MetadataHelpers.UnmangleMetadataNameForArity(name, _arity) _mangleName = (_name IsNot name) End If If makeBad OrElse metadataArity < containerMetadataArity Then _lazyCachedUseSiteInfo.Initialize(ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedType1, Me)) End If Debug.Assert(Not _mangleName OrElse _name.Length < name.Length) End Sub Friend ReadOnly Property ContainingPEModule As PEModuleSymbol Get Dim s As Symbol = _container While s.Kind <> SymbolKind.Namespace s = s.ContainingSymbol End While Return DirectCast(s, PENamespaceSymbol).ContainingPEModule End Get End Property Public Overrides ReadOnly Property ContainingModule As ModuleSymbol Get Return ContainingPEModule End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return _arity End Get End Property Friend Overrides ReadOnly Property MangleName As Boolean Get Return _mangleName End Get End Property Friend Overrides ReadOnly Property Layout As TypeLayout Get Return Me.ContainingPEModule.Module.GetTypeLayout(_handle) End Get End Property Friend Overrides ReadOnly Property MarshallingCharSet As CharSet Get Dim result As CharSet = _flags.ToCharSet() If result = 0 Then Return CharSet.Ansi End If Return result End Get End Property Public Overrides ReadOnly Property IsSerializable As Boolean Get Return (_flags And TypeAttributes.Serializable) <> 0 End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return (_flags And TypeAttributes.SpecialName) <> 0 End Get End Property Friend ReadOnly Property MetadataArity As Integer Get Return _genericParameterHandles.Count End Get End Property Friend ReadOnly Property Handle As TypeDefinitionHandle Get Return _handle End Get End Property Friend Overrides Function GetInterfacesToEmit() As IEnumerable(Of NamedTypeSymbol) Return InterfacesNoUseSiteDiagnostics End Function Friend Overrides Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol If (Me._flags And TypeAttributes.Interface) = 0 Then Dim moduleSymbol As PEModuleSymbol = Me.ContainingPEModule Try Dim token As EntityHandle = moduleSymbol.Module.GetBaseTypeOfTypeOrThrow(Me._handle) If Not token.IsNil Then Dim decodedType = New MetadataDecoder(moduleSymbol, Me).GetTypeOfToken(token) Return DirectCast(TupleTypeDecoder.DecodeTupleTypesIfApplicable(decodedType, _handle, moduleSymbol), NamedTypeSymbol) End If Catch mrEx As BadImageFormatException Return New UnsupportedMetadataTypeSymbol(mrEx) End Try End If Return Nothing End Function Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Try Dim moduleSymbol As PEModuleSymbol = Me.ContainingPEModule Dim interfaceImpls = moduleSymbol.Module.GetInterfaceImplementationsOrThrow(Me._handle) If interfaceImpls.Count = 0 Then Return ImmutableArray(Of NamedTypeSymbol).Empty End If Dim symbols As NamedTypeSymbol() = New NamedTypeSymbol(interfaceImpls.Count - 1) {} Dim tokenDecoder As New MetadataDecoder(moduleSymbol, Me) Dim i = 0 For Each interfaceImpl In interfaceImpls Dim interfaceHandle As EntityHandle = moduleSymbol.Module.MetadataReader.GetInterfaceImplementation(interfaceImpl).Interface Dim typeSymbol As TypeSymbol = tokenDecoder.GetTypeOfToken(interfaceHandle) typeSymbol = DirectCast(TupleTypeDecoder.DecodeTupleTypesIfApplicable(typeSymbol, interfaceImpl, moduleSymbol), NamedTypeSymbol) 'TODO: how to pass reason to unsupported Dim namedTypeSymbol As NamedTypeSymbol = TryCast(typeSymbol, NamedTypeSymbol) symbols(i) = If(namedTypeSymbol IsNot Nothing, namedTypeSymbol, New UnsupportedMetadataTypeSymbol()) ' "interface tmpList contains a bad type" i = i + 1 Next Return symbols.AsImmutableOrNull Catch mrEx As BadImageFormatException Return ImmutableArray.Create(Of NamedTypeSymbol)(New UnsupportedMetadataTypeSymbol(mrEx)) End Try End Function Private Shared Function CyclicInheritanceError(diag As DiagnosticInfo) As ErrorTypeSymbol Return New ExtendedErrorTypeSymbol(diag, True) End Function Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Dim diag = BaseTypeAnalysis.GetDependencyDiagnosticsForImportedClass(Me) If diag IsNot Nothing Then Return CyclicInheritanceError(diag) End If Return GetDeclaredBase(Nothing) End Function Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Dim declaredInterfaces As ImmutableArray(Of NamedTypeSymbol) = GetDeclaredInterfacesNoUseSiteDiagnostics(Nothing) If (Not Me.IsInterface) Then ' only interfaces needs to check for inheritance cycles via interfaces. Return declaredInterfaces End If Return (From t In declaredInterfaces Let diag = BaseTypeAnalysis.GetDependencyDiagnosticsForImportedBaseInterface(Me, t) Select If(diag Is Nothing, t, CyclicInheritanceError(diag))).AsImmutable End Function Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return TryCast(_container, NamedTypeSymbol) End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Dim access As Accessibility = Accessibility.Private Select Case _flags And TypeAttributes.VisibilityMask Case TypeAttributes.NestedAssembly access = Accessibility.Friend Case TypeAttributes.NestedFamORAssem access = Accessibility.ProtectedOrFriend Case TypeAttributes.NestedFamANDAssem access = Accessibility.ProtectedAndFriend Case TypeAttributes.NestedPrivate access = Accessibility.Private Case TypeAttributes.Public, TypeAttributes.NestedPublic access = Accessibility.Public Case TypeAttributes.NestedFamily access = Accessibility.Protected Case TypeAttributes.NotPublic access = Accessibility.Friend Case Else Debug.Assert(False, "Unexpected!!!") End Select Return access End Get End Property Public Overrides ReadOnly Property EnumUnderlyingType As NamedTypeSymbol Get If _lazyEnumUnderlyingType Is Nothing AndAlso TypeKind = TypeKind.Enum Then ' From §8.5.2 ' An enum is considerably more restricted than a true type, as ' follows: ' • It shall have exactly one instance field, and the type of that field defines the underlying type of ' the enumeration. ' • It shall not have any static fields unless they are literal. (see §8.6.1.2) ' The underlying type shall be a built-in integer type. Enums shall derive from System.Enum, hence they are ' value types. Like all value types, they shall be sealed (see §8.9.9). Dim underlyingType As NamedTypeSymbol = Nothing For Each member In GetMembers() If (Not member.IsShared AndAlso member.Kind = SymbolKind.Field) Then Dim type = DirectCast(member, FieldSymbol).Type If (type.SpecialType.IsClrInteger()) Then If (underlyingType Is Nothing) Then underlyingType = DirectCast(type, NamedTypeSymbol) Else underlyingType = New UnsupportedMetadataTypeSymbol() Exit For End If End If End If Next Interlocked.CompareExchange(_lazyEnumUnderlyingType, If(underlyingType, New UnsupportedMetadataTypeSymbol()), Nothing) End If Return _lazyEnumUnderlyingType End Get End Property Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) If _lazyCustomAttributes.IsDefault Then If (_lazyTypeKind = TypeKind.Unknown AndAlso ((_flags And TypeAttributes.Interface) <> 0 OrElse Me.Arity <> 0 OrElse Me.ContainingType IsNot Nothing)) OrElse Me.TypeKind <> TypeKind.Module Then ContainingPEModule.LoadCustomAttributes(_handle, _lazyCustomAttributes) Else Dim stdModuleAttribute As CustomAttributeHandle Dim attributes = ContainingPEModule.GetCustomAttributesForToken( _handle, stdModuleAttribute, filterOut1:=AttributeDescription.StandardModuleAttribute) Debug.Assert(Not stdModuleAttribute.IsNil) ImmutableInterlocked.InterlockedInitialize(_lazyCustomAttributes, attributes) End If End If Return _lazyCustomAttributes End Function Friend Overrides Iterator Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData) For Each attribute In GetAttributes() Yield attribute Next If Me.TypeKind = TypeKind.Module Then Yield New PEAttributeData(ContainingPEModule, ContainingPEModule.Module.GetAttributeHandle(Me._handle, AttributeDescription.StandardModuleAttribute)) End If End Function Public Overrides ReadOnly Property MemberNames As IEnumerable(Of String) Get EnsureNonTypeMemberNamesAreLoaded() Return _lazyMemberNames End Get End Property Private Sub EnsureNonTypeMemberNamesAreLoaded() If _lazyMemberNames Is Nothing Then Dim peModule = ContainingPEModule.Module Dim names = New HashSet(Of String)() Try For Each methodDef In peModule.GetMethodsOfTypeOrThrow(_handle) Try names.Add(peModule.GetMethodDefNameOrThrow(methodDef)) Catch mrEx As BadImageFormatException End Try Next Catch mrEx As BadImageFormatException End Try Try For Each propertyDef In peModule.GetPropertiesOfTypeOrThrow(_handle) Try names.Add(peModule.GetPropertyDefNameOrThrow(propertyDef)) Catch mrEx As BadImageFormatException End Try Next Catch mrEx As BadImageFormatException End Try Try For Each eventDef In peModule.GetEventsOfTypeOrThrow(_handle) Try names.Add(peModule.GetEventDefNameOrThrow(eventDef)) Catch mrEx As BadImageFormatException End Try Next Catch mrEx As BadImageFormatException End Try Try For Each fieldDef In peModule.GetFieldsOfTypeOrThrow(_handle) Try names.Add(peModule.GetFieldDefNameOrThrow(fieldDef)) Catch mrEx As BadImageFormatException End Try Next Catch mrEx As BadImageFormatException End Try Interlocked.CompareExchange(Of ICollection(Of String))( _lazyMemberNames, SpecializedCollections.ReadOnlySet(names), Nothing) End If End Sub Public Overloads Overrides Function GetMembers() As ImmutableArray(Of Symbol) EnsureNestedTypesAreLoaded() EnsureNonTypeMembersAreLoaded() Return _lazyMembers.Flatten(DeclarationOrderSymbolComparer.Instance) End Function Friend Overrides Function GetMembersUnordered() As ImmutableArray(Of Symbol) EnsureNestedTypesAreLoaded() EnsureNonTypeMembersAreLoaded() Return _lazyMembers.Flatten().ConditionallyDeOrder() End Function Friend Overrides Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol) ' If there are any fields, they are at the very beginning. Return GetMembers(Of FieldSymbol)(GetMembers(), SymbolKind.Field, offset:=0) End Function Friend Overrides Iterator Function GetMethodsToEmit() As IEnumerable(Of MethodSymbol) Dim members = GetMembers() ' Get to methods. Dim index = GetIndexOfFirstMember(members, SymbolKind.Method) If Not Me.IsInterfaceType() Then While index < members.Length Dim member = members(index) If member.Kind <> SymbolKind.Method Then Exit While End If Dim method = DirectCast(member, MethodSymbol) ' Don't emit the default value type constructor - the runtime handles that If Not method.IsDefaultValueTypeConstructor() Then Yield method End If index += 1 End While Else ' We do not create symbols for v-table gap methods, let's figure out where the gaps go. If index >= members.Length OrElse members(index).Kind <> SymbolKind.Method Then ' We didn't import any methods, it is Ok to return an empty set. Return End If Dim method = DirectCast(members(index), PEMethodSymbol) Dim [module] = ContainingPEModule.Module Dim methodDefs = ArrayBuilder(Of MethodDefinitionHandle).GetInstance() Try For Each methodDef In [module].GetMethodsOfTypeOrThrow(_handle) methodDefs.Add(methodDef) Next Catch mrEx As BadImageFormatException End Try For Each methodDef In methodDefs If method.Handle = methodDef Then Yield method index += 1 If index = members.Length OrElse members(index).Kind <> SymbolKind.Method Then ' no need to return any gaps at the end. methodDefs.Free() Return End If method = DirectCast(members(index), PEMethodSymbol) Else ' Encountered a gap. Dim gapSize As Integer Try gapSize = ModuleExtensions.GetVTableGapSize([module].GetMethodDefNameOrThrow(methodDef)) Catch mrEx As BadImageFormatException gapSize = 1 End Try ' We don't have a symbol to return, so, even if the name doesn't represent a gap, we still have a gap. Do Yield Nothing gapSize -= 1 Loop While gapSize > 0 End If Next ' Ensure we explicitly returned from inside loop. Throw ExceptionUtilities.Unreachable End If End Function Friend Overrides Function GetPropertiesToEmit() As IEnumerable(Of PropertySymbol) Return GetMembers(Of PropertySymbol)(GetMembers(), SymbolKind.Property) End Function Friend Overrides Function GetEventsToEmit() As IEnumerable(Of EventSymbol) Return GetMembers(Of EventSymbol)(GetMembers(), SymbolKind.Event) End Function Private Class DeclarationOrderSymbolComparer Implements IComparer(Of ISymbol) Public Shared ReadOnly Instance As New DeclarationOrderSymbolComparer() Private Sub New() End Sub Public Function Compare(x As ISymbol, y As ISymbol) As Integer Implements IComparer(Of ISymbol).Compare If x Is y Then Return 0 End If Dim cmp As Integer = x.Kind.ToSortOrder - y.Kind.ToSortOrder If cmp <> 0 Then Return cmp End If Select Case x.Kind Case SymbolKind.Field Return HandleComparer.Default.Compare(DirectCast(x, PEFieldSymbol).Handle, DirectCast(y, PEFieldSymbol).Handle) Case SymbolKind.Method If DirectCast(x, MethodSymbol).IsDefaultValueTypeConstructor() Then Return -1 ElseIf DirectCast(y, MethodSymbol).IsDefaultValueTypeConstructor() Then Return 1 End If Return HandleComparer.Default.Compare(DirectCast(x, PEMethodSymbol).Handle, DirectCast(y, PEMethodSymbol).Handle) Case SymbolKind.Property Return HandleComparer.Default.Compare(DirectCast(x, PEPropertySymbol).Handle, DirectCast(y, PEPropertySymbol).Handle) Case SymbolKind.Event Return HandleComparer.Default.Compare(DirectCast(x, PEEventSymbol).Handle, DirectCast(y, PEEventSymbol).Handle) Case SymbolKind.NamedType Return HandleComparer.Default.Compare(DirectCast(x, PENamedTypeSymbol).Handle, DirectCast(y, PENamedTypeSymbol).Handle) Case Else Throw ExceptionUtilities.UnexpectedValue(x.Kind) End Select End Function End Class Private Sub EnsureNonTypeMembersAreLoaded() If _lazyMembers Is Nothing Then ' A method may be referenced as an accessor by one or more properties. And, ' any of those properties may be "bogus" if one of the property accessors ' does not match the property signature. If the method is referenced by at ' least one non-bogus property, then the method is created as an accessor, ' and (for purposes of error reporting if the method is referenced directly) the ' associated property is set (arbitrarily) to the first non-bogus property found ' in metadata. If the method is not referenced by any non-bogus properties, ' then the method is created as a normal method rather than an accessor. ' Create a dictionary of method symbols indexed by metadata row id ' (to allow efficient lookup when matching property accessors). Dim methodHandleToSymbol As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol) = CreateMethods() Dim members = ArrayBuilder(Of Symbol).GetInstance() Dim ensureParameterlessConstructor As Boolean = (TypeKind = TypeKind.Structure OrElse TypeKind = TypeKind.Enum) AndAlso Not IsShared For Each member In methodHandleToSymbol.Values members.Add(member) If ensureParameterlessConstructor Then ensureParameterlessConstructor = Not member.IsParameterlessConstructor() End If Next If ensureParameterlessConstructor Then members.Add(New SynthesizedConstructorSymbol(Nothing, Me, Me.IsShared, False, Nothing, Nothing)) End If ' CreateFields will add withEvent names here if there are any. ' Otherwise stays Nothing Dim withEventNames As HashSet(Of String) = Nothing CreateProperties(methodHandleToSymbol, members) CreateFields(members, withEventNames) CreateEvents(methodHandleToSymbol, members) Dim membersDict As New Dictionary(Of String, ImmutableArray(Of Symbol))(CaseInsensitiveComparison.Comparer) Dim groupedMembers = members.GroupBy(Function(m) m.Name, CaseInsensitiveComparison.Comparer) For Each g In groupedMembers membersDict.Add(g.Key, ImmutableArray.CreateRange(g)) Next members.Free() ' tell WithEvents properties that they are WithEvents properties If withEventNames IsNot Nothing Then For Each withEventName In withEventNames Dim weMembers As ImmutableArray(Of Symbol) = Nothing If membersDict.TryGetValue(withEventName, weMembers) Then ' there must be only a single match for a given WithEvents name If weMembers.Length <> 1 Then Continue For End If ' it must be a valid property Dim asProperty = TryCast(weMembers(0), PEPropertySymbol) If asProperty IsNot Nothing AndAlso IsValidWithEventsProperty(asProperty) Then asProperty.SetIsWithEvents(True) End If End If Next End If ' Merge types into members For Each typeSymbols In _lazyNestedTypes.Values Dim name = typeSymbols(0).Name Dim symbols As ImmutableArray(Of Symbol) = Nothing If Not membersDict.TryGetValue(name, symbols) Then membersDict.Add(name, StaticCast(Of Symbol).From(typeSymbols)) Else membersDict(name) = symbols.Concat(StaticCast(Of Symbol).From(typeSymbols)) End If Next Dim exchangeResult = Interlocked.CompareExchange(_lazyMembers, membersDict, Nothing) If exchangeResult Is Nothing Then Dim memberNames = SpecializedCollections.ReadOnlyCollection(membersDict.Keys) Interlocked.Exchange(Of ICollection(Of String))(_lazyMemberNames, memberNames) End If End If End Sub ''' <summary> ''' Some simple sanity checks if a property can actually be a withevents property ''' </summary> Private Function IsValidWithEventsProperty(prop As PEPropertySymbol) As Boolean ' NOTE: Dev10 does not make any checks. Just has comment that it could be a good idea to do in Whidbey. ' We will check, just to make stuff a bit more robust. ' It will be extremely rare that this function would fail though. If prop.IsReadOnly Or prop.IsWriteOnly Then Return False End If If Not prop.IsOverridable Then Return False End If Return True End Function Public Overloads Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol) EnsureNestedTypesAreLoaded() EnsureNonTypeMembersAreLoaded() Dim m As ImmutableArray(Of Symbol) = Nothing If _lazyMembers.TryGetValue(name, m) Then Return m End If Return ImmutableArray(Of Symbol).Empty End Function Friend Overrides Function GetTypeMembersUnordered() As ImmutableArray(Of NamedTypeSymbol) EnsureNestedTypesAreLoaded() Return StaticCast(Of NamedTypeSymbol).From(_lazyNestedTypes.Flatten()) End Function Public Overloads Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol) EnsureNestedTypesAreLoaded() Return StaticCast(Of NamedTypeSymbol).From(_lazyNestedTypes.Flatten(DeclarationOrderSymbolComparer.Instance)) End Function Private Sub EnsureNestedTypesAreLoaded() If _lazyNestedTypes Is Nothing Then Dim typesDict = CreateNestedTypes() Interlocked.CompareExchange(_lazyNestedTypes, typesDict, Nothing) ' Build cache of TypeDef Tokens ' Potentially this can be done in the background. If _lazyNestedTypes Is typesDict Then ContainingPEModule.OnNewTypeDeclarationsLoaded(typesDict) End If End If End Sub Public Overloads Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol) EnsureNestedTypesAreLoaded() Dim t As ImmutableArray(Of PENamedTypeSymbol) = Nothing If _lazyNestedTypes.TryGetValue(name, t) Then Return StaticCast(Of NamedTypeSymbol).From(t) End If Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overloads Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol) Return GetTypeMembers(name).WhereAsArray(Function(type, arity_) type.Arity = arity_, arity) End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return StaticCast(Of Location).From(ContainingPEModule.MetadataLocation) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Friend ReadOnly Property TypeDefFlags As TypeAttributes Get Return _flags End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get EnsureTypeParametersAreLoaded() Return _lazyTypeParameters End Get End Property Private Sub EnsureTypeParametersAreLoaded() If _lazyTypeParameters.IsDefault Then Debug.Assert(_arity > 0) Dim ownedParams(_arity - 1) As PETypeParameterSymbol Dim moduleSymbol = ContainingPEModule ' If this is a nested type generic parameters in metadata include generic parameters of the outer types. Dim firstIndex = _genericParameterHandles.Count - Arity For i = 0 To ownedParams.Length - 1 ownedParams(i) = New PETypeParameterSymbol(moduleSymbol, Me, CUShort(i), _genericParameterHandles(firstIndex + i)) Next ImmutableInterlocked.InterlockedCompareExchange(_lazyTypeParameters, StaticCast(Of TypeParameterSymbol).From(ownedParams.AsImmutableOrNull), Nothing) End If End Sub Public Overrides ReadOnly Property IsMustInherit As Boolean Get Return (_flags And TypeAttributes.Abstract) <> 0 AndAlso (_flags And TypeAttributes.Sealed) = 0 End Get End Property Friend Overrides ReadOnly Property IsMetadataAbstract As Boolean Get Return (_flags And TypeAttributes.Abstract) <> 0 End Get End Property Public Overrides ReadOnly Property IsNotInheritable As Boolean Get Return (_flags And TypeAttributes.Sealed) <> 0 End Get End Property Friend Overrides ReadOnly Property IsMetadataSealed As Boolean Get Return (_flags And TypeAttributes.Sealed) <> 0 End Get End Property Friend Overrides ReadOnly Property IsWindowsRuntimeImport As Boolean Get Return (_flags And TypeAttributes.WindowsRuntime) <> 0 End Get End Property Friend Overrides ReadOnly Property ShouldAddWinRTMembers As Boolean Get Return IsWindowsRuntimeImport End Get End Property Friend Overrides Function GetGuidString(ByRef guidString As String) As Boolean Return ContainingPEModule.Module.HasGuidAttribute(_handle, guidString) End Function Public NotOverridable Overrides ReadOnly Property MightContainExtensionMethods As Boolean Get If _lazyMightContainExtensionMethods = ThreeState.Unknown Then ' Only top level non-generic types with an Extension attribute are ' valid containers of extension methods. Dim result As Boolean = False If _container.Kind = SymbolKind.Namespace AndAlso _arity = 0 Then Dim containingModuleSymbol = Me.ContainingPEModule If containingModuleSymbol.MightContainExtensionMethods AndAlso containingModuleSymbol.Module.HasExtensionAttribute(Me._handle, ignoreCase:=True) Then result = True End If End If If result Then _lazyMightContainExtensionMethods = ThreeState.True Else _lazyMightContainExtensionMethods = ThreeState.False End If End If Return _lazyMightContainExtensionMethods = ThreeState.True End Get End Property Friend Overrides ReadOnly Property HasCodeAnalysisEmbeddedAttribute As Boolean Get If Me._lazyHasCodeAnalysisEmbeddedAttribute = ThreeState.Unknown Then Interlocked.CompareExchange( Me._lazyHasCodeAnalysisEmbeddedAttribute, Me.ContainingPEModule.Module.HasCodeAnalysisEmbeddedAttribute(Me._handle).ToThreeState(), ThreeState.Unknown) End If Return Me._lazyHasCodeAnalysisEmbeddedAttribute = ThreeState.True End Get End Property Friend Overrides ReadOnly Property HasVisualBasicEmbeddedAttribute As Boolean Get If Me._lazyHasVisualBasicEmbeddedAttribute = ThreeState.Unknown Then Interlocked.CompareExchange( Me._lazyHasVisualBasicEmbeddedAttribute, Me.ContainingPEModule.Module.HasVisualBasicEmbeddedAttribute(Me._handle).ToThreeState(), ThreeState.Unknown) End If Return Me._lazyHasVisualBasicEmbeddedAttribute = ThreeState.True End Get End Property Friend Overrides Sub BuildExtensionMethodsMap( map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)), appendThrough As NamespaceSymbol ) If Me.MightContainExtensionMethods Then EnsureNestedTypesAreLoaded() EnsureNonTypeMembersAreLoaded() If Not appendThrough.BuildExtensionMethodsMap(map, _lazyMembers) Then ' Didn't find any extension methods, record the fact. _lazyMightContainExtensionMethods = ThreeState.False End If End If End Sub Friend Overrides Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder, appendThrough As NamedTypeSymbol) If Me.MightContainExtensionMethods Then EnsureNestedTypesAreLoaded() EnsureNonTypeMembersAreLoaded() If Not appendThrough.AddExtensionMethodLookupSymbolsInfo(nameSet, options, originalBinder, _lazyMembers) Then ' Didn't find any extension methods, record the fact. _lazyMightContainExtensionMethods = ThreeState.False End If End If End Sub Public Overrides ReadOnly Property TypeKind As TypeKind Get If _lazyTypeKind = TypeKind.Unknown Then Dim result As TypeKind If (_flags And TypeAttributes.Interface) <> 0 Then result = TypeKind.Interface Else Dim base As TypeSymbol = GetDeclaredBase(Nothing) result = TypeKind.Class If base IsNot Nothing Then ' Code is cloned from MetaImport::DoImportBaseAndImplements() Dim baseCorTypeId As SpecialType = base.SpecialType If baseCorTypeId = SpecialType.System_Enum Then ' Enum result = TypeKind.Enum ElseIf baseCorTypeId = SpecialType.System_MulticastDelegate OrElse (baseCorTypeId = SpecialType.System_Delegate AndAlso Me.SpecialType <> SpecialType.System_MulticastDelegate) Then ' Delegate result = TypeKind.Delegate ElseIf (baseCorTypeId = SpecialType.System_ValueType AndAlso Me.SpecialType <> SpecialType.System_Enum) Then ' Struct result = TypeKind.Structure ElseIf Me.Arity = 0 AndAlso Me.ContainingType Is Nothing AndAlso ContainingPEModule.Module.HasAttribute(Me._handle, AttributeDescription.StandardModuleAttribute) Then result = TypeKind.Module End If End If End If _lazyTypeKind = result End If Return CType(_lazyTypeKind, TypeKind) End Get End Property Friend Overrides ReadOnly Property IsInterface As Boolean Get Return (_flags And TypeAttributes.Interface) <> 0 End Get End Property Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String ' Note: m_lazyDocComment is passed ByRef Return PEDocumentationCommentUtils.GetDocumentationComment( Me, ContainingPEModule, preferredCulture, cancellationToken, _lazyDocComment) End Function Friend Overrides ReadOnly Property IsComImport As Boolean Get Return (_flags And TypeAttributes.Import) <> 0 End Get End Property Friend Overrides ReadOnly Property CoClassType As TypeSymbol Get If _lazyCoClassType Is ErrorTypeSymbol.UnknownResultType Then Interlocked.CompareExchange(_lazyCoClassType, MakeComImportCoClassType(), DirectCast(ErrorTypeSymbol.UnknownResultType, TypeSymbol)) End If Return _lazyCoClassType End Get End Property Private Function MakeComImportCoClassType() As TypeSymbol If Not Me.IsInterface Then Return Nothing End If Dim coClassTypeName As String = Nothing If Not Me.ContainingPEModule.Module.HasStringValuedAttribute(Me._handle, AttributeDescription.CoClassAttribute, coClassTypeName) Then Return Nothing End If Dim decoder As New MetadataDecoder(Me.ContainingPEModule) Return decoder.GetTypeSymbolForSerializedType(coClassTypeName) End Function Friend Overrides ReadOnly Property DefaultPropertyName As String Get ' Unset value is Nothing. No default member is String.Empty. If _lazyDefaultPropertyName Is Nothing Then Dim memberName = GetDefaultPropertyName() Interlocked.CompareExchange(_lazyDefaultPropertyName, If(memberName, String.Empty), Nothing) End If ' Return Nothing rather than String.Empty for no default member. Return If(String.IsNullOrEmpty(_lazyDefaultPropertyName), Nothing, _lazyDefaultPropertyName) End Get End Property Private Function GetDefaultPropertyName() As String Dim memberName As String = Nothing ContainingPEModule.Module.HasDefaultMemberAttribute(Me._handle, memberName) If memberName IsNot Nothing Then For Each member In GetMembers(memberName) ' Allow Default Shared properties for consistency with Dev10. If member.Kind = SymbolKind.Property Then Return memberName End If Next End If Return Nothing End Function Private Function CreateNestedTypes() As Dictionary(Of String, ImmutableArray(Of PENamedTypeSymbol)) Dim members = ArrayBuilder(Of PENamedTypeSymbol).GetInstance() Dim moduleSymbol = Me.ContainingPEModule Dim [module] = moduleSymbol.Module Try For Each nestedTypeDef In [module].GetNestedTypeDefsOrThrow(_handle) If [module].ShouldImportNestedType(nestedTypeDef) Then members.Add(New PENamedTypeSymbol(moduleSymbol, Me, nestedTypeDef)) End If Next Catch mrEx As BadImageFormatException End Try Dim children = members.GroupBy(Function(t) t.Name, IdentifierComparison.Comparer) Dim types = New Dictionary(Of String, ImmutableArray(Of PENamedTypeSymbol))(IdentifierComparison.Comparer) For Each c In children types.Add(c.Key, c.ToArray().AsImmutableOrNull()) Next members.Free() Return types End Function Private Sub CreateFields(members As ArrayBuilder(Of Symbol), <Out()> ByRef witheventPropertyNames As HashSet(Of String)) Dim moduleSymbol = Me.ContainingPEModule Dim [module] = moduleSymbol.Module Try For Each fieldDef In [module].GetFieldsOfTypeOrThrow(_handle) Dim import As Boolean Try import = [module].ShouldImportField(fieldDef, moduleSymbol.ImportOptions) If Not import Then Select Case Me.TypeKind Case TypeKind.Structure Dim specialType = Me.SpecialType If specialType = SpecialType.None OrElse specialType = SpecialType.System_Nullable_T Then ' This is an ordinary struct If ([module].GetFieldDefFlagsOrThrow(fieldDef) And FieldAttributes.Static) = 0 Then import = True End If End If Case TypeKind.Enum If ([module].GetFieldDefFlagsOrThrow(fieldDef) And FieldAttributes.Static) = 0 Then import = True End If End Select End If Catch mrEx As BadImageFormatException End Try If import Then members.Add(New PEFieldSymbol(moduleSymbol, Me, fieldDef)) End If Dim witheventPropertyName As String = Nothing If [module].HasAccessedThroughPropertyAttribute(fieldDef, witheventPropertyName) Then ' Dev10 does not check if names are duplicated, but it does check ' that withevents names match some property name using identifier match ' So if names are duplicated they would refer to same property. ' We will just put names in a set. If witheventPropertyNames Is Nothing Then witheventPropertyNames = New HashSet(Of String)(IdentifierComparison.Comparer) End If witheventPropertyNames.Add(witheventPropertyName) End If Next Catch mrEx As BadImageFormatException End Try End Sub Private Function CreateMethods() As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol) Dim methods = New Dictionary(Of MethodDefinitionHandle, PEMethodSymbol)() Dim moduleSymbol = Me.ContainingPEModule Dim [module] = moduleSymbol.Module Try For Each methodDef In [module].GetMethodsOfTypeOrThrow(_handle) If [module].ShouldImportMethod(_handle, methodDef, moduleSymbol.ImportOptions) Then methods.Add(methodDef, New PEMethodSymbol(moduleSymbol, Me, methodDef)) End If Next Catch mrEx As BadImageFormatException End Try Return methods End Function Private Sub CreateProperties(methodHandleToSymbol As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol), members As ArrayBuilder(Of Symbol)) Dim moduleSymbol = Me.ContainingPEModule Dim [module] = moduleSymbol.Module Try For Each propertyDef In [module].GetPropertiesOfTypeOrThrow(_handle) Try Dim methods = [module].GetPropertyMethodsOrThrow(propertyDef) Dim getMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, _handle, methods.Getter) Dim setMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, _handle, methods.Setter) If (getMethod IsNot Nothing) OrElse (setMethod IsNot Nothing) Then members.Add(PEPropertySymbol.Create(moduleSymbol, Me, propertyDef, getMethod, setMethod)) End If Catch mrEx As BadImageFormatException End Try Next Catch mrEx As BadImageFormatException End Try End Sub Private Sub CreateEvents(methodHandleToSymbol As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol), members As ArrayBuilder(Of Symbol)) Dim moduleSymbol = Me.ContainingPEModule Dim [module] = moduleSymbol.Module Try For Each eventRid In [module].GetEventsOfTypeOrThrow(_handle) Try Dim methods = [module].GetEventMethodsOrThrow(eventRid) ' NOTE: C# ignores all other accessors (most notably, raise/fire). Dim addMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, _handle, methods.Adder) Dim removeMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, _handle, methods.Remover) Dim raiseMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, _handle, methods.Raiser) ' VB ignores events that do not have both Add and Remove. If (addMethod IsNot Nothing) AndAlso (removeMethod IsNot Nothing) Then members.Add(New PEEventSymbol(moduleSymbol, Me, eventRid, addMethod, removeMethod, raiseMethod)) End If Catch mrEx As BadImageFormatException End Try Next Catch mrEx As BadImageFormatException End Try End Sub Private Shared Function GetAccessorMethod(moduleSymbol As PEModuleSymbol, methodHandleToSymbol As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol), typeDef As TypeDefinitionHandle, methodDef As MethodDefinitionHandle) As PEMethodSymbol If methodDef.IsNil Then Return Nothing End If Dim method As PEMethodSymbol = Nothing Dim found As Boolean = methodHandleToSymbol.TryGetValue(methodDef, method) Debug.Assert(found OrElse Not moduleSymbol.Module.ShouldImportMethod(typeDef, methodDef, moduleSymbol.ImportOptions)) Return method End Function Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol) Dim primaryDependency As AssemblySymbol = Me.PrimaryDependency If Not _lazyCachedUseSiteInfo.IsInitialized Then _lazyCachedUseSiteInfo.Initialize(primaryDependency, CalculateUseSiteInfoImpl()) End If Return _lazyCachedUseSiteInfo.ToUseSiteInfo(primaryDependency) End Function Private Function CalculateUseSiteInfoImpl() As UseSiteInfo(Of AssemblySymbol) Dim useSiteInfo = CalculateUseSiteInfo() If useSiteInfo.DiagnosticInfo Is Nothing Then ' Check if this type Is marked by RequiredAttribute attribute. ' If so mark the type as bad, because it relies upon semantics that are not understood by the VB compiler. If Me.ContainingPEModule.Module.HasRequiredAttributeAttribute(Me.Handle) Then Return New UseSiteInfo(Of AssemblySymbol)(ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedType1, Me)) End If Dim typeKind = Me.TypeKind Dim specialtype = Me.SpecialType If (typeKind = TypeKind.Class OrElse typeKind = TypeKind.Module) AndAlso specialtype <> SpecialType.System_Enum AndAlso specialtype <> SpecialType.System_MulticastDelegate Then Dim base As TypeSymbol = GetDeclaredBase(Nothing) If base IsNot Nothing AndAlso base.SpecialType = SpecialType.None AndAlso base.ContainingAssembly?.IsMissing Then Dim missingType = TryCast(base, MissingMetadataTypeSymbol.TopLevel) If missingType IsNot Nothing AndAlso missingType.Arity = 0 Then Dim emittedName As String = MetadataHelpers.BuildQualifiedName(missingType.NamespaceName, missingType.MetadataName) Select Case SpecialTypes.GetTypeFromMetadataName(emittedName) Case SpecialType.System_Enum, SpecialType.System_Delegate, SpecialType.System_MulticastDelegate, SpecialType.System_ValueType ' This might be a structure, an enum, or a delegate Return missingType.GetUseSiteInfo() End Select End If End If End If ' Verify type parameters for containing types ' match those on the containing types. If Not MatchesContainingTypeParameters() Then Return New UseSiteInfo(Of AssemblySymbol)(ErrorFactory.ErrorInfo(ERRID.ERR_NestingViolatesCLS1, Me)) End If End If Return useSiteInfo End Function ''' <summary> ''' Return true if the type parameters specified on the nested type (Me), ''' that represent the corresponding type parameters on the containing ''' types, in fact match the actual type parameters on the containing types. ''' </summary> Private Function MatchesContainingTypeParameters() As Boolean If _genericParameterHandles.Count = 0 Then Return True End If Dim container = ContainingType If container Is Nothing Then Return True End If Dim containingTypeParameters = container.GetAllTypeParameters() Dim n = containingTypeParameters.Length If n = 0 Then Return True End If ' Create an instance of PENamedTypeSymbol for the nested type, but ' with all type parameters, from the nested type and all containing ' types. The type parameters on this temporary type instance are used ' for comparison with those on the actual containing types. The ' containing symbol for the temporary type is the namespace directly. Dim nestedType = New PENamedTypeSymbol(ContainingPEModule, DirectCast(ContainingNamespace, PENamespaceSymbol), _handle) Dim nestedTypeParameters = nestedType.TypeParameters Dim containingTypeMap = TypeSubstitution.Create( container, containingTypeParameters, IndexedTypeParameterSymbol.Take(n).As(Of TypeSymbol)) Dim nestedTypeMap = TypeSubstitution.Create( nestedType, nestedTypeParameters, IndexedTypeParameterSymbol.Take(nestedTypeParameters.Length).As(Of TypeSymbol)) For i = 0 To n - 1 Dim containingTypeParameter = containingTypeParameters(i) Dim nestedTypeParameter = nestedTypeParameters(i) If Not MethodSignatureComparer.HaveSameConstraints( containingTypeParameter, containingTypeMap, nestedTypeParameter, nestedTypeMap) Then Return False End If Next Return True End Function ''' <summary> ''' Force all declaration errors to be generated. ''' </summary> Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) Throw ExceptionUtilities.Unreachable End Sub Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get ObsoleteAttributeHelpers.InitializeObsoleteDataFromMetadata(_lazyObsoleteAttributeData, _handle, ContainingPEModule) Return _lazyObsoleteAttributeData End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) If Me._lazyConditionalAttributeSymbols.IsDefault Then Dim conditionalSymbols As ImmutableArray(Of String) = ContainingPEModule.Module.GetConditionalAttributeValues(_handle) Debug.Assert(Not conditionalSymbols.IsDefault) ImmutableInterlocked.InterlockedCompareExchange(_lazyConditionalAttributeSymbols, conditionalSymbols, Nothing) End If Return Me._lazyConditionalAttributeSymbols End Function Friend Overrides Function GetAttributeUsageInfo() As AttributeUsageInfo If _lazyAttributeUsageInfo.IsNull Then _lazyAttributeUsageInfo = DecodeAttributeUsageInfo() End If Debug.Assert(Not _lazyAttributeUsageInfo.IsNull) Return _lazyAttributeUsageInfo End Function Private Function DecodeAttributeUsageInfo() As AttributeUsageInfo Dim attributeUsageHandle = Me.ContainingPEModule.Module.GetAttributeUsageAttributeHandle(_handle) If Not attributeUsageHandle.IsNil Then Dim decoder = New MetadataDecoder(ContainingPEModule) Dim positionalArgs As TypedConstant() = Nothing Dim namedArgs As KeyValuePair(Of String, TypedConstant)() = Nothing If decoder.GetCustomAttribute(attributeUsageHandle, positionalArgs, namedArgs) Then Return AttributeData.DecodeAttributeUsageAttribute(positionalArgs(0), namedArgs.AsImmutableOrNull()) End If End If Dim baseType = Me.BaseTypeNoUseSiteDiagnostics Return If(baseType IsNot Nothing, baseType.GetAttributeUsageInfo(), AttributeUsageInfo.Default) End Function Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean Get If _lazyIsExtensibleInterface = ThreeState.Unknown Then _lazyIsExtensibleInterface = DecodeIsExtensibleInterface().ToThreeState() End If Return _lazyIsExtensibleInterface.Value End Get End Property Private Function DecodeIsExtensibleInterface() As Boolean If Me.IsInterfaceType() Then If Me.HasAttributeForExtensibleInterface() Then Return True End If For Each [interface] In Me.AllInterfacesNoUseSiteDiagnostics If [interface].IsExtensibleInterfaceNoUseSiteDiagnostics Then Return True End If Next End If Return False End Function Private Function HasAttributeForExtensibleInterface() As Boolean Dim metadataModule = Me.ContainingPEModule.Module ' Is interface marked with 'TypeLibTypeAttribute( flags w/o TypeLibTypeFlags.FNonExtensible )' attribute Dim flags As Cci.TypeLibTypeFlags = Nothing If metadataModule.HasTypeLibTypeAttribute(Me._handle, flags) AndAlso (flags And Cci.TypeLibTypeFlags.FNonExtensible) = 0 Then Return True End If ' Is interface marked with 'InterfaceTypeAttribute( flags with ComInterfaceType.InterfaceIsIDispatch )' attribute Dim interfaceType As ComInterfaceType = Nothing If metadataModule.HasInterfaceTypeAttribute(Me._handle, interfaceType) AndAlso (interfaceType And Cci.Constants.ComInterfaceType_InterfaceIsIDispatch) <> 0 Then Return True End If Return False End Function ''' <remarks> ''' This is for perf, not for correctness. ''' </remarks> Friend NotOverridable Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation Get Return Nothing End Get End Property ''' <summary> ''' Returns the index of the first member of the specific kind. ''' Returns the number of members if not found. ''' </summary> Private Shared Function GetIndexOfFirstMember(members As ImmutableArray(Of Symbol), kind As SymbolKind) As Integer Dim n = members.Length For i = 0 To n - 1 If members(i).Kind = kind Then Return i End If Next Return n End Function ''' <summary> ''' Returns all members of the specific kind, starting at the optional offset. ''' Members of the same kind are assumed to be contiguous. ''' </summary> Private Overloads Shared Iterator Function GetMembers(Of TSymbol As Symbol)(members As ImmutableArray(Of Symbol), kind As SymbolKind, Optional offset As Integer = -1) As IEnumerable(Of TSymbol) If offset < 0 Then offset = GetIndexOfFirstMember(members, kind) End If Dim n = members.Length For i = offset To n - 1 Dim member = members(i) If member.Kind <> kind Then Return End If Yield DirectCast(member, TSymbol) Next End Function Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() 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.Generic Imports System.Collections.Immutable Imports System.Collections.ObjectModel Imports System.Globalization Imports System.Reflection Imports System.Reflection.Metadata Imports System.Linq Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Imports TypeAttributes = System.Reflection.TypeAttributes Imports FieldAttributes = System.Reflection.FieldAttributes Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ''' <summary> ''' The class to represent all types imported from a PE/module. ''' </summary> ''' <remarks></remarks> Friend Class PENamedTypeSymbol Inherits InstanceTypeSymbol Private ReadOnly _container As NamespaceOrTypeSymbol #Region "Metadata" Private ReadOnly _handle As TypeDefinitionHandle Private ReadOnly _genericParameterHandles As GenericParameterHandleCollection Private ReadOnly _name As String Private ReadOnly _flags As TypeAttributes Private ReadOnly _arity As UShort Private ReadOnly _mangleName As Boolean ' CONSIDER: combine with flags #End Region ''' <summary> ''' A map of types immediately contained within this type ''' grouped by their name (case-insensitively). ''' </summary> Private _lazyNestedTypes As Dictionary(Of String, ImmutableArray(Of PENamedTypeSymbol)) ''' <summary> ''' A set of all the names of the members in this type. ''' </summary> Private _lazyMemberNames As ICollection(Of String) ''' <summary> ''' A map of members immediately contained within this type ''' grouped by their name (case-insensitively). ''' </summary> ''' <remarks></remarks> Private _lazyMembers As Dictionary(Of String, ImmutableArray(Of Symbol)) Private _lazyTypeParameters As ImmutableArray(Of TypeParameterSymbol) Private _lazyEnumUnderlyingType As NamedTypeSymbol Private _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData) Private _lazyConditionalAttributeSymbols As ImmutableArray(Of String) Private _lazyAttributeUsageInfo As AttributeUsageInfo = AttributeUsageInfo.Null Private _lazyCoClassType As TypeSymbol = ErrorTypeSymbol.UnknownResultType ''' <summary> ''' Lazily initialized by TypeKind property. ''' Using Integer type to make sure read/write operations are atomic. ''' </summary> ''' <remarks></remarks> Private _lazyTypeKind As Integer Private _lazyDocComment As Tuple(Of CultureInfo, String) Private _lazyDefaultPropertyName As String Private _lazyCachedUseSiteInfo As CachedUseSiteInfo(Of AssemblySymbol) = CachedUseSiteInfo(Of AssemblySymbol).Uninitialized ' Indicates unknown state. Private _lazyMightContainExtensionMethods As Byte = ThreeState.Unknown Private _lazyHasCodeAnalysisEmbeddedAttribute As Integer = ThreeState.Unknown Private _lazyHasVisualBasicEmbeddedAttribute As Integer = ThreeState.Unknown Private _lazyObsoleteAttributeData As ObsoleteAttributeData = ObsoleteAttributeData.Uninitialized Private _lazyIsExtensibleInterface As ThreeState = ThreeState.Unknown Friend Sub New( moduleSymbol As PEModuleSymbol, containingNamespace As PENamespaceSymbol, handle As TypeDefinitionHandle ) Me.New(moduleSymbol, containingNamespace, 0, handle) End Sub Friend Sub New( moduleSymbol As PEModuleSymbol, containingType As PENamedTypeSymbol, handle As TypeDefinitionHandle ) Me.New(moduleSymbol, containingType, CUShort(containingType.MetadataArity), handle) End Sub Private Sub New( moduleSymbol As PEModuleSymbol, container As NamespaceOrTypeSymbol, containerMetadataArity As UShort, handle As TypeDefinitionHandle ) Debug.Assert(Not handle.IsNil) Debug.Assert(container IsNot Nothing) _handle = handle _container = container Dim makeBad As Boolean = False Dim name As String Try name = moduleSymbol.Module.GetTypeDefNameOrThrow(handle) Catch mrEx As BadImageFormatException name = String.Empty makeBad = True End Try Try _flags = moduleSymbol.Module.GetTypeDefFlagsOrThrow(handle) Catch mrEx As BadImageFormatException makeBad = True End Try Dim metadataArity As Integer Try _genericParameterHandles = moduleSymbol.Module.GetTypeDefGenericParamsOrThrow(handle) metadataArity = _genericParameterHandles.Count Catch mrEx As BadImageFormatException _genericParameterHandles = Nothing metadataArity = 0 makeBad = True End Try ' Figure out arity from the language point of view If metadataArity > containerMetadataArity Then _arity = CType(metadataArity - containerMetadataArity, UShort) End If If _arity = 0 Then _lazyTypeParameters = ImmutableArray(Of TypeParameterSymbol).Empty _name = name _mangleName = False Else ' Unmangle name for a generic type. _name = MetadataHelpers.UnmangleMetadataNameForArity(name, _arity) _mangleName = (_name IsNot name) End If If makeBad OrElse metadataArity < containerMetadataArity Then _lazyCachedUseSiteInfo.Initialize(ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedType1, Me)) End If Debug.Assert(Not _mangleName OrElse _name.Length < name.Length) End Sub Friend ReadOnly Property ContainingPEModule As PEModuleSymbol Get Dim s As Symbol = _container While s.Kind <> SymbolKind.Namespace s = s.ContainingSymbol End While Return DirectCast(s, PENamespaceSymbol).ContainingPEModule End Get End Property Public Overrides ReadOnly Property ContainingModule As ModuleSymbol Get Return ContainingPEModule End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return _arity End Get End Property Friend Overrides ReadOnly Property MangleName As Boolean Get Return _mangleName End Get End Property Friend Overrides ReadOnly Property Layout As TypeLayout Get Return Me.ContainingPEModule.Module.GetTypeLayout(_handle) End Get End Property Friend Overrides ReadOnly Property MarshallingCharSet As CharSet Get Dim result As CharSet = _flags.ToCharSet() If result = 0 Then Return CharSet.Ansi End If Return result End Get End Property Public Overrides ReadOnly Property IsSerializable As Boolean Get Return (_flags And TypeAttributes.Serializable) <> 0 End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return (_flags And TypeAttributes.SpecialName) <> 0 End Get End Property Friend ReadOnly Property MetadataArity As Integer Get Return _genericParameterHandles.Count End Get End Property Friend ReadOnly Property Handle As TypeDefinitionHandle Get Return _handle End Get End Property Friend Overrides Function GetInterfacesToEmit() As IEnumerable(Of NamedTypeSymbol) Return InterfacesNoUseSiteDiagnostics End Function Friend Overrides Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol If (Me._flags And TypeAttributes.Interface) = 0 Then Dim moduleSymbol As PEModuleSymbol = Me.ContainingPEModule Try Dim token As EntityHandle = moduleSymbol.Module.GetBaseTypeOfTypeOrThrow(Me._handle) If Not token.IsNil Then Dim decodedType = New MetadataDecoder(moduleSymbol, Me).GetTypeOfToken(token) Return DirectCast(TupleTypeDecoder.DecodeTupleTypesIfApplicable(decodedType, _handle, moduleSymbol), NamedTypeSymbol) End If Catch mrEx As BadImageFormatException Return New UnsupportedMetadataTypeSymbol(mrEx) End Try End If Return Nothing End Function Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Try Dim moduleSymbol As PEModuleSymbol = Me.ContainingPEModule Dim interfaceImpls = moduleSymbol.Module.GetInterfaceImplementationsOrThrow(Me._handle) If interfaceImpls.Count = 0 Then Return ImmutableArray(Of NamedTypeSymbol).Empty End If Dim symbols As NamedTypeSymbol() = New NamedTypeSymbol(interfaceImpls.Count - 1) {} Dim tokenDecoder As New MetadataDecoder(moduleSymbol, Me) Dim i = 0 For Each interfaceImpl In interfaceImpls Dim interfaceHandle As EntityHandle = moduleSymbol.Module.MetadataReader.GetInterfaceImplementation(interfaceImpl).Interface Dim typeSymbol As TypeSymbol = tokenDecoder.GetTypeOfToken(interfaceHandle) typeSymbol = DirectCast(TupleTypeDecoder.DecodeTupleTypesIfApplicable(typeSymbol, interfaceImpl, moduleSymbol), NamedTypeSymbol) 'TODO: how to pass reason to unsupported Dim namedTypeSymbol As NamedTypeSymbol = TryCast(typeSymbol, NamedTypeSymbol) symbols(i) = If(namedTypeSymbol IsNot Nothing, namedTypeSymbol, New UnsupportedMetadataTypeSymbol()) ' "interface tmpList contains a bad type" i = i + 1 Next Return symbols.AsImmutableOrNull Catch mrEx As BadImageFormatException Return ImmutableArray.Create(Of NamedTypeSymbol)(New UnsupportedMetadataTypeSymbol(mrEx)) End Try End Function Private Shared Function CyclicInheritanceError(diag As DiagnosticInfo) As ErrorTypeSymbol Return New ExtendedErrorTypeSymbol(diag, True) End Function Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Dim diag = BaseTypeAnalysis.GetDependencyDiagnosticsForImportedClass(Me) If diag IsNot Nothing Then Return CyclicInheritanceError(diag) End If Return GetDeclaredBase(Nothing) End Function Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Dim declaredInterfaces As ImmutableArray(Of NamedTypeSymbol) = GetDeclaredInterfacesNoUseSiteDiagnostics(Nothing) If (Not Me.IsInterface) Then ' only interfaces needs to check for inheritance cycles via interfaces. Return declaredInterfaces End If Return (From t In declaredInterfaces Let diag = BaseTypeAnalysis.GetDependencyDiagnosticsForImportedBaseInterface(Me, t) Select If(diag Is Nothing, t, CyclicInheritanceError(diag))).AsImmutable End Function Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return TryCast(_container, NamedTypeSymbol) End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Dim access As Accessibility = Accessibility.Private Select Case _flags And TypeAttributes.VisibilityMask Case TypeAttributes.NestedAssembly access = Accessibility.Friend Case TypeAttributes.NestedFamORAssem access = Accessibility.ProtectedOrFriend Case TypeAttributes.NestedFamANDAssem access = Accessibility.ProtectedAndFriend Case TypeAttributes.NestedPrivate access = Accessibility.Private Case TypeAttributes.Public, TypeAttributes.NestedPublic access = Accessibility.Public Case TypeAttributes.NestedFamily access = Accessibility.Protected Case TypeAttributes.NotPublic access = Accessibility.Friend Case Else Debug.Assert(False, "Unexpected!!!") End Select Return access End Get End Property Public Overrides ReadOnly Property EnumUnderlyingType As NamedTypeSymbol Get If _lazyEnumUnderlyingType Is Nothing AndAlso TypeKind = TypeKind.Enum Then ' From §8.5.2 ' An enum is considerably more restricted than a true type, as ' follows: ' • It shall have exactly one instance field, and the type of that field defines the underlying type of ' the enumeration. ' • It shall not have any static fields unless they are literal. (see §8.6.1.2) ' The underlying type shall be a built-in integer type. Enums shall derive from System.Enum, hence they are ' value types. Like all value types, they shall be sealed (see §8.9.9). Dim underlyingType As NamedTypeSymbol = Nothing For Each member In GetMembers() If (Not member.IsShared AndAlso member.Kind = SymbolKind.Field) Then Dim type = DirectCast(member, FieldSymbol).Type If (type.SpecialType.IsClrInteger()) Then If (underlyingType Is Nothing) Then underlyingType = DirectCast(type, NamedTypeSymbol) Else underlyingType = New UnsupportedMetadataTypeSymbol() Exit For End If End If End If Next Interlocked.CompareExchange(_lazyEnumUnderlyingType, If(underlyingType, New UnsupportedMetadataTypeSymbol()), Nothing) End If Return _lazyEnumUnderlyingType End Get End Property Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) If _lazyCustomAttributes.IsDefault Then If (_lazyTypeKind = TypeKind.Unknown AndAlso ((_flags And TypeAttributes.Interface) <> 0 OrElse Me.Arity <> 0 OrElse Me.ContainingType IsNot Nothing)) OrElse Me.TypeKind <> TypeKind.Module Then ContainingPEModule.LoadCustomAttributes(_handle, _lazyCustomAttributes) Else Dim stdModuleAttribute As CustomAttributeHandle Dim attributes = ContainingPEModule.GetCustomAttributesForToken( _handle, stdModuleAttribute, filterOut1:=AttributeDescription.StandardModuleAttribute) Debug.Assert(Not stdModuleAttribute.IsNil) ImmutableInterlocked.InterlockedInitialize(_lazyCustomAttributes, attributes) End If End If Return _lazyCustomAttributes End Function Friend Overrides Iterator Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData) For Each attribute In GetAttributes() Yield attribute Next If Me.TypeKind = TypeKind.Module Then Yield New PEAttributeData(ContainingPEModule, ContainingPEModule.Module.GetAttributeHandle(Me._handle, AttributeDescription.StandardModuleAttribute)) End If End Function Public Overrides ReadOnly Property MemberNames As IEnumerable(Of String) Get EnsureNonTypeMemberNamesAreLoaded() Return _lazyMemberNames End Get End Property Private Sub EnsureNonTypeMemberNamesAreLoaded() If _lazyMemberNames Is Nothing Then Dim peModule = ContainingPEModule.Module Dim names = New HashSet(Of String)() Try For Each methodDef In peModule.GetMethodsOfTypeOrThrow(_handle) Try names.Add(peModule.GetMethodDefNameOrThrow(methodDef)) Catch mrEx As BadImageFormatException End Try Next Catch mrEx As BadImageFormatException End Try Try For Each propertyDef In peModule.GetPropertiesOfTypeOrThrow(_handle) Try names.Add(peModule.GetPropertyDefNameOrThrow(propertyDef)) Catch mrEx As BadImageFormatException End Try Next Catch mrEx As BadImageFormatException End Try Try For Each eventDef In peModule.GetEventsOfTypeOrThrow(_handle) Try names.Add(peModule.GetEventDefNameOrThrow(eventDef)) Catch mrEx As BadImageFormatException End Try Next Catch mrEx As BadImageFormatException End Try Try For Each fieldDef In peModule.GetFieldsOfTypeOrThrow(_handle) Try names.Add(peModule.GetFieldDefNameOrThrow(fieldDef)) Catch mrEx As BadImageFormatException End Try Next Catch mrEx As BadImageFormatException End Try Interlocked.CompareExchange(Of ICollection(Of String))( _lazyMemberNames, SpecializedCollections.ReadOnlySet(names), Nothing) End If End Sub Public Overloads Overrides Function GetMembers() As ImmutableArray(Of Symbol) EnsureNestedTypesAreLoaded() EnsureNonTypeMembersAreLoaded() Return _lazyMembers.Flatten(DeclarationOrderSymbolComparer.Instance) End Function Friend Overrides Function GetMembersUnordered() As ImmutableArray(Of Symbol) EnsureNestedTypesAreLoaded() EnsureNonTypeMembersAreLoaded() Return _lazyMembers.Flatten().ConditionallyDeOrder() End Function Friend Overrides Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol) ' If there are any fields, they are at the very beginning. Return GetMembers(Of FieldSymbol)(GetMembers(), SymbolKind.Field, offset:=0) End Function Friend Overrides Iterator Function GetMethodsToEmit() As IEnumerable(Of MethodSymbol) Dim members = GetMembers() ' Get to methods. Dim index = GetIndexOfFirstMember(members, SymbolKind.Method) If Not Me.IsInterfaceType() Then While index < members.Length Dim member = members(index) If member.Kind <> SymbolKind.Method Then Exit While End If Dim method = DirectCast(member, MethodSymbol) ' Don't emit the default value type constructor - the runtime handles that If Not method.IsDefaultValueTypeConstructor() Then Yield method End If index += 1 End While Else ' We do not create symbols for v-table gap methods, let's figure out where the gaps go. If index >= members.Length OrElse members(index).Kind <> SymbolKind.Method Then ' We didn't import any methods, it is Ok to return an empty set. Return End If Dim method = DirectCast(members(index), PEMethodSymbol) Dim [module] = ContainingPEModule.Module Dim methodDefs = ArrayBuilder(Of MethodDefinitionHandle).GetInstance() Try For Each methodDef In [module].GetMethodsOfTypeOrThrow(_handle) methodDefs.Add(methodDef) Next Catch mrEx As BadImageFormatException End Try For Each methodDef In methodDefs If method.Handle = methodDef Then Yield method index += 1 If index = members.Length OrElse members(index).Kind <> SymbolKind.Method Then ' no need to return any gaps at the end. methodDefs.Free() Return End If method = DirectCast(members(index), PEMethodSymbol) Else ' Encountered a gap. Dim gapSize As Integer Try gapSize = ModuleExtensions.GetVTableGapSize([module].GetMethodDefNameOrThrow(methodDef)) Catch mrEx As BadImageFormatException gapSize = 1 End Try ' We don't have a symbol to return, so, even if the name doesn't represent a gap, we still have a gap. Do Yield Nothing gapSize -= 1 Loop While gapSize > 0 End If Next ' Ensure we explicitly returned from inside loop. Throw ExceptionUtilities.Unreachable End If End Function Friend Overrides Function GetPropertiesToEmit() As IEnumerable(Of PropertySymbol) Return GetMembers(Of PropertySymbol)(GetMembers(), SymbolKind.Property) End Function Friend Overrides Function GetEventsToEmit() As IEnumerable(Of EventSymbol) Return GetMembers(Of EventSymbol)(GetMembers(), SymbolKind.Event) End Function Private Class DeclarationOrderSymbolComparer Implements IComparer(Of ISymbol) Public Shared ReadOnly Instance As New DeclarationOrderSymbolComparer() Private Sub New() End Sub Public Function Compare(x As ISymbol, y As ISymbol) As Integer Implements IComparer(Of ISymbol).Compare If x Is y Then Return 0 End If Dim cmp As Integer = x.Kind.ToSortOrder - y.Kind.ToSortOrder If cmp <> 0 Then Return cmp End If Select Case x.Kind Case SymbolKind.Field Return HandleComparer.Default.Compare(DirectCast(x, PEFieldSymbol).Handle, DirectCast(y, PEFieldSymbol).Handle) Case SymbolKind.Method If DirectCast(x, MethodSymbol).IsDefaultValueTypeConstructor() Then Return -1 ElseIf DirectCast(y, MethodSymbol).IsDefaultValueTypeConstructor() Then Return 1 End If Return HandleComparer.Default.Compare(DirectCast(x, PEMethodSymbol).Handle, DirectCast(y, PEMethodSymbol).Handle) Case SymbolKind.Property Return HandleComparer.Default.Compare(DirectCast(x, PEPropertySymbol).Handle, DirectCast(y, PEPropertySymbol).Handle) Case SymbolKind.Event Return HandleComparer.Default.Compare(DirectCast(x, PEEventSymbol).Handle, DirectCast(y, PEEventSymbol).Handle) Case SymbolKind.NamedType Return HandleComparer.Default.Compare(DirectCast(x, PENamedTypeSymbol).Handle, DirectCast(y, PENamedTypeSymbol).Handle) Case Else Throw ExceptionUtilities.UnexpectedValue(x.Kind) End Select End Function End Class Private Sub EnsureNonTypeMembersAreLoaded() If _lazyMembers Is Nothing Then ' A method may be referenced as an accessor by one or more properties. And, ' any of those properties may be "bogus" if one of the property accessors ' does not match the property signature. If the method is referenced by at ' least one non-bogus property, then the method is created as an accessor, ' and (for purposes of error reporting if the method is referenced directly) the ' associated property is set (arbitrarily) to the first non-bogus property found ' in metadata. If the method is not referenced by any non-bogus properties, ' then the method is created as a normal method rather than an accessor. ' Create a dictionary of method symbols indexed by metadata row id ' (to allow efficient lookup when matching property accessors). Dim methodHandleToSymbol As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol) = CreateMethods() Dim members = ArrayBuilder(Of Symbol).GetInstance() Dim ensureParameterlessConstructor As Boolean = (TypeKind = TypeKind.Structure OrElse TypeKind = TypeKind.Enum) AndAlso Not IsShared For Each member In methodHandleToSymbol.Values members.Add(member) If ensureParameterlessConstructor Then ensureParameterlessConstructor = Not member.IsParameterlessConstructor() End If Next If ensureParameterlessConstructor Then members.Add(New SynthesizedConstructorSymbol(Nothing, Me, Me.IsShared, False, Nothing, Nothing)) End If ' CreateFields will add withEvent names here if there are any. ' Otherwise stays Nothing Dim withEventNames As HashSet(Of String) = Nothing CreateProperties(methodHandleToSymbol, members) CreateFields(members, withEventNames) CreateEvents(methodHandleToSymbol, members) Dim membersDict As New Dictionary(Of String, ImmutableArray(Of Symbol))(CaseInsensitiveComparison.Comparer) Dim groupedMembers = members.GroupBy(Function(m) m.Name, CaseInsensitiveComparison.Comparer) For Each g In groupedMembers membersDict.Add(g.Key, ImmutableArray.CreateRange(g)) Next members.Free() ' tell WithEvents properties that they are WithEvents properties If withEventNames IsNot Nothing Then For Each withEventName In withEventNames Dim weMembers As ImmutableArray(Of Symbol) = Nothing If membersDict.TryGetValue(withEventName, weMembers) Then ' there must be only a single match for a given WithEvents name If weMembers.Length <> 1 Then Continue For End If ' it must be a valid property Dim asProperty = TryCast(weMembers(0), PEPropertySymbol) If asProperty IsNot Nothing AndAlso IsValidWithEventsProperty(asProperty) Then asProperty.SetIsWithEvents(True) End If End If Next End If ' Merge types into members For Each typeSymbols In _lazyNestedTypes.Values Dim name = typeSymbols(0).Name Dim symbols As ImmutableArray(Of Symbol) = Nothing If Not membersDict.TryGetValue(name, symbols) Then membersDict.Add(name, StaticCast(Of Symbol).From(typeSymbols)) Else membersDict(name) = symbols.Concat(StaticCast(Of Symbol).From(typeSymbols)) End If Next Dim exchangeResult = Interlocked.CompareExchange(_lazyMembers, membersDict, Nothing) If exchangeResult Is Nothing Then Dim memberNames = SpecializedCollections.ReadOnlyCollection(membersDict.Keys) Interlocked.Exchange(Of ICollection(Of String))(_lazyMemberNames, memberNames) End If End If End Sub ''' <summary> ''' Some simple sanity checks if a property can actually be a withevents property ''' </summary> Private Function IsValidWithEventsProperty(prop As PEPropertySymbol) As Boolean ' NOTE: Dev10 does not make any checks. Just has comment that it could be a good idea to do in Whidbey. ' We will check, just to make stuff a bit more robust. ' It will be extremely rare that this function would fail though. If prop.IsReadOnly Or prop.IsWriteOnly Then Return False End If If Not prop.IsOverridable Then Return False End If Return True End Function Public Overloads Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol) EnsureNestedTypesAreLoaded() EnsureNonTypeMembersAreLoaded() Dim m As ImmutableArray(Of Symbol) = Nothing If _lazyMembers.TryGetValue(name, m) Then Return m End If Return ImmutableArray(Of Symbol).Empty End Function Friend Overrides Function GetTypeMembersUnordered() As ImmutableArray(Of NamedTypeSymbol) EnsureNestedTypesAreLoaded() Return StaticCast(Of NamedTypeSymbol).From(_lazyNestedTypes.Flatten()) End Function Public Overloads Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol) EnsureNestedTypesAreLoaded() Return StaticCast(Of NamedTypeSymbol).From(_lazyNestedTypes.Flatten(DeclarationOrderSymbolComparer.Instance)) End Function Private Sub EnsureNestedTypesAreLoaded() If _lazyNestedTypes Is Nothing Then Dim typesDict = CreateNestedTypes() Interlocked.CompareExchange(_lazyNestedTypes, typesDict, Nothing) ' Build cache of TypeDef Tokens ' Potentially this can be done in the background. If _lazyNestedTypes Is typesDict Then ContainingPEModule.OnNewTypeDeclarationsLoaded(typesDict) End If End If End Sub Public Overloads Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol) EnsureNestedTypesAreLoaded() Dim t As ImmutableArray(Of PENamedTypeSymbol) = Nothing If _lazyNestedTypes.TryGetValue(name, t) Then Return StaticCast(Of NamedTypeSymbol).From(t) End If Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overloads Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol) Return GetTypeMembers(name).WhereAsArray(Function(type, arity_) type.Arity = arity_, arity) End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return StaticCast(Of Location).From(ContainingPEModule.MetadataLocation) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Friend ReadOnly Property TypeDefFlags As TypeAttributes Get Return _flags End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get EnsureTypeParametersAreLoaded() Return _lazyTypeParameters End Get End Property Private Sub EnsureTypeParametersAreLoaded() If _lazyTypeParameters.IsDefault Then Debug.Assert(_arity > 0) Dim ownedParams(_arity - 1) As PETypeParameterSymbol Dim moduleSymbol = ContainingPEModule ' If this is a nested type generic parameters in metadata include generic parameters of the outer types. Dim firstIndex = _genericParameterHandles.Count - Arity For i = 0 To ownedParams.Length - 1 ownedParams(i) = New PETypeParameterSymbol(moduleSymbol, Me, CUShort(i), _genericParameterHandles(firstIndex + i)) Next ImmutableInterlocked.InterlockedCompareExchange(_lazyTypeParameters, StaticCast(Of TypeParameterSymbol).From(ownedParams.AsImmutableOrNull), Nothing) End If End Sub Public Overrides ReadOnly Property IsMustInherit As Boolean Get Return (_flags And TypeAttributes.Abstract) <> 0 AndAlso (_flags And TypeAttributes.Sealed) = 0 End Get End Property Friend Overrides ReadOnly Property IsMetadataAbstract As Boolean Get Return (_flags And TypeAttributes.Abstract) <> 0 End Get End Property Public Overrides ReadOnly Property IsNotInheritable As Boolean Get Return (_flags And TypeAttributes.Sealed) <> 0 End Get End Property Friend Overrides ReadOnly Property IsMetadataSealed As Boolean Get Return (_flags And TypeAttributes.Sealed) <> 0 End Get End Property Friend Overrides ReadOnly Property IsWindowsRuntimeImport As Boolean Get Return (_flags And TypeAttributes.WindowsRuntime) <> 0 End Get End Property Friend Overrides ReadOnly Property ShouldAddWinRTMembers As Boolean Get Return IsWindowsRuntimeImport End Get End Property Friend Overrides Function GetGuidString(ByRef guidString As String) As Boolean Return ContainingPEModule.Module.HasGuidAttribute(_handle, guidString) End Function Public NotOverridable Overrides ReadOnly Property MightContainExtensionMethods As Boolean Get If _lazyMightContainExtensionMethods = ThreeState.Unknown Then ' Only top level non-generic types with an Extension attribute are ' valid containers of extension methods. Dim result As Boolean = False If _container.Kind = SymbolKind.Namespace AndAlso _arity = 0 Then Dim containingModuleSymbol = Me.ContainingPEModule If containingModuleSymbol.MightContainExtensionMethods AndAlso containingModuleSymbol.Module.HasExtensionAttribute(Me._handle, ignoreCase:=True) Then result = True End If End If If result Then _lazyMightContainExtensionMethods = ThreeState.True Else _lazyMightContainExtensionMethods = ThreeState.False End If End If Return _lazyMightContainExtensionMethods = ThreeState.True End Get End Property Friend Overrides ReadOnly Property HasCodeAnalysisEmbeddedAttribute As Boolean Get If Me._lazyHasCodeAnalysisEmbeddedAttribute = ThreeState.Unknown Then Interlocked.CompareExchange( Me._lazyHasCodeAnalysisEmbeddedAttribute, Me.ContainingPEModule.Module.HasCodeAnalysisEmbeddedAttribute(Me._handle).ToThreeState(), ThreeState.Unknown) End If Return Me._lazyHasCodeAnalysisEmbeddedAttribute = ThreeState.True End Get End Property Friend Overrides ReadOnly Property HasVisualBasicEmbeddedAttribute As Boolean Get If Me._lazyHasVisualBasicEmbeddedAttribute = ThreeState.Unknown Then Interlocked.CompareExchange( Me._lazyHasVisualBasicEmbeddedAttribute, Me.ContainingPEModule.Module.HasVisualBasicEmbeddedAttribute(Me._handle).ToThreeState(), ThreeState.Unknown) End If Return Me._lazyHasVisualBasicEmbeddedAttribute = ThreeState.True End Get End Property Friend Overrides Sub BuildExtensionMethodsMap( map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)), appendThrough As NamespaceSymbol ) If Me.MightContainExtensionMethods Then EnsureNestedTypesAreLoaded() EnsureNonTypeMembersAreLoaded() If Not appendThrough.BuildExtensionMethodsMap(map, _lazyMembers) Then ' Didn't find any extension methods, record the fact. _lazyMightContainExtensionMethods = ThreeState.False End If End If End Sub Friend Overrides Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder, appendThrough As NamedTypeSymbol) If Me.MightContainExtensionMethods Then EnsureNestedTypesAreLoaded() EnsureNonTypeMembersAreLoaded() If Not appendThrough.AddExtensionMethodLookupSymbolsInfo(nameSet, options, originalBinder, _lazyMembers) Then ' Didn't find any extension methods, record the fact. _lazyMightContainExtensionMethods = ThreeState.False End If End If End Sub Public Overrides ReadOnly Property TypeKind As TypeKind Get If _lazyTypeKind = TypeKind.Unknown Then Dim result As TypeKind If (_flags And TypeAttributes.Interface) <> 0 Then result = TypeKind.Interface Else Dim base As TypeSymbol = GetDeclaredBase(Nothing) result = TypeKind.Class If base IsNot Nothing Then ' Code is cloned from MetaImport::DoImportBaseAndImplements() Dim baseCorTypeId As SpecialType = base.SpecialType If baseCorTypeId = SpecialType.System_Enum Then ' Enum result = TypeKind.Enum ElseIf baseCorTypeId = SpecialType.System_MulticastDelegate OrElse (baseCorTypeId = SpecialType.System_Delegate AndAlso Me.SpecialType <> SpecialType.System_MulticastDelegate) Then ' Delegate result = TypeKind.Delegate ElseIf (baseCorTypeId = SpecialType.System_ValueType AndAlso Me.SpecialType <> SpecialType.System_Enum) Then ' Struct result = TypeKind.Structure ElseIf Me.Arity = 0 AndAlso Me.ContainingType Is Nothing AndAlso ContainingPEModule.Module.HasAttribute(Me._handle, AttributeDescription.StandardModuleAttribute) Then result = TypeKind.Module End If End If End If _lazyTypeKind = result End If Return CType(_lazyTypeKind, TypeKind) End Get End Property Friend Overrides ReadOnly Property IsInterface As Boolean Get Return (_flags And TypeAttributes.Interface) <> 0 End Get End Property Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String ' Note: m_lazyDocComment is passed ByRef Return PEDocumentationCommentUtils.GetDocumentationComment( Me, ContainingPEModule, preferredCulture, cancellationToken, _lazyDocComment) End Function Friend Overrides ReadOnly Property IsComImport As Boolean Get Return (_flags And TypeAttributes.Import) <> 0 End Get End Property Friend Overrides ReadOnly Property CoClassType As TypeSymbol Get If _lazyCoClassType Is ErrorTypeSymbol.UnknownResultType Then Interlocked.CompareExchange(_lazyCoClassType, MakeComImportCoClassType(), DirectCast(ErrorTypeSymbol.UnknownResultType, TypeSymbol)) End If Return _lazyCoClassType End Get End Property Private Function MakeComImportCoClassType() As TypeSymbol If Not Me.IsInterface Then Return Nothing End If Dim coClassTypeName As String = Nothing If Not Me.ContainingPEModule.Module.HasStringValuedAttribute(Me._handle, AttributeDescription.CoClassAttribute, coClassTypeName) Then Return Nothing End If Dim decoder As New MetadataDecoder(Me.ContainingPEModule) Return decoder.GetTypeSymbolForSerializedType(coClassTypeName) End Function Friend Overrides ReadOnly Property DefaultPropertyName As String Get ' Unset value is Nothing. No default member is String.Empty. If _lazyDefaultPropertyName Is Nothing Then Dim memberName = GetDefaultPropertyName() Interlocked.CompareExchange(_lazyDefaultPropertyName, If(memberName, String.Empty), Nothing) End If ' Return Nothing rather than String.Empty for no default member. Return If(String.IsNullOrEmpty(_lazyDefaultPropertyName), Nothing, _lazyDefaultPropertyName) End Get End Property Private Function GetDefaultPropertyName() As String Dim memberName As String = Nothing ContainingPEModule.Module.HasDefaultMemberAttribute(Me._handle, memberName) If memberName IsNot Nothing Then For Each member In GetMembers(memberName) ' Allow Default Shared properties for consistency with Dev10. If member.Kind = SymbolKind.Property Then Return memberName End If Next End If Return Nothing End Function Private Function CreateNestedTypes() As Dictionary(Of String, ImmutableArray(Of PENamedTypeSymbol)) Dim members = ArrayBuilder(Of PENamedTypeSymbol).GetInstance() Dim moduleSymbol = Me.ContainingPEModule Dim [module] = moduleSymbol.Module Try For Each nestedTypeDef In [module].GetNestedTypeDefsOrThrow(_handle) If [module].ShouldImportNestedType(nestedTypeDef) Then members.Add(New PENamedTypeSymbol(moduleSymbol, Me, nestedTypeDef)) End If Next Catch mrEx As BadImageFormatException End Try Dim children = members.GroupBy(Function(t) t.Name, IdentifierComparison.Comparer) Dim types = New Dictionary(Of String, ImmutableArray(Of PENamedTypeSymbol))(IdentifierComparison.Comparer) For Each c In children types.Add(c.Key, c.ToArray().AsImmutableOrNull()) Next members.Free() Return types End Function Private Sub CreateFields(members As ArrayBuilder(Of Symbol), <Out()> ByRef witheventPropertyNames As HashSet(Of String)) Dim moduleSymbol = Me.ContainingPEModule Dim [module] = moduleSymbol.Module Try For Each fieldDef In [module].GetFieldsOfTypeOrThrow(_handle) Dim import As Boolean Try import = [module].ShouldImportField(fieldDef, moduleSymbol.ImportOptions) If Not import Then Select Case Me.TypeKind Case TypeKind.Structure Dim specialType = Me.SpecialType If specialType = SpecialType.None OrElse specialType = SpecialType.System_Nullable_T Then ' This is an ordinary struct If ([module].GetFieldDefFlagsOrThrow(fieldDef) And FieldAttributes.Static) = 0 Then import = True End If End If Case TypeKind.Enum If ([module].GetFieldDefFlagsOrThrow(fieldDef) And FieldAttributes.Static) = 0 Then import = True End If End Select End If Catch mrEx As BadImageFormatException End Try If import Then members.Add(New PEFieldSymbol(moduleSymbol, Me, fieldDef)) End If Dim witheventPropertyName As String = Nothing If [module].HasAccessedThroughPropertyAttribute(fieldDef, witheventPropertyName) Then ' Dev10 does not check if names are duplicated, but it does check ' that withevents names match some property name using identifier match ' So if names are duplicated they would refer to same property. ' We will just put names in a set. If witheventPropertyNames Is Nothing Then witheventPropertyNames = New HashSet(Of String)(IdentifierComparison.Comparer) End If witheventPropertyNames.Add(witheventPropertyName) End If Next Catch mrEx As BadImageFormatException End Try End Sub Private Function CreateMethods() As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol) Dim methods = New Dictionary(Of MethodDefinitionHandle, PEMethodSymbol)() Dim moduleSymbol = Me.ContainingPEModule Dim [module] = moduleSymbol.Module Try For Each methodDef In [module].GetMethodsOfTypeOrThrow(_handle) If [module].ShouldImportMethod(_handle, methodDef, moduleSymbol.ImportOptions) Then methods.Add(methodDef, New PEMethodSymbol(moduleSymbol, Me, methodDef)) End If Next Catch mrEx As BadImageFormatException End Try Return methods End Function Private Sub CreateProperties(methodHandleToSymbol As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol), members As ArrayBuilder(Of Symbol)) Dim moduleSymbol = Me.ContainingPEModule Dim [module] = moduleSymbol.Module Try For Each propertyDef In [module].GetPropertiesOfTypeOrThrow(_handle) Try Dim methods = [module].GetPropertyMethodsOrThrow(propertyDef) Dim getMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, _handle, methods.Getter) Dim setMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, _handle, methods.Setter) If (getMethod IsNot Nothing) OrElse (setMethod IsNot Nothing) Then members.Add(PEPropertySymbol.Create(moduleSymbol, Me, propertyDef, getMethod, setMethod)) End If Catch mrEx As BadImageFormatException End Try Next Catch mrEx As BadImageFormatException End Try End Sub Private Sub CreateEvents(methodHandleToSymbol As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol), members As ArrayBuilder(Of Symbol)) Dim moduleSymbol = Me.ContainingPEModule Dim [module] = moduleSymbol.Module Try For Each eventRid In [module].GetEventsOfTypeOrThrow(_handle) Try Dim methods = [module].GetEventMethodsOrThrow(eventRid) ' NOTE: C# ignores all other accessors (most notably, raise/fire). Dim addMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, _handle, methods.Adder) Dim removeMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, _handle, methods.Remover) Dim raiseMethod = GetAccessorMethod(moduleSymbol, methodHandleToSymbol, _handle, methods.Raiser) ' VB ignores events that do not have both Add and Remove. If (addMethod IsNot Nothing) AndAlso (removeMethod IsNot Nothing) Then members.Add(New PEEventSymbol(moduleSymbol, Me, eventRid, addMethod, removeMethod, raiseMethod)) End If Catch mrEx As BadImageFormatException End Try Next Catch mrEx As BadImageFormatException End Try End Sub Private Shared Function GetAccessorMethod(moduleSymbol As PEModuleSymbol, methodHandleToSymbol As Dictionary(Of MethodDefinitionHandle, PEMethodSymbol), typeDef As TypeDefinitionHandle, methodDef As MethodDefinitionHandle) As PEMethodSymbol If methodDef.IsNil Then Return Nothing End If Dim method As PEMethodSymbol = Nothing Dim found As Boolean = methodHandleToSymbol.TryGetValue(methodDef, method) Debug.Assert(found OrElse Not moduleSymbol.Module.ShouldImportMethod(typeDef, methodDef, moduleSymbol.ImportOptions)) Return method End Function Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol) Dim primaryDependency As AssemblySymbol = Me.PrimaryDependency If Not _lazyCachedUseSiteInfo.IsInitialized Then _lazyCachedUseSiteInfo.Initialize(primaryDependency, CalculateUseSiteInfoImpl()) End If Return _lazyCachedUseSiteInfo.ToUseSiteInfo(primaryDependency) End Function Private Function CalculateUseSiteInfoImpl() As UseSiteInfo(Of AssemblySymbol) Dim useSiteInfo = CalculateUseSiteInfo() If useSiteInfo.DiagnosticInfo Is Nothing Then ' Check if this type Is marked by RequiredAttribute attribute. ' If so mark the type as bad, because it relies upon semantics that are not understood by the VB compiler. If Me.ContainingPEModule.Module.HasRequiredAttributeAttribute(Me.Handle) Then Return New UseSiteInfo(Of AssemblySymbol)(ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedType1, Me)) End If Dim typeKind = Me.TypeKind Dim specialtype = Me.SpecialType If (typeKind = TypeKind.Class OrElse typeKind = TypeKind.Module) AndAlso specialtype <> SpecialType.System_Enum AndAlso specialtype <> SpecialType.System_MulticastDelegate Then Dim base As TypeSymbol = GetDeclaredBase(Nothing) If base IsNot Nothing AndAlso base.SpecialType = SpecialType.None AndAlso base.ContainingAssembly?.IsMissing Then Dim missingType = TryCast(base, MissingMetadataTypeSymbol.TopLevel) If missingType IsNot Nothing AndAlso missingType.Arity = 0 Then Dim emittedName As String = MetadataHelpers.BuildQualifiedName(missingType.NamespaceName, missingType.MetadataName) Select Case SpecialTypes.GetTypeFromMetadataName(emittedName) Case SpecialType.System_Enum, SpecialType.System_Delegate, SpecialType.System_MulticastDelegate, SpecialType.System_ValueType ' This might be a structure, an enum, or a delegate Return missingType.GetUseSiteInfo() End Select End If End If End If ' Verify type parameters for containing types ' match those on the containing types. If Not MatchesContainingTypeParameters() Then Return New UseSiteInfo(Of AssemblySymbol)(ErrorFactory.ErrorInfo(ERRID.ERR_NestingViolatesCLS1, Me)) End If End If Return useSiteInfo End Function ''' <summary> ''' Return true if the type parameters specified on the nested type (Me), ''' that represent the corresponding type parameters on the containing ''' types, in fact match the actual type parameters on the containing types. ''' </summary> Private Function MatchesContainingTypeParameters() As Boolean If _genericParameterHandles.Count = 0 Then Return True End If Dim container = ContainingType If container Is Nothing Then Return True End If Dim containingTypeParameters = container.GetAllTypeParameters() Dim n = containingTypeParameters.Length If n = 0 Then Return True End If ' Create an instance of PENamedTypeSymbol for the nested type, but ' with all type parameters, from the nested type and all containing ' types. The type parameters on this temporary type instance are used ' for comparison with those on the actual containing types. The ' containing symbol for the temporary type is the namespace directly. Dim nestedType = New PENamedTypeSymbol(ContainingPEModule, DirectCast(ContainingNamespace, PENamespaceSymbol), _handle) Dim nestedTypeParameters = nestedType.TypeParameters Dim containingTypeMap = TypeSubstitution.Create( container, containingTypeParameters, IndexedTypeParameterSymbol.Take(n).As(Of TypeSymbol)) Dim nestedTypeMap = TypeSubstitution.Create( nestedType, nestedTypeParameters, IndexedTypeParameterSymbol.Take(nestedTypeParameters.Length).As(Of TypeSymbol)) For i = 0 To n - 1 Dim containingTypeParameter = containingTypeParameters(i) Dim nestedTypeParameter = nestedTypeParameters(i) If Not MethodSignatureComparer.HaveSameConstraints( containingTypeParameter, containingTypeMap, nestedTypeParameter, nestedTypeMap) Then Return False End If Next Return True End Function ''' <summary> ''' Force all declaration errors to be generated. ''' </summary> Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) Throw ExceptionUtilities.Unreachable End Sub Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get ObsoleteAttributeHelpers.InitializeObsoleteDataFromMetadata(_lazyObsoleteAttributeData, _handle, ContainingPEModule) Return _lazyObsoleteAttributeData End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) If Me._lazyConditionalAttributeSymbols.IsDefault Then Dim conditionalSymbols As ImmutableArray(Of String) = ContainingPEModule.Module.GetConditionalAttributeValues(_handle) Debug.Assert(Not conditionalSymbols.IsDefault) ImmutableInterlocked.InterlockedCompareExchange(_lazyConditionalAttributeSymbols, conditionalSymbols, Nothing) End If Return Me._lazyConditionalAttributeSymbols End Function Friend Overrides Function GetAttributeUsageInfo() As AttributeUsageInfo If _lazyAttributeUsageInfo.IsNull Then _lazyAttributeUsageInfo = DecodeAttributeUsageInfo() End If Debug.Assert(Not _lazyAttributeUsageInfo.IsNull) Return _lazyAttributeUsageInfo End Function Private Function DecodeAttributeUsageInfo() As AttributeUsageInfo Dim attributeUsageHandle = Me.ContainingPEModule.Module.GetAttributeUsageAttributeHandle(_handle) If Not attributeUsageHandle.IsNil Then Dim decoder = New MetadataDecoder(ContainingPEModule) Dim positionalArgs As TypedConstant() = Nothing Dim namedArgs As KeyValuePair(Of String, TypedConstant)() = Nothing If decoder.GetCustomAttribute(attributeUsageHandle, positionalArgs, namedArgs) Then Return AttributeData.DecodeAttributeUsageAttribute(positionalArgs(0), namedArgs.AsImmutableOrNull()) End If End If Dim baseType = Me.BaseTypeNoUseSiteDiagnostics Return If(baseType IsNot Nothing, baseType.GetAttributeUsageInfo(), AttributeUsageInfo.Default) End Function Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean Get If _lazyIsExtensibleInterface = ThreeState.Unknown Then _lazyIsExtensibleInterface = DecodeIsExtensibleInterface().ToThreeState() End If Return _lazyIsExtensibleInterface.Value End Get End Property Private Function DecodeIsExtensibleInterface() As Boolean If Me.IsInterfaceType() Then If Me.HasAttributeForExtensibleInterface() Then Return True End If For Each [interface] In Me.AllInterfacesNoUseSiteDiagnostics If [interface].IsExtensibleInterfaceNoUseSiteDiagnostics Then Return True End If Next End If Return False End Function Private Function HasAttributeForExtensibleInterface() As Boolean Dim metadataModule = Me.ContainingPEModule.Module ' Is interface marked with 'TypeLibTypeAttribute( flags w/o TypeLibTypeFlags.FNonExtensible )' attribute Dim flags As Cci.TypeLibTypeFlags = Nothing If metadataModule.HasTypeLibTypeAttribute(Me._handle, flags) AndAlso (flags And Cci.TypeLibTypeFlags.FNonExtensible) = 0 Then Return True End If ' Is interface marked with 'InterfaceTypeAttribute( flags with ComInterfaceType.InterfaceIsIDispatch )' attribute Dim interfaceType As ComInterfaceType = Nothing If metadataModule.HasInterfaceTypeAttribute(Me._handle, interfaceType) AndAlso (interfaceType And Cci.Constants.ComInterfaceType_InterfaceIsIDispatch) <> 0 Then Return True End If Return False End Function ''' <remarks> ''' This is for perf, not for correctness. ''' </remarks> Friend NotOverridable Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation Get Return Nothing End Get End Property ''' <summary> ''' Returns the index of the first member of the specific kind. ''' Returns the number of members if not found. ''' </summary> Private Shared Function GetIndexOfFirstMember(members As ImmutableArray(Of Symbol), kind As SymbolKind) As Integer Dim n = members.Length For i = 0 To n - 1 If members(i).Kind = kind Then Return i End If Next Return n End Function ''' <summary> ''' Returns all members of the specific kind, starting at the optional offset. ''' Members of the same kind are assumed to be contiguous. ''' </summary> Private Overloads Shared Iterator Function GetMembers(Of TSymbol As Symbol)(members As ImmutableArray(Of Symbol), kind As SymbolKind, Optional offset As Integer = -1) As IEnumerable(Of TSymbol) If offset < 0 Then offset = GetIndexOfFirstMember(members, kind) End If Dim n = members.Length For i = offset To n - 1 Dim member = members(i) If member.Kind <> kind Then Return End If Yield DirectCast(member, TSymbol) Next End Function Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() 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/Analyzers/CSharp/Analyzers/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementDiagnosticAnalyzer.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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.NewLines.ConstructorInitializerPlacement { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class ConstructorInitializerPlacementDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public ConstructorInitializerPlacementDiagnosticAnalyzer() : base(IDEDiagnosticIds.ConstructorInitializerPlacementDiagnosticId, EnforceOnBuildValues.ConsecutiveBracePlacement, CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, LanguageNames.CSharp, new LocalizableResourceString( nameof(CSharpAnalyzersResources.Blank_line_not_allowed_after_constructor_initializer_colon), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxTreeAction(AnalyzeTree); private void AnalyzeTree(SyntaxTreeAnalysisContext context) { var option = context.GetOption(CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer); if (option.Value) return; Recurse(context, option.Notification.Severity, context.Tree.GetRoot(context.CancellationToken)); } private void Recurse(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode node) { context.CancellationToken.ThrowIfCancellationRequested(); // Don't bother analyzing nodes that have syntax errors in them. if (node.ContainsDiagnostics) return; if (node is ConstructorInitializerSyntax initializer) ProcessConstructorInitializer(context, severity, initializer); foreach (var child in node.ChildNodesAndTokens()) { if (child.IsNode) Recurse(context, severity, child.AsNode()!); } } private void ProcessConstructorInitializer( SyntaxTreeAnalysisContext context, ReportDiagnostic severity, ConstructorInitializerSyntax initializer) { var sourceText = context.Tree.GetText(context.CancellationToken); var colonToken = initializer.ColonToken; var thisOrBaseKeyword = initializer.ThisOrBaseKeyword; var colonLine = sourceText.Lines.GetLineFromPosition(colonToken.SpanStart); var thisBaseLine = sourceText.Lines.GetLineFromPosition(thisOrBaseKeyword.SpanStart); if (colonLine == thisBaseLine) return; if (colonToken.TrailingTrivia.Count == 0) return; if (colonToken.TrailingTrivia.Last().Kind() != SyntaxKind.EndOfLineTrivia) return; if (colonToken.TrailingTrivia.Any(t => !t.IsWhitespaceOrEndOfLine())) return; if (thisOrBaseKeyword.LeadingTrivia.Any(t => !t.IsWhitespaceOrEndOfLine() && !t.IsSingleOrMultiLineComment())) return; context.ReportDiagnostic(DiagnosticHelper.Create( this.Descriptor, colonToken.GetLocation(), severity, additionalLocations: ImmutableArray.Create(initializer.GetLocation()), properties: null)); } } }
// 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.NewLines.ConstructorInitializerPlacement { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class ConstructorInitializerPlacementDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public ConstructorInitializerPlacementDiagnosticAnalyzer() : base(IDEDiagnosticIds.ConstructorInitializerPlacementDiagnosticId, EnforceOnBuildValues.ConsecutiveBracePlacement, CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, LanguageNames.CSharp, new LocalizableResourceString( nameof(CSharpAnalyzersResources.Blank_line_not_allowed_after_constructor_initializer_colon), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxTreeAction(AnalyzeTree); private void AnalyzeTree(SyntaxTreeAnalysisContext context) { var option = context.GetOption(CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer); if (option.Value) return; Recurse(context, option.Notification.Severity, context.Tree.GetRoot(context.CancellationToken)); } private void Recurse(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode node) { context.CancellationToken.ThrowIfCancellationRequested(); // Don't bother analyzing nodes that have syntax errors in them. if (node.ContainsDiagnostics) return; if (node is ConstructorInitializerSyntax initializer) ProcessConstructorInitializer(context, severity, initializer); foreach (var child in node.ChildNodesAndTokens()) { if (child.IsNode) Recurse(context, severity, child.AsNode()!); } } private void ProcessConstructorInitializer( SyntaxTreeAnalysisContext context, ReportDiagnostic severity, ConstructorInitializerSyntax initializer) { var sourceText = context.Tree.GetText(context.CancellationToken); var colonToken = initializer.ColonToken; var thisOrBaseKeyword = initializer.ThisOrBaseKeyword; var colonLine = sourceText.Lines.GetLineFromPosition(colonToken.SpanStart); var thisBaseLine = sourceText.Lines.GetLineFromPosition(thisOrBaseKeyword.SpanStart); if (colonLine == thisBaseLine) return; if (colonToken.TrailingTrivia.Count == 0) return; if (colonToken.TrailingTrivia.Last().Kind() != SyntaxKind.EndOfLineTrivia) return; if (colonToken.TrailingTrivia.Any(t => !t.IsWhitespaceOrEndOfLine())) return; if (thisOrBaseKeyword.LeadingTrivia.Any(t => !t.IsWhitespaceOrEndOfLine() && !t.IsSingleOrMultiLineComment())) return; context.ReportDiagnostic(DiagnosticHelper.Create( this.Descriptor, colonToken.GetLocation(), severity, additionalLocations: ImmutableArray.Create(initializer.GetLocation()), properties: null)); } } }
-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/CodeGeneration/Symbols/CodeGenerationConstructorInfo.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.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationConstructorInfo { private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationConstructorInfo> s_constructorToInfoMap = new(); private readonly bool _isPrimaryConstructor; private readonly bool _isUnsafe; private readonly string _typeName; private readonly ImmutableArray<SyntaxNode> _baseConstructorArguments; private readonly ImmutableArray<SyntaxNode> _thisConstructorArguments; private readonly ImmutableArray<SyntaxNode> _statements; private CodeGenerationConstructorInfo( bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { _isPrimaryConstructor = isPrimaryConstructor; _isUnsafe = isUnsafe; _typeName = typeName; _statements = statements; _baseConstructorArguments = baseConstructorArguments; _thisConstructorArguments = thisConstructorArguments; } public static void Attach( IMethodSymbol constructor, bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { var info = new CodeGenerationConstructorInfo(isPrimaryConstructor, isUnsafe, typeName, statements, baseConstructorArguments, thisConstructorArguments); s_constructorToInfoMap.Add(constructor, info); } private static CodeGenerationConstructorInfo? GetInfo(IMethodSymbol method) { s_constructorToInfoMap.TryGetValue(method, out var info); return info; } public static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(IMethodSymbol constructor) => GetThisConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(IMethodSymbol constructor) => GetBaseConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol constructor) => GetStatements(GetInfo(constructor)); public static string GetTypeName(IMethodSymbol constructor) => GetTypeName(GetInfo(constructor), constructor); public static bool GetIsUnsafe(IMethodSymbol constructor) => GetIsUnsafe(GetInfo(constructor)); public static bool GetIsPrimaryConstructor(IMethodSymbol constructor) => GetIsPrimaryConstructor(GetInfo(constructor)); private static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._thisConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._baseConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationConstructorInfo? info) => info?._statements ?? default; private static string GetTypeName(CodeGenerationConstructorInfo? info, IMethodSymbol constructor) => info == null ? constructor.ContainingType.Name : info._typeName; private static bool GetIsUnsafe(CodeGenerationConstructorInfo? info) => info?._isUnsafe ?? false; private static bool GetIsPrimaryConstructor(CodeGenerationConstructorInfo? info) => info?._isPrimaryConstructor ?? 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.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationConstructorInfo { private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationConstructorInfo> s_constructorToInfoMap = new(); private readonly bool _isPrimaryConstructor; private readonly bool _isUnsafe; private readonly string _typeName; private readonly ImmutableArray<SyntaxNode> _baseConstructorArguments; private readonly ImmutableArray<SyntaxNode> _thisConstructorArguments; private readonly ImmutableArray<SyntaxNode> _statements; private CodeGenerationConstructorInfo( bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { _isPrimaryConstructor = isPrimaryConstructor; _isUnsafe = isUnsafe; _typeName = typeName; _statements = statements; _baseConstructorArguments = baseConstructorArguments; _thisConstructorArguments = thisConstructorArguments; } public static void Attach( IMethodSymbol constructor, bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { var info = new CodeGenerationConstructorInfo(isPrimaryConstructor, isUnsafe, typeName, statements, baseConstructorArguments, thisConstructorArguments); s_constructorToInfoMap.Add(constructor, info); } private static CodeGenerationConstructorInfo? GetInfo(IMethodSymbol method) { s_constructorToInfoMap.TryGetValue(method, out var info); return info; } public static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(IMethodSymbol constructor) => GetThisConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(IMethodSymbol constructor) => GetBaseConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol constructor) => GetStatements(GetInfo(constructor)); public static string GetTypeName(IMethodSymbol constructor) => GetTypeName(GetInfo(constructor), constructor); public static bool GetIsUnsafe(IMethodSymbol constructor) => GetIsUnsafe(GetInfo(constructor)); public static bool GetIsPrimaryConstructor(IMethodSymbol constructor) => GetIsPrimaryConstructor(GetInfo(constructor)); private static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._thisConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._baseConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationConstructorInfo? info) => info?._statements ?? default; private static string GetTypeName(CodeGenerationConstructorInfo? info, IMethodSymbol constructor) => info == null ? constructor.ContainingType.Name : info._typeName; private static bool GetIsUnsafe(CodeGenerationConstructorInfo? info) => info?._isUnsafe ?? false; private static bool GetIsPrimaryConstructor(CodeGenerationConstructorInfo? info) => info?._isPrimaryConstructor ?? 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/VisualBasic/Portable/CodeGeneration/ParameterGenerator.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 Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Class ParameterGenerator Public Shared Function GenerateParameterList(parameterDefinitions As ImmutableArray(Of IParameterSymbol), options As CodeGenerationOptions) As ParameterListSyntax Return GenerateParameterList(DirectCast(parameterDefinitions, IList(Of IParameterSymbol)), options) End Function Public Shared Function GenerateParameterList(parameterDefinitions As IEnumerable(Of IParameterSymbol), options As CodeGenerationOptions) As ParameterListSyntax Dim result = New List(Of ParameterSyntax)() Dim seenOptional = False For Each p In parameterDefinitions Dim generated = GenerateParameter(p, seenOptional, options) result.Add(generated) seenOptional = seenOptional OrElse generated.Default IsNot Nothing Next Return SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(result)) End Function Friend Shared Function GenerateParameter(parameter As IParameterSymbol, seenOptional As Boolean, options As CodeGenerationOptions) As ParameterSyntax Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of ParameterSyntax)(parameter, options) If reusableSyntax IsNot Nothing Then Return reusableSyntax End If ' TODO(cyrusn): Should we provide some way to disable this special case? ' If the type is actually an array, then we place the array specifier on the identifier, ' not on the type syntax. If parameter.Type.IsArrayType() Then Dim arrayType = DirectCast(parameter.Type, IArrayTypeSymbol) Dim elementType = arrayType.ElementType If Not elementType.IsArrayType() AndAlso elementType.OriginalDefinition.SpecialType <> SpecialType.System_Nullable_T Then Dim arguments = Enumerable.Repeat(Of ArgumentSyntax)(SyntaxFactory.OmittedArgument(), arrayType.Rank) Dim argumentList = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments)) Return SyntaxFactory.Parameter( AttributeGenerator.GenerateAttributeBlocks(parameter.GetAttributes(), options), GenerateModifiers(parameter, seenOptional), parameter.Name.ToModifiedIdentifier.WithArrayBounds(argumentList), SyntaxFactory.SimpleAsClause(type:=elementType.GenerateTypeSyntax()), GenerateEqualsValue(parameter, seenOptional)) End If End If Dim asClause = If(parameter.Type Is Nothing, Nothing, SyntaxFactory.SimpleAsClause(type:=parameter.Type.GenerateTypeSyntax())) Return SyntaxFactory.Parameter( AttributeGenerator.GenerateAttributeBlocks(parameter.GetAttributes(), options), GenerateModifiers(parameter, seenOptional), parameter.Name.ToModifiedIdentifier(), asClause, GenerateEqualsValue(parameter, seenOptional)) End Function Private Shared Function GenerateModifiers(parameter As IParameterSymbol, seenOptional As Boolean) As SyntaxTokenList If parameter.IsParams Then Return SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ParamArrayKeyword)) End If Dim modifiers = SyntaxFactory.TokenList() If parameter.IsRefOrOut() Then modifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.ByRefKeyword)) End If If parameter.IsOptional OrElse seenOptional Then modifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.OptionalKeyword)) End If Return modifiers End Function Private Shared Function GenerateEqualsValue(parameter As IParameterSymbol, seenOptional As Boolean) As EqualsValueSyntax If parameter.HasExplicitDefaultValue OrElse parameter.IsOptional OrElse seenOptional Then Return SyntaxFactory.EqualsValue( ExpressionGenerator.GenerateExpression( parameter.Type, If(parameter.HasExplicitDefaultValue, parameter.ExplicitDefaultValue, Nothing), canUseFieldReference:=True)) End If Return Nothing 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 Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Class ParameterGenerator Public Shared Function GenerateParameterList(parameterDefinitions As ImmutableArray(Of IParameterSymbol), options As CodeGenerationOptions) As ParameterListSyntax Return GenerateParameterList(DirectCast(parameterDefinitions, IList(Of IParameterSymbol)), options) End Function Public Shared Function GenerateParameterList(parameterDefinitions As IEnumerable(Of IParameterSymbol), options As CodeGenerationOptions) As ParameterListSyntax Dim result = New List(Of ParameterSyntax)() Dim seenOptional = False For Each p In parameterDefinitions Dim generated = GenerateParameter(p, seenOptional, options) result.Add(generated) seenOptional = seenOptional OrElse generated.Default IsNot Nothing Next Return SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(result)) End Function Friend Shared Function GenerateParameter(parameter As IParameterSymbol, seenOptional As Boolean, options As CodeGenerationOptions) As ParameterSyntax Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of ParameterSyntax)(parameter, options) If reusableSyntax IsNot Nothing Then Return reusableSyntax End If ' TODO(cyrusn): Should we provide some way to disable this special case? ' If the type is actually an array, then we place the array specifier on the identifier, ' not on the type syntax. If parameter.Type.IsArrayType() Then Dim arrayType = DirectCast(parameter.Type, IArrayTypeSymbol) Dim elementType = arrayType.ElementType If Not elementType.IsArrayType() AndAlso elementType.OriginalDefinition.SpecialType <> SpecialType.System_Nullable_T Then Dim arguments = Enumerable.Repeat(Of ArgumentSyntax)(SyntaxFactory.OmittedArgument(), arrayType.Rank) Dim argumentList = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments)) Return SyntaxFactory.Parameter( AttributeGenerator.GenerateAttributeBlocks(parameter.GetAttributes(), options), GenerateModifiers(parameter, seenOptional), parameter.Name.ToModifiedIdentifier.WithArrayBounds(argumentList), SyntaxFactory.SimpleAsClause(type:=elementType.GenerateTypeSyntax()), GenerateEqualsValue(parameter, seenOptional)) End If End If Dim asClause = If(parameter.Type Is Nothing, Nothing, SyntaxFactory.SimpleAsClause(type:=parameter.Type.GenerateTypeSyntax())) Return SyntaxFactory.Parameter( AttributeGenerator.GenerateAttributeBlocks(parameter.GetAttributes(), options), GenerateModifiers(parameter, seenOptional), parameter.Name.ToModifiedIdentifier(), asClause, GenerateEqualsValue(parameter, seenOptional)) End Function Private Shared Function GenerateModifiers(parameter As IParameterSymbol, seenOptional As Boolean) As SyntaxTokenList If parameter.IsParams Then Return SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ParamArrayKeyword)) End If Dim modifiers = SyntaxFactory.TokenList() If parameter.IsRefOrOut() Then modifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.ByRefKeyword)) End If If parameter.IsOptional OrElse seenOptional Then modifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.OptionalKeyword)) End If Return modifiers End Function Private Shared Function GenerateEqualsValue(parameter As IParameterSymbol, seenOptional As Boolean) As EqualsValueSyntax If parameter.HasExplicitDefaultValue OrElse parameter.IsOptional OrElse seenOptional Then Return SyntaxFactory.EqualsValue( ExpressionGenerator.GenerateExpression( parameter.Type, If(parameter.HasExplicitDefaultValue, parameter.ExplicitDefaultValue, Nothing), canUseFieldReference:=True)) End If Return Nothing 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/Portable/InternalUtilities/IsExternalInit.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. // Copied from: // https://github.com/dotnet/runtime/blob/218ef0f7776c2c20f6c594e3475b80f1fe2d7d08/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/IsExternalInit.cs using System.ComponentModel; namespace System.Runtime.CompilerServices { /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This class should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } }
// 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. // Copied from: // https://github.com/dotnet/runtime/blob/218ef0f7776c2c20f6c594e3475b80f1fe2d7d08/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/IsExternalInit.cs using System.ComponentModel; namespace System.Runtime.CompilerServices { /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This class should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } }
-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/Core/Source/ExpressionCompiler/DkmExceptionUtilities.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.Debugging { internal static partial class DkmExceptionUtilities { internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000b); internal const int CORDBG_E_MISSING_METADATA = unchecked((int)0x80131c35); internal static bool IsBadOrMissingMetadataException(Exception e) { return e is ObjectDisposedException || e.HResult == COR_E_BADIMAGEFORMAT || e.HResult == CORDBG_E_MISSING_METADATA; } } }
// 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.Debugging { internal static partial class DkmExceptionUtilities { internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000b); internal const int CORDBG_E_MISSING_METADATA = unchecked((int)0x80131c35); internal static bool IsBadOrMissingMetadataException(Exception e) { return e is ObjectDisposedException || e.HResult == COR_E_BADIMAGEFORMAT || e.HResult == CORDBG_E_MISSING_METADATA; } } }
-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_ForStatement.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitForStatement(BoundForStatement node) { Debug.Assert(node != null); var rewrittenInitializer = VisitStatement(node.Initializer); var rewrittenCondition = VisitExpression(node.Condition); var rewrittenIncrement = VisitStatement(node.Increment); var rewrittenBody = VisitStatement(node.Body); Debug.Assert(rewrittenBody is { }); // EnC: We need to insert a hidden sequence point to handle function remapping in case // the containing method is edited while methods invoked in the condition are being executed. if (rewrittenCondition != null && this.Instrument) { rewrittenCondition = _instrumenter.InstrumentForStatementCondition(node, rewrittenCondition, _factory); } return RewriteForStatement( node, rewrittenInitializer, rewrittenCondition, rewrittenIncrement, rewrittenBody); } private BoundStatement RewriteForStatementWithoutInnerLocals( BoundLoopStatement original, ImmutableArray<LocalSymbol> outerLocals, BoundStatement? rewrittenInitializer, BoundExpression? rewrittenCondition, BoundStatement? rewrittenIncrement, BoundStatement rewrittenBody, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors) { Debug.Assert(original.Kind == BoundKind.ForStatement || original.Kind == BoundKind.ForEachStatement); Debug.Assert(rewrittenBody != null); // The sequence point behavior exhibited here is different from that of the native compiler. In the native // compiler, if you have something like // // for([|int i = 0, j = 0|]; ; [|i++, j++|]) // // then all the initializers are treated as a single sequence point, as are // all the loop incrementors. // // We now make each one individually a sequence point: // // for([|int i = 0|], [|j = 0|]; ; [|i++|], [|j++|]) // // If we decide that we want to preserve the native compiler stepping behavior // then we'll need to be a bit fancy here. The initializer and increment statements // can contain lambdas whose bodies need to have sequence points inserted, so we // need to make sure we visit the children. But we'll also need to make sure that // we do not generate one sequence point for each statement in the initializers // and the incrementors. SyntaxNode syntax = original.Syntax; var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance(); if (rewrittenInitializer != null) { statementBuilder.Add(rewrittenInitializer); } var startLabel = new GeneratedLabelSymbol("start"); // for (initializer; condition; increment) // body; // // becomes the following (with block added for locals) // // { // initializer; // goto end; // start: // body; // continue: // increment; // end: // GotoIfTrue condition start; // break: // } var endLabel = new GeneratedLabelSymbol("end"); // initializer; // goto end; BoundStatement gotoEnd = new BoundGotoStatement(syntax, endLabel); if (this.Instrument) { // Mark the initial jump as hidden. // We do it to tell that this is not a part of previous statement. // This jump may be a target of another jump (for example if loops are nested) and that will make // impression of the previous statement being re-executed gotoEnd = BoundSequencePoint.CreateHidden(gotoEnd); } statementBuilder.Add(gotoEnd); // start: // body; statementBuilder.Add(new BoundLabelStatement(syntax, startLabel)); statementBuilder.Add(rewrittenBody); // continue: // increment; statementBuilder.Add(new BoundLabelStatement(syntax, continueLabel)); if (rewrittenIncrement != null) { statementBuilder.Add(rewrittenIncrement); } // end: // GotoIfTrue condition start; statementBuilder.Add(new BoundLabelStatement(syntax, endLabel)); BoundStatement? branchBack = null; if (rewrittenCondition != null) { branchBack = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, true, startLabel); } else { branchBack = new BoundGotoStatement(syntax, startLabel); } if (this.Instrument) { switch (original.Kind) { case BoundKind.ForEachStatement: branchBack = _instrumenter.InstrumentForEachStatementConditionalGotoStart((BoundForEachStatement)original, branchBack); break; case BoundKind.ForStatement: branchBack = _instrumenter.InstrumentForStatementConditionalGotoStartOrBreak((BoundForStatement)original, branchBack); break; default: throw ExceptionUtilities.UnexpectedValue(original.Kind); } } statementBuilder.Add(branchBack); // break: statementBuilder.Add(new BoundLabelStatement(syntax, breakLabel)); var statements = statementBuilder.ToImmutableAndFree(); return new BoundBlock(syntax, outerLocals, statements, hasErrors); } private BoundStatement RewriteForStatement( BoundForStatement node, BoundStatement? rewrittenInitializer, BoundExpression? rewrittenCondition, BoundStatement? rewrittenIncrement, BoundStatement rewrittenBody) { if (node.InnerLocals.IsEmpty) { return RewriteForStatementWithoutInnerLocals( node, node.OuterLocals, rewrittenInitializer, rewrittenCondition, rewrittenIncrement, rewrittenBody, node.BreakLabel, node.ContinueLabel, node.HasErrors); } // We need to enter inner_scope-block from the top, that is where an instance of a display class will be created // if any local is captured within a lambda. // for (initializer; condition; increment) // body; // // becomes the following (with block added for locals) // // { // initializer; // start: // { // GotoIfFalse condition break; // body; // continue: // increment; // goto start; // } // break: // } Debug.Assert(rewrittenBody != null); SyntaxNode syntax = node.Syntax; var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance(); // initializer; if (rewrittenInitializer != null) { statementBuilder.Add(rewrittenInitializer); } var startLabel = new GeneratedLabelSymbol("start"); // start: BoundStatement startLabelStatement = new BoundLabelStatement(syntax, startLabel); if (Instrument) { startLabelStatement = BoundSequencePoint.CreateHidden(startLabelStatement); } statementBuilder.Add(startLabelStatement); var blockBuilder = ArrayBuilder<BoundStatement>.GetInstance(); // GotoIfFalse condition break; if (rewrittenCondition != null) { BoundStatement ifNotConditionGotoBreak = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, false, node.BreakLabel); if (this.Instrument) { ifNotConditionGotoBreak = _instrumenter.InstrumentForStatementConditionalGotoStartOrBreak(node, ifNotConditionGotoBreak); } blockBuilder.Add(ifNotConditionGotoBreak); } // body; blockBuilder.Add(rewrittenBody); // continue: // increment; blockBuilder.Add(new BoundLabelStatement(syntax, node.ContinueLabel)); if (rewrittenIncrement != null) { blockBuilder.Add(rewrittenIncrement); } // goto start; blockBuilder.Add(new BoundGotoStatement(syntax, startLabel)); statementBuilder.Add(new BoundBlock(syntax, node.InnerLocals, blockBuilder.ToImmutableAndFree())); // break: statementBuilder.Add(new BoundLabelStatement(syntax, node.BreakLabel)); var statements = statementBuilder.ToImmutableAndFree(); return new BoundBlock(syntax, node.OuterLocals, statements, node.HasErrors); } } }
// 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitForStatement(BoundForStatement node) { Debug.Assert(node != null); var rewrittenInitializer = VisitStatement(node.Initializer); var rewrittenCondition = VisitExpression(node.Condition); var rewrittenIncrement = VisitStatement(node.Increment); var rewrittenBody = VisitStatement(node.Body); Debug.Assert(rewrittenBody is { }); // EnC: We need to insert a hidden sequence point to handle function remapping in case // the containing method is edited while methods invoked in the condition are being executed. if (rewrittenCondition != null && this.Instrument) { rewrittenCondition = _instrumenter.InstrumentForStatementCondition(node, rewrittenCondition, _factory); } return RewriteForStatement( node, rewrittenInitializer, rewrittenCondition, rewrittenIncrement, rewrittenBody); } private BoundStatement RewriteForStatementWithoutInnerLocals( BoundLoopStatement original, ImmutableArray<LocalSymbol> outerLocals, BoundStatement? rewrittenInitializer, BoundExpression? rewrittenCondition, BoundStatement? rewrittenIncrement, BoundStatement rewrittenBody, GeneratedLabelSymbol breakLabel, GeneratedLabelSymbol continueLabel, bool hasErrors) { Debug.Assert(original.Kind == BoundKind.ForStatement || original.Kind == BoundKind.ForEachStatement); Debug.Assert(rewrittenBody != null); // The sequence point behavior exhibited here is different from that of the native compiler. In the native // compiler, if you have something like // // for([|int i = 0, j = 0|]; ; [|i++, j++|]) // // then all the initializers are treated as a single sequence point, as are // all the loop incrementors. // // We now make each one individually a sequence point: // // for([|int i = 0|], [|j = 0|]; ; [|i++|], [|j++|]) // // If we decide that we want to preserve the native compiler stepping behavior // then we'll need to be a bit fancy here. The initializer and increment statements // can contain lambdas whose bodies need to have sequence points inserted, so we // need to make sure we visit the children. But we'll also need to make sure that // we do not generate one sequence point for each statement in the initializers // and the incrementors. SyntaxNode syntax = original.Syntax; var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance(); if (rewrittenInitializer != null) { statementBuilder.Add(rewrittenInitializer); } var startLabel = new GeneratedLabelSymbol("start"); // for (initializer; condition; increment) // body; // // becomes the following (with block added for locals) // // { // initializer; // goto end; // start: // body; // continue: // increment; // end: // GotoIfTrue condition start; // break: // } var endLabel = new GeneratedLabelSymbol("end"); // initializer; // goto end; BoundStatement gotoEnd = new BoundGotoStatement(syntax, endLabel); if (this.Instrument) { // Mark the initial jump as hidden. // We do it to tell that this is not a part of previous statement. // This jump may be a target of another jump (for example if loops are nested) and that will make // impression of the previous statement being re-executed gotoEnd = BoundSequencePoint.CreateHidden(gotoEnd); } statementBuilder.Add(gotoEnd); // start: // body; statementBuilder.Add(new BoundLabelStatement(syntax, startLabel)); statementBuilder.Add(rewrittenBody); // continue: // increment; statementBuilder.Add(new BoundLabelStatement(syntax, continueLabel)); if (rewrittenIncrement != null) { statementBuilder.Add(rewrittenIncrement); } // end: // GotoIfTrue condition start; statementBuilder.Add(new BoundLabelStatement(syntax, endLabel)); BoundStatement? branchBack = null; if (rewrittenCondition != null) { branchBack = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, true, startLabel); } else { branchBack = new BoundGotoStatement(syntax, startLabel); } if (this.Instrument) { switch (original.Kind) { case BoundKind.ForEachStatement: branchBack = _instrumenter.InstrumentForEachStatementConditionalGotoStart((BoundForEachStatement)original, branchBack); break; case BoundKind.ForStatement: branchBack = _instrumenter.InstrumentForStatementConditionalGotoStartOrBreak((BoundForStatement)original, branchBack); break; default: throw ExceptionUtilities.UnexpectedValue(original.Kind); } } statementBuilder.Add(branchBack); // break: statementBuilder.Add(new BoundLabelStatement(syntax, breakLabel)); var statements = statementBuilder.ToImmutableAndFree(); return new BoundBlock(syntax, outerLocals, statements, hasErrors); } private BoundStatement RewriteForStatement( BoundForStatement node, BoundStatement? rewrittenInitializer, BoundExpression? rewrittenCondition, BoundStatement? rewrittenIncrement, BoundStatement rewrittenBody) { if (node.InnerLocals.IsEmpty) { return RewriteForStatementWithoutInnerLocals( node, node.OuterLocals, rewrittenInitializer, rewrittenCondition, rewrittenIncrement, rewrittenBody, node.BreakLabel, node.ContinueLabel, node.HasErrors); } // We need to enter inner_scope-block from the top, that is where an instance of a display class will be created // if any local is captured within a lambda. // for (initializer; condition; increment) // body; // // becomes the following (with block added for locals) // // { // initializer; // start: // { // GotoIfFalse condition break; // body; // continue: // increment; // goto start; // } // break: // } Debug.Assert(rewrittenBody != null); SyntaxNode syntax = node.Syntax; var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance(); // initializer; if (rewrittenInitializer != null) { statementBuilder.Add(rewrittenInitializer); } var startLabel = new GeneratedLabelSymbol("start"); // start: BoundStatement startLabelStatement = new BoundLabelStatement(syntax, startLabel); if (Instrument) { startLabelStatement = BoundSequencePoint.CreateHidden(startLabelStatement); } statementBuilder.Add(startLabelStatement); var blockBuilder = ArrayBuilder<BoundStatement>.GetInstance(); // GotoIfFalse condition break; if (rewrittenCondition != null) { BoundStatement ifNotConditionGotoBreak = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, false, node.BreakLabel); if (this.Instrument) { ifNotConditionGotoBreak = _instrumenter.InstrumentForStatementConditionalGotoStartOrBreak(node, ifNotConditionGotoBreak); } blockBuilder.Add(ifNotConditionGotoBreak); } // body; blockBuilder.Add(rewrittenBody); // continue: // increment; blockBuilder.Add(new BoundLabelStatement(syntax, node.ContinueLabel)); if (rewrittenIncrement != null) { blockBuilder.Add(rewrittenIncrement); } // goto start; blockBuilder.Add(new BoundGotoStatement(syntax, startLabel)); statementBuilder.Add(new BoundBlock(syntax, node.InnerLocals, blockBuilder.ToImmutableAndFree())); // break: statementBuilder.Add(new BoundLabelStatement(syntax, node.BreakLabel)); var statements = statementBuilder.ToImmutableAndFree(); return new BoundBlock(syntax, node.OuterLocals, statements, node.HasErrors); } } }
-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/Test/Emit/PDB/PortablePdbTests.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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Security.Cryptography; using System.Text; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PortablePdbTests : CSharpPDBTestBase { [Fact] public void SequencePointBlob() { string source = @" class C { public static void Main() { if (F()) { System.Console.WriteLine(1); } } public static bool F() => false; } "; var c = CreateCompilation(source, options: TestOptions.DebugDll); var pdbStream = new MemoryStream(); var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream); using (var peReader = new PEReader(peBlob)) using (var pdbMetadata = new PinnedMetadata(pdbStream.ToImmutable())) { var mdReader = peReader.GetMetadataReader(); var pdbReader = pdbMetadata.Reader; foreach (var methodHandle in mdReader.MethodDefinitions) { var method = mdReader.GetMethodDefinition(methodHandle); var methodDebugInfo = pdbReader.GetMethodDebugInformation(methodHandle); var name = mdReader.GetString(method.Name); TextWriter writer = new StringWriter(); foreach (var sp in methodDebugInfo.GetSequencePoints()) { if (sp.IsHidden) { writer.WriteLine($"{sp.Offset}: <hidden>"); } else { writer.WriteLine($"{sp.Offset}: ({sp.StartLine},{sp.StartColumn})-({sp.EndLine},{sp.EndColumn})"); } } var spString = writer.ToString(); var spBlob = pdbReader.GetBlobBytes(methodDebugInfo.SequencePointsBlob); switch (name) { case "Main": AssertEx.AssertEqualToleratingWhitespaceDifferences(@" 0: (5,5)-(5,6) 1: (6,9)-(6,17) 7: <hidden> 10: (7,9)-(7,10) 11: (8,13)-(8,41) 18: (9,9)-(9,10) 19: (10,5)-(10,6) ", spString); AssertEx.Equal(new byte[] { 0x01, // local signature 0x00, // IL offset 0x00, // Delta Lines 0x01, // Delta Columns 0x05, // Start Line 0x05, // Start Column 0x01, // delta IL offset 0x00, // Delta Lines 0x08, // Delta Columns 0x02, // delta Start Line (signed compressed) 0x08, // delta Start Column (signed compressed) 0x06, // delta IL offset 0x00, // hidden 0x00, // hidden 0x03, // delta IL offset 0x00, // Delta Lines 0x01, // Delta Columns 0x02, // delta Start Line (signed compressed) 0x00, // delta Start Column (signed compressed) 0x01, // delta IL offset 0x00, // Delta Lines 0x1C, // Delta Columns 0x02, // delta Start Line (signed compressed) 0x08, // delta Start Column (signed compressed) 0x07, // delta IL offset 0x00, // Delta Lines 0x01, // Delta Columns 0x02, // delta Start Line (signed compressed) 0x79, // delta Start Column (signed compressed) 0x01, // delta IL offset 0x00, // Delta Lines 0x01, // Delta Columns 0x02, // delta Start Line (signed compressed) 0x79, // delta Start Column (signed compressed) }, spBlob); break; case "F": AssertEx.AssertEqualToleratingWhitespaceDifferences("0: (12,31)-(12,36)", spString); AssertEx.Equal(new byte[] { 0x00, // local signature 0x00, // delta IL offset 0x00, // Delta Lines 0x05, // Delta Columns 0x0C, // Start Line 0x1F // Start Column }, spBlob); break; } } } } [Fact] public void EmbeddedPortablePdb() { string source = @" using System; class C { public static void Main() { Console.WriteLine(); } } "; var c = CreateCompilation(Parse(source, "goo.cs"), options: TestOptions.DebugDll); var peBlob = c.EmitToArray(EmitOptions.Default. WithDebugInformationFormat(DebugInformationFormat.Embedded). WithPdbFilePath(@"a/b/c/d.pdb"). WithPdbChecksumAlgorithm(HashAlgorithmName.SHA512)); using (var peReader = new PEReader(peBlob)) { var entries = peReader.ReadDebugDirectory(); AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type)); var codeView = entries[0]; var checksum = entries[1]; var embedded = entries[2]; // EmbeddedPortablePdb entry: Assert.Equal(0x0100, embedded.MajorVersion); Assert.Equal(0x0100, embedded.MinorVersion); Assert.Equal(0u, embedded.Stamp); BlobContentId pdbId; using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded)) { var mdReader = embeddedMetadataProvider.GetMetadataReader(); AssertEx.Equal(new[] { "goo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name))); pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id); } // CodeView entry: var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView); Assert.Equal(0x0100, codeView.MajorVersion); Assert.Equal(0x504D, codeView.MinorVersion); Assert.Equal(pdbId.Stamp, codeView.Stamp); Assert.Equal(pdbId.Guid, codeViewData.Guid); Assert.Equal("d.pdb", codeViewData.Path); // Checksum entry: var checksumData = peReader.ReadPdbChecksumDebugDirectoryData(checksum); Assert.Equal("SHA512", checksumData.AlgorithmName); Assert.Equal(64, checksumData.Checksum.Length); } } [Fact] public void EmbeddedPortablePdb_Deterministic() { string source = @" using System; class C { public static void Main() { Console.WriteLine(); } } "; var c = CreateCompilation(Parse(source, "goo.cs"), options: TestOptions.DebugDll.WithDeterministic(true)); var peBlob = c.EmitToArray(EmitOptions.Default. WithDebugInformationFormat(DebugInformationFormat.Embedded). WithPdbChecksumAlgorithm(HashAlgorithmName.SHA384). WithPdbFilePath(@"a/b/c/d.pdb")); using (var peReader = new PEReader(peBlob)) { var entries = peReader.ReadDebugDirectory(); AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.Reproducible, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type)); var codeView = entries[0]; var checksum = entries[1]; var reproducible = entries[2]; var embedded = entries[3]; // EmbeddedPortablePdb entry: Assert.Equal(0x0100, embedded.MajorVersion); Assert.Equal(0x0100, embedded.MinorVersion); Assert.Equal(0u, embedded.Stamp); BlobContentId pdbId; using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded)) { var mdReader = embeddedMetadataProvider.GetMetadataReader(); AssertEx.Equal(new[] { "goo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name))); pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id); } // CodeView entry: var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView); Assert.Equal(0x0100, codeView.MajorVersion); Assert.Equal(0x504D, codeView.MinorVersion); Assert.Equal(pdbId.Stamp, codeView.Stamp); Assert.Equal(pdbId.Guid, codeViewData.Guid); Assert.Equal("d.pdb", codeViewData.Path); // Checksum entry: var checksumData = peReader.ReadPdbChecksumDebugDirectoryData(checksum); Assert.Equal("SHA384", checksumData.AlgorithmName); Assert.Equal(48, checksumData.Checksum.Length); // Reproducible entry: Assert.Equal(0, reproducible.MajorVersion); Assert.Equal(0, reproducible.MinorVersion); Assert.Equal(0U, reproducible.Stamp); Assert.Equal(0, reproducible.DataSize); } } [Fact] public void SourceLink() { string source = @" using System; class C { public static void Main() { Console.WriteLine(); } } "; var sourceLinkBlob = Encoding.UTF8.GetBytes(@" { ""documents"": { ""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*"" } } "); var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll); var pdbStream = new MemoryStream(); c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream, sourceLinkStream: new MemoryStream(sourceLinkBlob)); pdbStream.Position = 0; using (var provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream)) { var pdbReader = provider.GetMetadataReader(); var actualBlob = (from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition) let cdi = pdbReader.GetCustomDebugInformation(cdiHandle) where pdbReader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink select pdbReader.GetBlobBytes(cdi.Value)).Single(); AssertEx.Equal(sourceLinkBlob, actualBlob); } } [Fact] public void SourceLink_Embedded() { string source = @" using System; class C { public static void Main() { Console.WriteLine(); } } "; var sourceLinkBlob = Encoding.UTF8.GetBytes(@" { ""documents"": { ""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*"" } } "); var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll); var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded), sourceLinkStream: new MemoryStream(sourceLinkBlob)); using (var peReader = new PEReader(peBlob)) { var embeddedEntry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embeddedEntry)) { var pdbReader = embeddedMetadataProvider.GetMetadataReader(); var actualBlob = (from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition) let cdi = pdbReader.GetCustomDebugInformation(cdiHandle) where pdbReader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink select pdbReader.GetBlobBytes(cdi.Value)).Single(); AssertEx.Equal(sourceLinkBlob, actualBlob); } } } [Fact] public void SourceLink_Errors() { string source = @" using System; class C { public static void Main() { Console.WriteLine(); } } "; var sourceLinkStream = new TestStream(canRead: true, readFunc: (_, __, ___) => { throw new Exception("Error!"); }); var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll); var result = c.Emit(new MemoryStream(), new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), sourceLinkStream: sourceLinkStream); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'Error!' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("Error!").WithLocation(1, 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. #nullable disable using System; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Security.Cryptography; using System.Text; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PortablePdbTests : CSharpPDBTestBase { [Fact] public void SequencePointBlob() { string source = @" class C { public static void Main() { if (F()) { System.Console.WriteLine(1); } } public static bool F() => false; } "; var c = CreateCompilation(source, options: TestOptions.DebugDll); var pdbStream = new MemoryStream(); var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream); using (var peReader = new PEReader(peBlob)) using (var pdbMetadata = new PinnedMetadata(pdbStream.ToImmutable())) { var mdReader = peReader.GetMetadataReader(); var pdbReader = pdbMetadata.Reader; foreach (var methodHandle in mdReader.MethodDefinitions) { var method = mdReader.GetMethodDefinition(methodHandle); var methodDebugInfo = pdbReader.GetMethodDebugInformation(methodHandle); var name = mdReader.GetString(method.Name); TextWriter writer = new StringWriter(); foreach (var sp in methodDebugInfo.GetSequencePoints()) { if (sp.IsHidden) { writer.WriteLine($"{sp.Offset}: <hidden>"); } else { writer.WriteLine($"{sp.Offset}: ({sp.StartLine},{sp.StartColumn})-({sp.EndLine},{sp.EndColumn})"); } } var spString = writer.ToString(); var spBlob = pdbReader.GetBlobBytes(methodDebugInfo.SequencePointsBlob); switch (name) { case "Main": AssertEx.AssertEqualToleratingWhitespaceDifferences(@" 0: (5,5)-(5,6) 1: (6,9)-(6,17) 7: <hidden> 10: (7,9)-(7,10) 11: (8,13)-(8,41) 18: (9,9)-(9,10) 19: (10,5)-(10,6) ", spString); AssertEx.Equal(new byte[] { 0x01, // local signature 0x00, // IL offset 0x00, // Delta Lines 0x01, // Delta Columns 0x05, // Start Line 0x05, // Start Column 0x01, // delta IL offset 0x00, // Delta Lines 0x08, // Delta Columns 0x02, // delta Start Line (signed compressed) 0x08, // delta Start Column (signed compressed) 0x06, // delta IL offset 0x00, // hidden 0x00, // hidden 0x03, // delta IL offset 0x00, // Delta Lines 0x01, // Delta Columns 0x02, // delta Start Line (signed compressed) 0x00, // delta Start Column (signed compressed) 0x01, // delta IL offset 0x00, // Delta Lines 0x1C, // Delta Columns 0x02, // delta Start Line (signed compressed) 0x08, // delta Start Column (signed compressed) 0x07, // delta IL offset 0x00, // Delta Lines 0x01, // Delta Columns 0x02, // delta Start Line (signed compressed) 0x79, // delta Start Column (signed compressed) 0x01, // delta IL offset 0x00, // Delta Lines 0x01, // Delta Columns 0x02, // delta Start Line (signed compressed) 0x79, // delta Start Column (signed compressed) }, spBlob); break; case "F": AssertEx.AssertEqualToleratingWhitespaceDifferences("0: (12,31)-(12,36)", spString); AssertEx.Equal(new byte[] { 0x00, // local signature 0x00, // delta IL offset 0x00, // Delta Lines 0x05, // Delta Columns 0x0C, // Start Line 0x1F // Start Column }, spBlob); break; } } } } [Fact] public void EmbeddedPortablePdb() { string source = @" using System; class C { public static void Main() { Console.WriteLine(); } } "; var c = CreateCompilation(Parse(source, "goo.cs"), options: TestOptions.DebugDll); var peBlob = c.EmitToArray(EmitOptions.Default. WithDebugInformationFormat(DebugInformationFormat.Embedded). WithPdbFilePath(@"a/b/c/d.pdb"). WithPdbChecksumAlgorithm(HashAlgorithmName.SHA512)); using (var peReader = new PEReader(peBlob)) { var entries = peReader.ReadDebugDirectory(); AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type)); var codeView = entries[0]; var checksum = entries[1]; var embedded = entries[2]; // EmbeddedPortablePdb entry: Assert.Equal(0x0100, embedded.MajorVersion); Assert.Equal(0x0100, embedded.MinorVersion); Assert.Equal(0u, embedded.Stamp); BlobContentId pdbId; using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded)) { var mdReader = embeddedMetadataProvider.GetMetadataReader(); AssertEx.Equal(new[] { "goo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name))); pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id); } // CodeView entry: var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView); Assert.Equal(0x0100, codeView.MajorVersion); Assert.Equal(0x504D, codeView.MinorVersion); Assert.Equal(pdbId.Stamp, codeView.Stamp); Assert.Equal(pdbId.Guid, codeViewData.Guid); Assert.Equal("d.pdb", codeViewData.Path); // Checksum entry: var checksumData = peReader.ReadPdbChecksumDebugDirectoryData(checksum); Assert.Equal("SHA512", checksumData.AlgorithmName); Assert.Equal(64, checksumData.Checksum.Length); } } [Fact] public void EmbeddedPortablePdb_Deterministic() { string source = @" using System; class C { public static void Main() { Console.WriteLine(); } } "; var c = CreateCompilation(Parse(source, "goo.cs"), options: TestOptions.DebugDll.WithDeterministic(true)); var peBlob = c.EmitToArray(EmitOptions.Default. WithDebugInformationFormat(DebugInformationFormat.Embedded). WithPdbChecksumAlgorithm(HashAlgorithmName.SHA384). WithPdbFilePath(@"a/b/c/d.pdb")); using (var peReader = new PEReader(peBlob)) { var entries = peReader.ReadDebugDirectory(); AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.Reproducible, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type)); var codeView = entries[0]; var checksum = entries[1]; var reproducible = entries[2]; var embedded = entries[3]; // EmbeddedPortablePdb entry: Assert.Equal(0x0100, embedded.MajorVersion); Assert.Equal(0x0100, embedded.MinorVersion); Assert.Equal(0u, embedded.Stamp); BlobContentId pdbId; using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded)) { var mdReader = embeddedMetadataProvider.GetMetadataReader(); AssertEx.Equal(new[] { "goo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name))); pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id); } // CodeView entry: var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView); Assert.Equal(0x0100, codeView.MajorVersion); Assert.Equal(0x504D, codeView.MinorVersion); Assert.Equal(pdbId.Stamp, codeView.Stamp); Assert.Equal(pdbId.Guid, codeViewData.Guid); Assert.Equal("d.pdb", codeViewData.Path); // Checksum entry: var checksumData = peReader.ReadPdbChecksumDebugDirectoryData(checksum); Assert.Equal("SHA384", checksumData.AlgorithmName); Assert.Equal(48, checksumData.Checksum.Length); // Reproducible entry: Assert.Equal(0, reproducible.MajorVersion); Assert.Equal(0, reproducible.MinorVersion); Assert.Equal(0U, reproducible.Stamp); Assert.Equal(0, reproducible.DataSize); } } [Fact] public void SourceLink() { string source = @" using System; class C { public static void Main() { Console.WriteLine(); } } "; var sourceLinkBlob = Encoding.UTF8.GetBytes(@" { ""documents"": { ""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*"" } } "); var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll); var pdbStream = new MemoryStream(); c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream, sourceLinkStream: new MemoryStream(sourceLinkBlob)); pdbStream.Position = 0; using (var provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream)) { var pdbReader = provider.GetMetadataReader(); var actualBlob = (from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition) let cdi = pdbReader.GetCustomDebugInformation(cdiHandle) where pdbReader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink select pdbReader.GetBlobBytes(cdi.Value)).Single(); AssertEx.Equal(sourceLinkBlob, actualBlob); } } [Fact] public void SourceLink_Embedded() { string source = @" using System; class C { public static void Main() { Console.WriteLine(); } } "; var sourceLinkBlob = Encoding.UTF8.GetBytes(@" { ""documents"": { ""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*"" } } "); var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll); var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded), sourceLinkStream: new MemoryStream(sourceLinkBlob)); using (var peReader = new PEReader(peBlob)) { var embeddedEntry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embeddedEntry)) { var pdbReader = embeddedMetadataProvider.GetMetadataReader(); var actualBlob = (from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition) let cdi = pdbReader.GetCustomDebugInformation(cdiHandle) where pdbReader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink select pdbReader.GetBlobBytes(cdi.Value)).Single(); AssertEx.Equal(sourceLinkBlob, actualBlob); } } } [Fact] public void SourceLink_Errors() { string source = @" using System; class C { public static void Main() { Console.WriteLine(); } } "; var sourceLinkStream = new TestStream(canRead: true, readFunc: (_, __, ___) => { throw new Exception("Error!"); }); var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll); var result = c.Emit(new MemoryStream(), new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), sourceLinkStream: sourceLinkStream); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'Error!' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("Error!").WithLocation(1, 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/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationNamespaceInfo.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.Runtime.CompilerServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationNamespaceInfo { private static readonly ConditionalWeakTable<INamespaceSymbol, CodeGenerationNamespaceInfo> s_namespaceToInfoMap = new(); private readonly IList<ISymbol> _imports; private CodeGenerationNamespaceInfo(IList<ISymbol> imports) => _imports = imports; public static void Attach( INamespaceSymbol @namespace, IList<ISymbol> imports) { var info = new CodeGenerationNamespaceInfo(imports ?? SpecializedCollections.EmptyList<ISymbol>()); s_namespaceToInfoMap.Add(@namespace, info); } private static CodeGenerationNamespaceInfo GetInfo(INamespaceSymbol @namespace) { s_namespaceToInfoMap.TryGetValue(@namespace, out var info); return info; } public static IList<ISymbol> GetImports(INamespaceSymbol @namespace) => GetImports(GetInfo(@namespace)); private static IList<ISymbol> GetImports(CodeGenerationNamespaceInfo info) { return info == null ? SpecializedCollections.EmptyList<ISymbol>() : info._imports; } } }
// 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.Runtime.CompilerServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationNamespaceInfo { private static readonly ConditionalWeakTable<INamespaceSymbol, CodeGenerationNamespaceInfo> s_namespaceToInfoMap = new(); private readonly IList<ISymbol> _imports; private CodeGenerationNamespaceInfo(IList<ISymbol> imports) => _imports = imports; public static void Attach( INamespaceSymbol @namespace, IList<ISymbol> imports) { var info = new CodeGenerationNamespaceInfo(imports ?? SpecializedCollections.EmptyList<ISymbol>()); s_namespaceToInfoMap.Add(@namespace, info); } private static CodeGenerationNamespaceInfo GetInfo(INamespaceSymbol @namespace) { s_namespaceToInfoMap.TryGetValue(@namespace, out var info); return info; } public static IList<ISymbol> GetImports(INamespaceSymbol @namespace) => GetImports(GetInfo(@namespace)); private static IList<ISymbol> GetImports(CodeGenerationNamespaceInfo info) { return info == null ? SpecializedCollections.EmptyList<ISymbol>() : info._imports; } } }
-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/Perf.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 Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Public Class Perf : Inherits BasicTestBase <Fact()> Public Sub Test() ' This test ensures that our perf benchmark code compiles without problems. ' Benchmark code can be found in the following file under the ' "CompilerTestResources" project that is part of Roslyn.sln - ' $/Roslyn/Main/Open/Compilers/Test/Resources/Core/PerfTests/VBPerfTest.vb ' You can also use VS's "Navigate To" feature to find the above file easily - ' Just hit "Ctrl + ," and type "VBPerfTest.vb" in the dialog that pops up. ' Please note that if this test fails, it is likely because of a bug in the ' *product* and not in the *test* / *benchmark code* :) ' The benchmark code has been verified to compile fine against Dev10. ' So if the test fails we should fix the product bug that is causing the failure ' as opposed to 'fixing' the test by updating the benchmark code. ' If you absolutely need to change the benchmark code - PLEASE SHOOT A MAIL TO SHYAM (GNAMBOO) ' so that he can apply the same changes to the copy of this benchmark code that is used in the perf test. CompileAndVerify(<compilation> <file name="VBPerfTest.vb"> <%= TestResources.PerfTests.VBPerfTest %> </file> </compilation>, references:={TestMetadata.Net40.SystemCore}).VerifyDiagnostics() 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 Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Public Class Perf : Inherits BasicTestBase <Fact()> Public Sub Test() ' This test ensures that our perf benchmark code compiles without problems. ' Benchmark code can be found in the following file under the ' "CompilerTestResources" project that is part of Roslyn.sln - ' $/Roslyn/Main/Open/Compilers/Test/Resources/Core/PerfTests/VBPerfTest.vb ' You can also use VS's "Navigate To" feature to find the above file easily - ' Just hit "Ctrl + ," and type "VBPerfTest.vb" in the dialog that pops up. ' Please note that if this test fails, it is likely because of a bug in the ' *product* and not in the *test* / *benchmark code* :) ' The benchmark code has been verified to compile fine against Dev10. ' So if the test fails we should fix the product bug that is causing the failure ' as opposed to 'fixing' the test by updating the benchmark code. ' If you absolutely need to change the benchmark code - PLEASE SHOOT A MAIL TO SHYAM (GNAMBOO) ' so that he can apply the same changes to the copy of this benchmark code that is used in the perf test. CompileAndVerify(<compilation> <file name="VBPerfTest.vb"> <%= TestResources.PerfTests.VBPerfTest %> </file> </compilation>, references:={TestMetadata.Net40.SystemCore}).VerifyDiagnostics() 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/Compilers/CSharp/Portable/Lowering/DiagnosticsPass_ExpressionTrees.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.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This pass detects and reports diagnostics that do not affect lambda convertibility. /// This part of the partial class focuses on features that cannot be used in expression trees. /// CAVEAT: Errors may be produced for ObsoleteAttribute, but such errors don't affect lambda convertibility. /// </summary> internal sealed partial class DiagnosticsPass { private readonly BindingDiagnosticBag _diagnostics; private readonly CSharpCompilation _compilation; private bool _inExpressionLambda; private bool _reportedUnsafe; private readonly MethodSymbol _containingSymbol; // Containing static local function, static anonymous function, or static lambda. private SourceMethodSymbol _staticLocalOrAnonymousFunction; public static void IssueDiagnostics(CSharpCompilation compilation, BoundNode node, BindingDiagnosticBag diagnostics, MethodSymbol containingSymbol) { Debug.Assert(node != null); Debug.Assert((object)containingSymbol != null); ExecutableCodeBinder.ValidateIteratorMethod(compilation, containingSymbol, diagnostics); try { var diagnosticPass = new DiagnosticsPass(compilation, diagnostics, containingSymbol); diagnosticPass.Visit(node); } catch (CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); } } private DiagnosticsPass(CSharpCompilation compilation, BindingDiagnosticBag diagnostics, MethodSymbol containingSymbol) { Debug.Assert(diagnostics != null); Debug.Assert((object)containingSymbol != null); _compilation = compilation; _diagnostics = diagnostics; _containingSymbol = containingSymbol; } private void Error(ErrorCode code, BoundNode node, params object[] args) { _diagnostics.Add(code, node.Syntax.Location, args); } private void CheckUnsafeType(BoundExpression e) { if (e != null && (object)e.Type != null && e.Type.IsPointerOrFunctionPointer()) NoteUnsafe(e); } private void NoteUnsafe(BoundNode node) { if (_inExpressionLambda && !_reportedUnsafe) { Error(ErrorCode.ERR_ExpressionTreeContainsPointerOp, node); _reportedUnsafe = true; } } public override BoundNode VisitArrayCreation(BoundArrayCreation node) { var arrayType = (ArrayTypeSymbol)node.Type; if (_inExpressionLambda && node.InitializerOpt != null && !arrayType.IsSZArray) { Error(ErrorCode.ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer, node); } return base.VisitArrayCreation(node); } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { if (_inExpressionLambda && node.Indices.Length == 1 && node.Indices[0].Type!.SpecialType == SpecialType.None) { Error(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, node); } return base.VisitArrayAccess(node); } public override BoundNode VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, node); } return base.VisitIndexOrRangePatternIndexerAccess(node); } public override BoundNode VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsFromEndIndexExpression, node); } return base.VisitFromEndIndexExpression(node); } public override BoundNode VisitRangeExpression(BoundRangeExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsRangeExpression, node); } return base.VisitRangeExpression(node); } public override BoundNode VisitSizeOfOperator(BoundSizeOfOperator node) { if (_inExpressionLambda && node.ConstantValue == null) { Error(ErrorCode.ERR_ExpressionTreeContainsPointerOp, node); } return base.VisitSizeOfOperator(node); } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { ExecutableCodeBinder.ValidateIteratorMethod(_compilation, node.Symbol, _diagnostics); var outerLocalFunction = _staticLocalOrAnonymousFunction; if (node.Symbol.IsStatic) { _staticLocalOrAnonymousFunction = node.Symbol; } var result = base.VisitLocalFunctionStatement(node); _staticLocalOrAnonymousFunction = outerLocalFunction; return result; } public override BoundNode VisitThisReference(BoundThisReference node) { CheckReferenceToThisOrBase(node); return base.VisitThisReference(node); } public override BoundNode VisitBaseReference(BoundBaseReference node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsBaseAccess, node); } CheckReferenceToThisOrBase(node); return base.VisitBaseReference(node); } public override BoundNode VisitLocal(BoundLocal node) { CheckReferenceToVariable(node, node.LocalSymbol); return base.VisitLocal(node); } public override BoundNode VisitParameter(BoundParameter node) { CheckReferenceToVariable(node, node.ParameterSymbol); return base.VisitParameter(node); } private void CheckReferenceToThisOrBase(BoundExpression node) { if (_staticLocalOrAnonymousFunction is object) { var diagnostic = _staticLocalOrAnonymousFunction.MethodKind == MethodKind.LocalFunction ? ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis : ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis; Error(diagnostic, node); } } private void CheckReferenceToVariable(BoundExpression node, Symbol symbol) { Debug.Assert(symbol.Kind == SymbolKind.Local || symbol.Kind == SymbolKind.Parameter || symbol is LocalFunctionSymbol); if (_staticLocalOrAnonymousFunction is object && Symbol.IsCaptured(symbol, _staticLocalOrAnonymousFunction)) { var diagnostic = _staticLocalOrAnonymousFunction.MethodKind == MethodKind.LocalFunction ? ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable : ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable; Error(diagnostic, node, new FormattedSymbol(symbol, SymbolDisplayFormat.ShortFormat)); } } private void CheckReferenceToMethodIfLocalFunction(BoundExpression node, MethodSymbol method) { if (method?.OriginalDefinition is LocalFunctionSymbol localFunction) { CheckReferenceToVariable(node, localFunction); } } public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsSwitchExpression, node); } return base.VisitConvertedSwitchExpression(node); } public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { if (!node.HasAnyErrors) { CheckForDeconstructionAssignmentToSelf((BoundTupleExpression)node.Left, node.Right); } return base.VisitDeconstructionAssignmentOperator(node); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { CheckForAssignmentToSelf(node); if (_inExpressionLambda && node.Left.Kind != BoundKind.ObjectInitializerMember && node.Left.Kind != BoundKind.DynamicObjectInitializerMember) { Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); } return base.VisitAssignmentOperator(node); } public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicObjectInitializerMember(node); } public override BoundNode VisitEventAccess(BoundEventAccess node) { // Don't bother reporting an obsolete diagnostic if the access is already wrong for other reasons // (specifically, we can't use it as a field here). if (node.IsUsableAsField) { bool hasBaseReceiver = node.ReceiverOpt != null && node.ReceiverOpt.Kind == BoundKind.BaseReference; Binder.ReportDiagnosticsIfObsolete(_diagnostics, node.EventSymbol.AssociatedField, node.Syntax, hasBaseReceiver, _containingSymbol, _containingSymbol.ContainingType, BinderFlags.None); } CheckReceiverIfField(node.ReceiverOpt); return base.VisitEventAccess(node); } public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); } bool hasBaseReceiver = node.ReceiverOpt != null && node.ReceiverOpt.Kind == BoundKind.BaseReference; Binder.ReportDiagnosticsIfObsolete(_diagnostics, node.Event, ((AssignmentExpressionSyntax)node.Syntax).Left, hasBaseReceiver, _containingSymbol, _containingSymbol.ContainingType, BinderFlags.None); CheckReceiverIfField(node.ReceiverOpt); return base.VisitEventAssignmentOperator(node); } public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { CheckCompoundAssignmentOperator(node); return base.VisitCompoundAssignmentOperator(node); } private void VisitCall( MethodSymbol method, PropertySymbol propertyAccess, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<string> argumentNamesOpt, BitVector defaultArguments, BoundNode node) { Debug.Assert((object)method != null); Debug.Assert(((object)propertyAccess == null) || (method == propertyAccess.GetOwnOrInheritedGetMethod()) || (method == propertyAccess.GetOwnOrInheritedSetMethod()) || propertyAccess.MustCallMethodsDirectly); CheckArguments(argumentRefKindsOpt, arguments, method); if (_inExpressionLambda) { if (method.CallsAreOmitted(node.SyntaxTree)) { Error(ErrorCode.ERR_PartialMethodInExpressionTree, node); } else if ((object)propertyAccess != null && propertyAccess.IsIndexedProperty() && !propertyAccess.IsIndexer) { Error(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, node); } else if (hasDefaultArgument(arguments, defaultArguments)) { Error(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, node); } else if (!argumentNamesOpt.IsDefaultOrEmpty) { Error(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, node); } else if (IsComCallWithRefOmitted(method, arguments, argumentRefKindsOpt)) { Error(ErrorCode.ERR_ComRefCallInExpressionTree, node); } else if (method.MethodKind == MethodKind.LocalFunction) { Error(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, node); } else if (method.RefKind != RefKind.None) { Error(ErrorCode.ERR_RefReturningCallInExpressionTree, node); } else if (method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } } static bool hasDefaultArgument(ImmutableArray<BoundExpression> arguments, BitVector defaultArguments) { for (int i = 0; i < arguments.Length; i++) { if (defaultArguments[i]) { return true; } } return false; } } public override BoundNode Visit(BoundNode node) { if (_inExpressionLambda && // Ignoring BoundConversion nodes prevents redundant diagnostics !(node is BoundConversion) && node is BoundExpression expr && expr.Type is TypeSymbol type && type.IsRestrictedType()) { Error(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, node, type.Name); } return base.Visit(node); } public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__reftype"); } return base.VisitRefTypeOperator(node); } public override BoundNode VisitRefValueOperator(BoundRefValueOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__refvalue"); } return base.VisitRefValueOperator(node); } public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__makeref"); } return base.VisitMakeRefOperator(node); } public override BoundNode VisitArgListOperator(BoundArgListOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_VarArgsInExpressionTree, node); } return base.VisitArgListOperator(node); } public override BoundNode VisitConditionalAccess(BoundConditionalAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_NullPropagatingOpInExpressionTree, node); } return base.VisitConditionalAccess(node); } public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) { if (_inExpressionLambda && !node.Arguments.IsDefaultOrEmpty) { Error(ErrorCode.ERR_DictionaryInitializerInExpressionTree, node); } if (node.MemberSymbol is PropertySymbol property) { CheckRefReturningPropertyAccess(node, property); } return base.VisitObjectInitializerMember(node); } public override BoundNode VisitCall(BoundCall node) { VisitCall(node.Method, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); CheckReceiverIfField(node.ReceiverOpt); CheckReferenceToMethodIfLocalFunction(node, node.Method); return base.VisitCall(node); } /// <summary> /// Called when a local represents an out variable declaration. Its syntax is of type DeclarationExpressionSyntax. /// </summary> private void CheckOutDeclaration(BoundLocal local) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsOutVariable, local); } } private void CheckDiscard(BoundDiscardExpression argument) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDiscard, argument); } } public override BoundNode VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { if (_inExpressionLambda && node.AddMethod.IsStatic) { Error(ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree, node); } VisitCall(node.AddMethod, null, node.Arguments, default(ImmutableArray<RefKind>), default(ImmutableArray<string>), node.DefaultArguments, node); return base.VisitCollectionElementInitializer(node); } public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) { VisitCall(node.Constructor, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); return base.VisitObjectCreationExpression(node); } public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) { var indexer = node.Indexer; var method = indexer.GetOwnOrInheritedGetMethod() ?? indexer.GetOwnOrInheritedSetMethod(); if ((object)method != null) { VisitCall(method, indexer, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); } CheckReceiverIfField(node.ReceiverOpt); return base.VisitIndexerAccess(node); } private void CheckRefReturningPropertyAccess(BoundNode node, PropertySymbol property) { if (_inExpressionLambda && property.RefKind != RefKind.None) { Error(ErrorCode.ERR_RefReturningCallInExpressionTree, node); } } public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; CheckRefReturningPropertyAccess(node, property); CheckReceiverIfField(node.ReceiverOpt); if (_inExpressionLambda && property.IsAbstract && property.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } return base.VisitPropertyAccess(node); } public override BoundNode VisitLambda(BoundLambda node) { if (_inExpressionLambda) { var lambda = node.Symbol; foreach (var p in lambda.Parameters) { if (p.RefKind != RefKind.None && p.Locations.Length != 0) { _diagnostics.Add(ErrorCode.ERR_ByRefParameterInExpressionTree, p.Locations[0]); } if (p.TypeWithAnnotations.IsRestrictedType()) { _diagnostics.Add(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, p.Locations[0], p.Type.Name); } } switch (node.Syntax.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: { var lambdaSyntax = (ParenthesizedLambdaExpressionSyntax)node.Syntax; if (lambdaSyntax.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword) { Error(ErrorCode.ERR_BadAsyncExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.Block) { Error(ErrorCode.ERR_StatementLambdaToExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.RefExpression) { Error(ErrorCode.ERR_BadRefReturnExpressionTree, node); } } break; case SyntaxKind.SimpleLambdaExpression: { var lambdaSyntax = (SimpleLambdaExpressionSyntax)node.Syntax; if (lambdaSyntax.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword) { Error(ErrorCode.ERR_BadAsyncExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.Block) { Error(ErrorCode.ERR_StatementLambdaToExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.RefExpression) { Error(ErrorCode.ERR_BadRefReturnExpressionTree, node); } } break; case SyntaxKind.AnonymousMethodExpression: Error(ErrorCode.ERR_ExpressionTreeContainsAnonymousMethod, node); break; default: // other syntax forms arise from query expressions, and always result from implied expression-lambda-like forms break; } } var outerLocalFunction = _staticLocalOrAnonymousFunction; if (node.Symbol.IsStatic) { _staticLocalOrAnonymousFunction = node.Symbol; } var result = base.VisitLambda(node); _staticLocalOrAnonymousFunction = outerLocalFunction; return result; } public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { // It is very common for bound trees to be left-heavy binary operators, eg, // a + b + c + d + ... // To avoid blowing the stack, do not recurse down the left hand side. // In order to avoid blowing the stack, we end up visiting right children // before left children; this should not be a problem in the diagnostics // pass. BoundBinaryOperator current = node; while (true) { CheckBinaryOperator(current); Visit(current.Right); if (current.Left.Kind == BoundKind.BinaryOperator) { current = (BoundBinaryOperator)current.Left; } else { Visit(current.Left); break; } } return null; } public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { CheckLiftedUserDefinedConditionalLogicalOperator(node); if (_inExpressionLambda) { var binary = node.LogicalOperator; var unary = node.OperatorKind.Operator() == BinaryOperatorKind.And ? node.FalseOperator : node.TrueOperator; if ((binary.IsAbstract && binary.IsStatic) || (unary.IsAbstract && unary.IsStatic)) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } } return base.VisitUserDefinedConditionalLogicalOperator(node); } private void CheckDynamic(BoundUnaryOperator node) { if (_inExpressionLambda && node.OperatorKind.IsDynamic()) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } } private void CheckDynamic(BoundBinaryOperator node) { if (_inExpressionLambda && node.OperatorKind.IsDynamic()) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } } public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) { CheckUnsafeType(node); CheckLiftedUnaryOp(node); CheckDynamic(node); if (_inExpressionLambda && node.MethodOpt is MethodSymbol method && method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } return base.VisitUnaryOperator(node); } public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) { CheckUnsafeType(node); BoundExpression operand = node.Operand; if (operand.Kind == BoundKind.FieldAccess) { CheckFieldAddress((BoundFieldAccess)operand, consumerOpt: null); } return base.VisitAddressOfOperator(node); } public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); } return base.VisitIncrementOperator(node); } public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) { NoteUnsafe(node); return base.VisitPointerElementAccess(node); } public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { NoteUnsafe(node); return base.VisitPointerIndirectionOperator(node); } public override BoundNode VisitConversion(BoundConversion node) { CheckUnsafeType(node.Operand); CheckUnsafeType(node); bool wasInExpressionLambda = _inExpressionLambda; bool oldReportedUnsafe = _reportedUnsafe; switch (node.ConversionKind) { case ConversionKind.MethodGroup: CheckMethodGroup((BoundMethodGroup)node.Operand, node.Conversion.Method, parentIsConversion: true, node.Type); return node; case ConversionKind.AnonymousFunction: if (!wasInExpressionLambda && node.Type.IsExpressionTree()) { _inExpressionLambda = true; // we report "unsafe in expression tree" at most once for each expression tree _reportedUnsafe = false; } break; case ConversionKind.ImplicitDynamic: case ConversionKind.ExplicitDynamic: if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } break; case ConversionKind.ExplicitTuple: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleConversion, node); } break; case ConversionKind.InterpolatedStringHandler: if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, node); } break; default: if (_inExpressionLambda && node.Conversion.Method is MethodSymbol method && method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } break; } var result = base.VisitConversion(node); _inExpressionLambda = wasInExpressionLambda; _reportedUnsafe = oldReportedUnsafe; return result; } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { if (node.Argument.Kind != BoundKind.MethodGroup) { this.Visit(node.Argument); } else { CheckMethodGroup((BoundMethodGroup)node.Argument, node.MethodOpt, parentIsConversion: true, convertedToType: node.Type); } return null; } public override BoundNode VisitMethodGroup(BoundMethodGroup node) { CheckMethodGroup(node, method: null, parentIsConversion: false, convertedToType: null); return null; } private void CheckMethodGroup(BoundMethodGroup node, MethodSymbol method, bool parentIsConversion, TypeSymbol convertedToType) { // Formerly reported ERR_MemGroupInExpressionTree when this occurred, but the expanded // ERR_LambdaInIsAs makes this impossible (since the node will always be wrapped in // a failed conversion). Debug.Assert(!(!parentIsConversion && _inExpressionLambda)); if (_inExpressionLambda) { if ((node.LookupSymbolOpt as MethodSymbol)?.MethodKind == MethodKind.LocalFunction) { Error(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, node); } else if (parentIsConversion && convertedToType.IsFunctionPointer()) { Error(ErrorCode.ERR_AddressOfMethodGroupInExpressionTree, node); } else if (method is not null && method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } } CheckReceiverIfField(node.ReceiverOpt); CheckReferenceToMethodIfLocalFunction(node, method); if (method is null || method.RequiresInstanceReceiver) { Visit(node.ReceiverOpt); } } public override BoundNode VisitNameOfOperator(BoundNameOfOperator node) { // The nameof(...) operator collapses to a constant in an expression tree, // so it does not matter what is recursively within it. return node; } public override BoundNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { if (_inExpressionLambda && (node.LeftOperand.IsLiteralNull() || node.LeftOperand.IsLiteralDefault())) { Error(ErrorCode.ERR_ExpressionTreeContainsBadCoalesce, node.LeftOperand); } return base.VisitNullCoalescingOperator(node); } public override BoundNode VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeCantContainNullCoalescingAssignment, node); } return base.VisitNullCoalescingAssignmentOperator(node); } public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); // avoid reporting errors for the method group: if (node.Expression.Kind == BoundKind.MethodGroup) { return base.VisitMethodGroup((BoundMethodGroup)node.Expression); } } return base.VisitDynamicInvocation(node); } public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } CheckReceiverIfField(node.Receiver); return base.VisitDynamicIndexerAccess(node); } public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicMemberAccess(node); } public override BoundNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicCollectionElementInitializer(node); } public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicObjectCreationExpression(node); } public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsIsMatch, node); } return base.VisitIsPatternExpression(node); } public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, node); } return base.VisitConvertedTupleLiteral(node); } public override BoundNode VisitTupleLiteral(BoundTupleLiteral node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, node); } return base.VisitTupleLiteral(node); } public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, node); } return base.VisitTupleBinaryOperator(node); } public override BoundNode VisitThrowExpression(BoundThrowExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, node); } return base.VisitThrowExpression(node); } public override BoundNode VisitWithExpression(BoundWithExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsWithExpression, node); } return base.VisitWithExpression(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. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This pass detects and reports diagnostics that do not affect lambda convertibility. /// This part of the partial class focuses on features that cannot be used in expression trees. /// CAVEAT: Errors may be produced for ObsoleteAttribute, but such errors don't affect lambda convertibility. /// </summary> internal sealed partial class DiagnosticsPass { private readonly BindingDiagnosticBag _diagnostics; private readonly CSharpCompilation _compilation; private bool _inExpressionLambda; private bool _reportedUnsafe; private readonly MethodSymbol _containingSymbol; // Containing static local function, static anonymous function, or static lambda. private SourceMethodSymbol _staticLocalOrAnonymousFunction; public static void IssueDiagnostics(CSharpCompilation compilation, BoundNode node, BindingDiagnosticBag diagnostics, MethodSymbol containingSymbol) { Debug.Assert(node != null); Debug.Assert((object)containingSymbol != null); ExecutableCodeBinder.ValidateIteratorMethod(compilation, containingSymbol, diagnostics); try { var diagnosticPass = new DiagnosticsPass(compilation, diagnostics, containingSymbol); diagnosticPass.Visit(node); } catch (CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); } } private DiagnosticsPass(CSharpCompilation compilation, BindingDiagnosticBag diagnostics, MethodSymbol containingSymbol) { Debug.Assert(diagnostics != null); Debug.Assert((object)containingSymbol != null); _compilation = compilation; _diagnostics = diagnostics; _containingSymbol = containingSymbol; } private void Error(ErrorCode code, BoundNode node, params object[] args) { _diagnostics.Add(code, node.Syntax.Location, args); } private void CheckUnsafeType(BoundExpression e) { if (e != null && (object)e.Type != null && e.Type.IsPointerOrFunctionPointer()) NoteUnsafe(e); } private void NoteUnsafe(BoundNode node) { if (_inExpressionLambda && !_reportedUnsafe) { Error(ErrorCode.ERR_ExpressionTreeContainsPointerOp, node); _reportedUnsafe = true; } } public override BoundNode VisitArrayCreation(BoundArrayCreation node) { var arrayType = (ArrayTypeSymbol)node.Type; if (_inExpressionLambda && node.InitializerOpt != null && !arrayType.IsSZArray) { Error(ErrorCode.ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer, node); } return base.VisitArrayCreation(node); } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { if (_inExpressionLambda && node.Indices.Length == 1 && node.Indices[0].Type!.SpecialType == SpecialType.None) { Error(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, node); } return base.VisitArrayAccess(node); } public override BoundNode VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, node); } return base.VisitIndexOrRangePatternIndexerAccess(node); } public override BoundNode VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsFromEndIndexExpression, node); } return base.VisitFromEndIndexExpression(node); } public override BoundNode VisitRangeExpression(BoundRangeExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsRangeExpression, node); } return base.VisitRangeExpression(node); } public override BoundNode VisitSizeOfOperator(BoundSizeOfOperator node) { if (_inExpressionLambda && node.ConstantValue == null) { Error(ErrorCode.ERR_ExpressionTreeContainsPointerOp, node); } return base.VisitSizeOfOperator(node); } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { ExecutableCodeBinder.ValidateIteratorMethod(_compilation, node.Symbol, _diagnostics); var outerLocalFunction = _staticLocalOrAnonymousFunction; if (node.Symbol.IsStatic) { _staticLocalOrAnonymousFunction = node.Symbol; } var result = base.VisitLocalFunctionStatement(node); _staticLocalOrAnonymousFunction = outerLocalFunction; return result; } public override BoundNode VisitThisReference(BoundThisReference node) { CheckReferenceToThisOrBase(node); return base.VisitThisReference(node); } public override BoundNode VisitBaseReference(BoundBaseReference node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsBaseAccess, node); } CheckReferenceToThisOrBase(node); return base.VisitBaseReference(node); } public override BoundNode VisitLocal(BoundLocal node) { CheckReferenceToVariable(node, node.LocalSymbol); return base.VisitLocal(node); } public override BoundNode VisitParameter(BoundParameter node) { CheckReferenceToVariable(node, node.ParameterSymbol); return base.VisitParameter(node); } private void CheckReferenceToThisOrBase(BoundExpression node) { if (_staticLocalOrAnonymousFunction is object) { var diagnostic = _staticLocalOrAnonymousFunction.MethodKind == MethodKind.LocalFunction ? ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis : ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis; Error(diagnostic, node); } } private void CheckReferenceToVariable(BoundExpression node, Symbol symbol) { Debug.Assert(symbol.Kind == SymbolKind.Local || symbol.Kind == SymbolKind.Parameter || symbol is LocalFunctionSymbol); if (_staticLocalOrAnonymousFunction is object && Symbol.IsCaptured(symbol, _staticLocalOrAnonymousFunction)) { var diagnostic = _staticLocalOrAnonymousFunction.MethodKind == MethodKind.LocalFunction ? ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable : ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable; Error(diagnostic, node, new FormattedSymbol(symbol, SymbolDisplayFormat.ShortFormat)); } } private void CheckReferenceToMethodIfLocalFunction(BoundExpression node, MethodSymbol method) { if (method?.OriginalDefinition is LocalFunctionSymbol localFunction) { CheckReferenceToVariable(node, localFunction); } } public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsSwitchExpression, node); } return base.VisitConvertedSwitchExpression(node); } public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { if (!node.HasAnyErrors) { CheckForDeconstructionAssignmentToSelf((BoundTupleExpression)node.Left, node.Right); } return base.VisitDeconstructionAssignmentOperator(node); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { CheckForAssignmentToSelf(node); if (_inExpressionLambda && node.Left.Kind != BoundKind.ObjectInitializerMember && node.Left.Kind != BoundKind.DynamicObjectInitializerMember) { Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); } return base.VisitAssignmentOperator(node); } public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicObjectInitializerMember(node); } public override BoundNode VisitEventAccess(BoundEventAccess node) { // Don't bother reporting an obsolete diagnostic if the access is already wrong for other reasons // (specifically, we can't use it as a field here). if (node.IsUsableAsField) { bool hasBaseReceiver = node.ReceiverOpt != null && node.ReceiverOpt.Kind == BoundKind.BaseReference; Binder.ReportDiagnosticsIfObsolete(_diagnostics, node.EventSymbol.AssociatedField, node.Syntax, hasBaseReceiver, _containingSymbol, _containingSymbol.ContainingType, BinderFlags.None); } CheckReceiverIfField(node.ReceiverOpt); return base.VisitEventAccess(node); } public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); } bool hasBaseReceiver = node.ReceiverOpt != null && node.ReceiverOpt.Kind == BoundKind.BaseReference; Binder.ReportDiagnosticsIfObsolete(_diagnostics, node.Event, ((AssignmentExpressionSyntax)node.Syntax).Left, hasBaseReceiver, _containingSymbol, _containingSymbol.ContainingType, BinderFlags.None); CheckReceiverIfField(node.ReceiverOpt); return base.VisitEventAssignmentOperator(node); } public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { CheckCompoundAssignmentOperator(node); return base.VisitCompoundAssignmentOperator(node); } private void VisitCall( MethodSymbol method, PropertySymbol propertyAccess, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<string> argumentNamesOpt, BitVector defaultArguments, BoundNode node) { Debug.Assert((object)method != null); Debug.Assert(((object)propertyAccess == null) || (method == propertyAccess.GetOwnOrInheritedGetMethod()) || (method == propertyAccess.GetOwnOrInheritedSetMethod()) || propertyAccess.MustCallMethodsDirectly); CheckArguments(argumentRefKindsOpt, arguments, method); if (_inExpressionLambda) { if (method.CallsAreOmitted(node.SyntaxTree)) { Error(ErrorCode.ERR_PartialMethodInExpressionTree, node); } else if ((object)propertyAccess != null && propertyAccess.IsIndexedProperty() && !propertyAccess.IsIndexer) { Error(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, node); } else if (hasDefaultArgument(arguments, defaultArguments)) { Error(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, node); } else if (!argumentNamesOpt.IsDefaultOrEmpty) { Error(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, node); } else if (IsComCallWithRefOmitted(method, arguments, argumentRefKindsOpt)) { Error(ErrorCode.ERR_ComRefCallInExpressionTree, node); } else if (method.MethodKind == MethodKind.LocalFunction) { Error(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, node); } else if (method.RefKind != RefKind.None) { Error(ErrorCode.ERR_RefReturningCallInExpressionTree, node); } else if (method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } } static bool hasDefaultArgument(ImmutableArray<BoundExpression> arguments, BitVector defaultArguments) { for (int i = 0; i < arguments.Length; i++) { if (defaultArguments[i]) { return true; } } return false; } } public override BoundNode Visit(BoundNode node) { if (_inExpressionLambda && // Ignoring BoundConversion nodes prevents redundant diagnostics !(node is BoundConversion) && node is BoundExpression expr && expr.Type is TypeSymbol type && type.IsRestrictedType()) { Error(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, node, type.Name); } return base.Visit(node); } public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__reftype"); } return base.VisitRefTypeOperator(node); } public override BoundNode VisitRefValueOperator(BoundRefValueOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__refvalue"); } return base.VisitRefValueOperator(node); } public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__makeref"); } return base.VisitMakeRefOperator(node); } public override BoundNode VisitArgListOperator(BoundArgListOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_VarArgsInExpressionTree, node); } return base.VisitArgListOperator(node); } public override BoundNode VisitConditionalAccess(BoundConditionalAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_NullPropagatingOpInExpressionTree, node); } return base.VisitConditionalAccess(node); } public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) { if (_inExpressionLambda && !node.Arguments.IsDefaultOrEmpty) { Error(ErrorCode.ERR_DictionaryInitializerInExpressionTree, node); } if (node.MemberSymbol is PropertySymbol property) { CheckRefReturningPropertyAccess(node, property); } return base.VisitObjectInitializerMember(node); } public override BoundNode VisitCall(BoundCall node) { VisitCall(node.Method, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); CheckReceiverIfField(node.ReceiverOpt); CheckReferenceToMethodIfLocalFunction(node, node.Method); return base.VisitCall(node); } /// <summary> /// Called when a local represents an out variable declaration. Its syntax is of type DeclarationExpressionSyntax. /// </summary> private void CheckOutDeclaration(BoundLocal local) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsOutVariable, local); } } private void CheckDiscard(BoundDiscardExpression argument) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDiscard, argument); } } public override BoundNode VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { if (_inExpressionLambda && node.AddMethod.IsStatic) { Error(ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree, node); } VisitCall(node.AddMethod, null, node.Arguments, default(ImmutableArray<RefKind>), default(ImmutableArray<string>), node.DefaultArguments, node); return base.VisitCollectionElementInitializer(node); } public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) { VisitCall(node.Constructor, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); return base.VisitObjectCreationExpression(node); } public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) { var indexer = node.Indexer; var method = indexer.GetOwnOrInheritedGetMethod() ?? indexer.GetOwnOrInheritedSetMethod(); if ((object)method != null) { VisitCall(method, indexer, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); } CheckReceiverIfField(node.ReceiverOpt); return base.VisitIndexerAccess(node); } private void CheckRefReturningPropertyAccess(BoundNode node, PropertySymbol property) { if (_inExpressionLambda && property.RefKind != RefKind.None) { Error(ErrorCode.ERR_RefReturningCallInExpressionTree, node); } } public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; CheckRefReturningPropertyAccess(node, property); CheckReceiverIfField(node.ReceiverOpt); if (_inExpressionLambda && property.IsAbstract && property.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } return base.VisitPropertyAccess(node); } public override BoundNode VisitLambda(BoundLambda node) { if (_inExpressionLambda) { var lambda = node.Symbol; foreach (var p in lambda.Parameters) { if (p.RefKind != RefKind.None && p.Locations.Length != 0) { _diagnostics.Add(ErrorCode.ERR_ByRefParameterInExpressionTree, p.Locations[0]); } if (p.TypeWithAnnotations.IsRestrictedType()) { _diagnostics.Add(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, p.Locations[0], p.Type.Name); } } switch (node.Syntax.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: { var lambdaSyntax = (ParenthesizedLambdaExpressionSyntax)node.Syntax; if (lambdaSyntax.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword) { Error(ErrorCode.ERR_BadAsyncExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.Block) { Error(ErrorCode.ERR_StatementLambdaToExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.RefExpression) { Error(ErrorCode.ERR_BadRefReturnExpressionTree, node); } } break; case SyntaxKind.SimpleLambdaExpression: { var lambdaSyntax = (SimpleLambdaExpressionSyntax)node.Syntax; if (lambdaSyntax.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword) { Error(ErrorCode.ERR_BadAsyncExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.Block) { Error(ErrorCode.ERR_StatementLambdaToExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.RefExpression) { Error(ErrorCode.ERR_BadRefReturnExpressionTree, node); } } break; case SyntaxKind.AnonymousMethodExpression: Error(ErrorCode.ERR_ExpressionTreeContainsAnonymousMethod, node); break; default: // other syntax forms arise from query expressions, and always result from implied expression-lambda-like forms break; } } var outerLocalFunction = _staticLocalOrAnonymousFunction; if (node.Symbol.IsStatic) { _staticLocalOrAnonymousFunction = node.Symbol; } var result = base.VisitLambda(node); _staticLocalOrAnonymousFunction = outerLocalFunction; return result; } public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { // It is very common for bound trees to be left-heavy binary operators, eg, // a + b + c + d + ... // To avoid blowing the stack, do not recurse down the left hand side. // In order to avoid blowing the stack, we end up visiting right children // before left children; this should not be a problem in the diagnostics // pass. BoundBinaryOperator current = node; while (true) { CheckBinaryOperator(current); Visit(current.Right); if (current.Left.Kind == BoundKind.BinaryOperator) { current = (BoundBinaryOperator)current.Left; } else { Visit(current.Left); break; } } return null; } public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { CheckLiftedUserDefinedConditionalLogicalOperator(node); if (_inExpressionLambda) { var binary = node.LogicalOperator; var unary = node.OperatorKind.Operator() == BinaryOperatorKind.And ? node.FalseOperator : node.TrueOperator; if ((binary.IsAbstract && binary.IsStatic) || (unary.IsAbstract && unary.IsStatic)) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } } return base.VisitUserDefinedConditionalLogicalOperator(node); } private void CheckDynamic(BoundUnaryOperator node) { if (_inExpressionLambda && node.OperatorKind.IsDynamic()) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } } private void CheckDynamic(BoundBinaryOperator node) { if (_inExpressionLambda && node.OperatorKind.IsDynamic()) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } } public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) { CheckUnsafeType(node); CheckLiftedUnaryOp(node); CheckDynamic(node); if (_inExpressionLambda && node.MethodOpt is MethodSymbol method && method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } return base.VisitUnaryOperator(node); } public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) { CheckUnsafeType(node); BoundExpression operand = node.Operand; if (operand.Kind == BoundKind.FieldAccess) { CheckFieldAddress((BoundFieldAccess)operand, consumerOpt: null); } return base.VisitAddressOfOperator(node); } public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); } return base.VisitIncrementOperator(node); } public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) { NoteUnsafe(node); return base.VisitPointerElementAccess(node); } public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { NoteUnsafe(node); return base.VisitPointerIndirectionOperator(node); } public override BoundNode VisitConversion(BoundConversion node) { CheckUnsafeType(node.Operand); CheckUnsafeType(node); bool wasInExpressionLambda = _inExpressionLambda; bool oldReportedUnsafe = _reportedUnsafe; switch (node.ConversionKind) { case ConversionKind.MethodGroup: CheckMethodGroup((BoundMethodGroup)node.Operand, node.Conversion.Method, parentIsConversion: true, node.Type); return node; case ConversionKind.AnonymousFunction: if (!wasInExpressionLambda && node.Type.IsExpressionTree()) { _inExpressionLambda = true; // we report "unsafe in expression tree" at most once for each expression tree _reportedUnsafe = false; } break; case ConversionKind.ImplicitDynamic: case ConversionKind.ExplicitDynamic: if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } break; case ConversionKind.ExplicitTuple: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleConversion, node); } break; case ConversionKind.InterpolatedStringHandler: if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, node); } break; default: if (_inExpressionLambda && node.Conversion.Method is MethodSymbol method && method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } break; } var result = base.VisitConversion(node); _inExpressionLambda = wasInExpressionLambda; _reportedUnsafe = oldReportedUnsafe; return result; } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { if (node.Argument.Kind != BoundKind.MethodGroup) { this.Visit(node.Argument); } else { CheckMethodGroup((BoundMethodGroup)node.Argument, node.MethodOpt, parentIsConversion: true, convertedToType: node.Type); } return null; } public override BoundNode VisitMethodGroup(BoundMethodGroup node) { CheckMethodGroup(node, method: null, parentIsConversion: false, convertedToType: null); return null; } private void CheckMethodGroup(BoundMethodGroup node, MethodSymbol method, bool parentIsConversion, TypeSymbol convertedToType) { // Formerly reported ERR_MemGroupInExpressionTree when this occurred, but the expanded // ERR_LambdaInIsAs makes this impossible (since the node will always be wrapped in // a failed conversion). Debug.Assert(!(!parentIsConversion && _inExpressionLambda)); if (_inExpressionLambda) { if ((node.LookupSymbolOpt as MethodSymbol)?.MethodKind == MethodKind.LocalFunction) { Error(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, node); } else if (parentIsConversion && convertedToType.IsFunctionPointer()) { Error(ErrorCode.ERR_AddressOfMethodGroupInExpressionTree, node); } else if (method is not null && method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } } CheckReceiverIfField(node.ReceiverOpt); CheckReferenceToMethodIfLocalFunction(node, method); if (method is null || method.RequiresInstanceReceiver) { Visit(node.ReceiverOpt); } } public override BoundNode VisitNameOfOperator(BoundNameOfOperator node) { // The nameof(...) operator collapses to a constant in an expression tree, // so it does not matter what is recursively within it. return node; } public override BoundNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { if (_inExpressionLambda && (node.LeftOperand.IsLiteralNull() || node.LeftOperand.IsLiteralDefault())) { Error(ErrorCode.ERR_ExpressionTreeContainsBadCoalesce, node.LeftOperand); } return base.VisitNullCoalescingOperator(node); } public override BoundNode VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeCantContainNullCoalescingAssignment, node); } return base.VisitNullCoalescingAssignmentOperator(node); } public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); // avoid reporting errors for the method group: if (node.Expression.Kind == BoundKind.MethodGroup) { return base.VisitMethodGroup((BoundMethodGroup)node.Expression); } } return base.VisitDynamicInvocation(node); } public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } CheckReceiverIfField(node.Receiver); return base.VisitDynamicIndexerAccess(node); } public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicMemberAccess(node); } public override BoundNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicCollectionElementInitializer(node); } public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicObjectCreationExpression(node); } public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsIsMatch, node); } return base.VisitIsPatternExpression(node); } public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, node); } return base.VisitConvertedTupleLiteral(node); } public override BoundNode VisitTupleLiteral(BoundTupleLiteral node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, node); } return base.VisitTupleLiteral(node); } public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, node); } return base.VisitTupleBinaryOperator(node); } public override BoundNode VisitThrowExpression(BoundThrowExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, node); } return base.VisitThrowExpression(node); } public override BoundNode VisitWithExpression(BoundWithExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsWithExpression, node); } return base.VisitWithExpression(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/Features/VisualBasic/Portable/CodeRefactorings/RemoveStatementCodeAction.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.CodeActions Namespace Microsoft.CodeAnalysis.VisualBasic.CodeActions Friend Class RemoveStatementCodeAction Inherits CodeAction Private ReadOnly _document As Document Private ReadOnly _node As SyntaxNode Private ReadOnly _title As String Public Sub New(document As Document, node As SyntaxNode, title As String) Me._document = document Me._node = node _title = title End Sub Public Overrides ReadOnly Property Title As String Get Return _title End Get End Property Protected Overrides Async Function GetChangedDocumentAsync(cancellationToken As CancellationToken) As Task(Of Document) Dim root = Await _document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim updatedRoot = root.RemoveNode(_node, SyntaxRemoveOptions.KeepUnbalancedDirectives) Return _document.WithSyntaxRoot(updatedRoot) 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.CodeActions Namespace Microsoft.CodeAnalysis.VisualBasic.CodeActions Friend Class RemoveStatementCodeAction Inherits CodeAction Private ReadOnly _document As Document Private ReadOnly _node As SyntaxNode Private ReadOnly _title As String Public Sub New(document As Document, node As SyntaxNode, title As String) Me._document = document Me._node = node _title = title End Sub Public Overrides ReadOnly Property Title As String Get Return _title End Get End Property Protected Overrides Async Function GetChangedDocumentAsync(cancellationToken As CancellationToken) As Task(Of Document) Dim root = Await _document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim updatedRoot = root.RemoveNode(_node, SyntaxRemoveOptions.KeepUnbalancedDirectives) Return _document.WithSyntaxRoot(updatedRoot) 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/Test/Perf/StackDepthTest/StackDepthTest.csproj
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <OutputType>Exe</OutputType> <TargetFramework>net472</TargetFramework> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Xml.Linq" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="Microsoft.CSharp" /> <Reference Include="System.Data" /> <Reference Include="System.Net.Http" /> <Reference Include="System.Xml" /> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> </ItemGroup> <ItemGroup> <None Include="runner.csx" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <OutputType>Exe</OutputType> <TargetFramework>net472</TargetFramework> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Xml.Linq" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="Microsoft.CSharp" /> <Reference Include="System.Data" /> <Reference Include="System.Net.Http" /> <Reference Include="System.Xml" /> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> </ItemGroup> <ItemGroup> <None Include="runner.csx" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> </ItemGroup> </Project>
-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/InternalUtilities/WeakListTests.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.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.InternalUtilities { public class WeakListTests : TestBase { private class C { private readonly string _value; public C(string value) { _value = value; } public override string ToString() { return _value; } } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private ObjectReference<C> Create(string value) { return new ObjectReference<C>(new C(value)); } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private void Add(WeakList<object> list, ObjectReference<C> value) { value.UseReference(r => list.Add(r)); } [Fact] public void EnumeratorCompacts() { var a = Create("a"); var b = Create("B"); var c = Create("C"); var d = Create("D"); var e = Create("E"); var list = new WeakList<object>(); Assert.Equal(0, list.TestOnly_UnderlyingArray.Length); Add(list, a); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, b); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, c); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, d); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, e); Assert.Equal(2 * 4 + 1, list.TestOnly_UnderlyingArray.Length); Assert.Equal(5, list.WeakCount); a.AssertReleased(); c.AssertReleased(); d.AssertReleased(); e.AssertReleased(); Assert.Equal(5, list.WeakCount); Assert.Null(list.GetWeakReference(0).GetTarget()); Assert.Same(b.GetReference(), list.GetWeakReference(1).GetTarget()); Assert.Null(list.GetWeakReference(2).GetTarget()); Assert.Null(list.GetWeakReference(3).GetTarget()); Assert.Null(list.GetWeakReference(4).GetTarget()); var array = list.ToArray(); Assert.Equal(1, array.Length); Assert.Same(b.GetReference(), array[0]); // list was compacted: Assert.Equal(1, list.WeakCount); Assert.Same(b.GetReference(), list.GetWeakReference(0).GetTarget()); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); GC.KeepAlive(b.GetReference()); } [ConditionalFact(typeof(ClrOnly))] public void ResizeCompactsAllDead() { var a = Create("A"); var list = new WeakList<object>(); for (int i = 0; i < 9; i++) { Add(list, a); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); var b = Create("B"); Add(list, b); // shrinks, #alive < length/4 Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Assert.Equal(1, list.WeakCount); b.AssertReleased(); list.ToArray(); // shrinks, #alive == 0 Assert.Equal(0, list.TestOnly_UnderlyingArray.Length); Assert.Equal(0, list.WeakCount); } [Fact] public void ResizeCompactsFirstFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 8; i++) { Add(list, a); } Add(list, b); Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // shrinks, #alive < length/4 Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Assert.Equal(2, list.WeakCount); b.AssertReleased(); list.ToArray(); // shrinks, #alive == 0 Assert.Equal(0, list.TestOnly_UnderlyingArray.Length); Assert.Equal(0, list.WeakCount); } [Fact] public void ResizeCompactsSecondFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 6; i++) { Add(list, a); } for (int i = 0; i < 3; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // just compacts, length/4 < #alive < 3/4 length Assert.Equal(9, list.TestOnly_UnderlyingArray.Length); Assert.Equal(4, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 4) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void ResizeCompactsThirdFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 4; i++) { Add(list, a); } for (int i = 0; i < 5; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // compacts #alive < 3/4 length Assert.Equal(9, list.TestOnly_UnderlyingArray.Length); Assert.Equal(6, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 6) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void ResizeCompactsLastFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 2; i++) { Add(list, a); } for (int i = 0; i < 7; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // expands #alive > 3/4 length Assert.Equal(9 * 2 + 1, list.TestOnly_UnderlyingArray.Length); Assert.Equal(8, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 8) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void ResizeCompactsAllAlive() { var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 9; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full Add(list, b); // expands #alive > 3/4 length Assert.Equal(9 * 2 + 1, list.TestOnly_UnderlyingArray.Length); Assert.Equal(10, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 10) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void Errors() { var list = new WeakList<object>(); Assert.Throws<ArgumentOutOfRangeException>(() => list.GetWeakReference(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => list.GetWeakReference(0)); } } }
// 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.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.InternalUtilities { public class WeakListTests : TestBase { private class C { private readonly string _value; public C(string value) { _value = value; } public override string ToString() { return _value; } } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private ObjectReference<C> Create(string value) { return new ObjectReference<C>(new C(value)); } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private void Add(WeakList<object> list, ObjectReference<C> value) { value.UseReference(r => list.Add(r)); } [Fact] public void EnumeratorCompacts() { var a = Create("a"); var b = Create("B"); var c = Create("C"); var d = Create("D"); var e = Create("E"); var list = new WeakList<object>(); Assert.Equal(0, list.TestOnly_UnderlyingArray.Length); Add(list, a); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, b); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, c); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, d); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, e); Assert.Equal(2 * 4 + 1, list.TestOnly_UnderlyingArray.Length); Assert.Equal(5, list.WeakCount); a.AssertReleased(); c.AssertReleased(); d.AssertReleased(); e.AssertReleased(); Assert.Equal(5, list.WeakCount); Assert.Null(list.GetWeakReference(0).GetTarget()); Assert.Same(b.GetReference(), list.GetWeakReference(1).GetTarget()); Assert.Null(list.GetWeakReference(2).GetTarget()); Assert.Null(list.GetWeakReference(3).GetTarget()); Assert.Null(list.GetWeakReference(4).GetTarget()); var array = list.ToArray(); Assert.Equal(1, array.Length); Assert.Same(b.GetReference(), array[0]); // list was compacted: Assert.Equal(1, list.WeakCount); Assert.Same(b.GetReference(), list.GetWeakReference(0).GetTarget()); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); GC.KeepAlive(b.GetReference()); } [ConditionalFact(typeof(ClrOnly))] public void ResizeCompactsAllDead() { var a = Create("A"); var list = new WeakList<object>(); for (int i = 0; i < 9; i++) { Add(list, a); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); var b = Create("B"); Add(list, b); // shrinks, #alive < length/4 Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Assert.Equal(1, list.WeakCount); b.AssertReleased(); list.ToArray(); // shrinks, #alive == 0 Assert.Equal(0, list.TestOnly_UnderlyingArray.Length); Assert.Equal(0, list.WeakCount); } [Fact] public void ResizeCompactsFirstFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 8; i++) { Add(list, a); } Add(list, b); Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // shrinks, #alive < length/4 Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Assert.Equal(2, list.WeakCount); b.AssertReleased(); list.ToArray(); // shrinks, #alive == 0 Assert.Equal(0, list.TestOnly_UnderlyingArray.Length); Assert.Equal(0, list.WeakCount); } [Fact] public void ResizeCompactsSecondFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 6; i++) { Add(list, a); } for (int i = 0; i < 3; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // just compacts, length/4 < #alive < 3/4 length Assert.Equal(9, list.TestOnly_UnderlyingArray.Length); Assert.Equal(4, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 4) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void ResizeCompactsThirdFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 4; i++) { Add(list, a); } for (int i = 0; i < 5; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // compacts #alive < 3/4 length Assert.Equal(9, list.TestOnly_UnderlyingArray.Length); Assert.Equal(6, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 6) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void ResizeCompactsLastFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 2; i++) { Add(list, a); } for (int i = 0; i < 7; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // expands #alive > 3/4 length Assert.Equal(9 * 2 + 1, list.TestOnly_UnderlyingArray.Length); Assert.Equal(8, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 8) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void ResizeCompactsAllAlive() { var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 9; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full Add(list, b); // expands #alive > 3/4 length Assert.Equal(9 * 2 + 1, list.TestOnly_UnderlyingArray.Length); Assert.Equal(10, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 10) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void Errors() { var list = new WeakList<object>(); Assert.Throws<ArgumentOutOfRangeException>(() => list.GetWeakReference(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => list.GetWeakReference(0)); } } }
-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/OverrideHidingHelper.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 System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Methods, Properties, and Events all can override or hide members. ''' This class has helper methods and extensions for sharing by multiple symbol types. ''' </summary> Friend Class OverrideHidingHelper ''' <summary> ''' Check for overriding and hiding errors in container and report them via diagnostics. ''' </summary> ''' <param name="container">Containing type to check. Should be an original definition.</param> ''' <param name="diagnostics">Place diagnostics here.</param> Public Shared Sub CheckHidingAndOverridingForType(container As SourceMemberContainerTypeSymbol, diagnostics As BindingDiagnosticBag) Debug.Assert(container.IsDefinition) ' Don't do this on constructed types Select Case container.TypeKind Case TypeKind.Class, TypeKind.Interface, TypeKind.Structure CheckMembersAgainstBaseType(container, diagnostics) CheckAllAbstractsAreOverriddenAndNotHidden(container, diagnostics) Case Else ' Modules, Enums and Delegates have nothing to do. End Select End Sub ' Determine if two method or property signatures match, using the rules in 4.1.1, i.e., ByRef mismatches, ' differences in optional parameters, custom modifiers, return type are not considered. An optional parameter ' matches if the corresponding parameter in the other signature is not there, optional of any type, ' or non-optional of matching type. ' ' Note that this sense of matching is not transitive. I.e. ' A) f(x as integer) ' B) f(x as integer, optional y as String = "") ' C) f(x as integer, y As String) ' A matches B, B matches C, but A doesn't match C ' ' Note that (A) and (B) above do match in terms of Dev10 behavior when we look for overridden ' methods/properties. We still keep this behavior in Roslyn to be able to generate the same ' error in the following case: ' ' Class Base ' Public Overridable Sub f(x As Integer) ' End Sub ' End Class ' ' Class Derived ' Inherits Base ' Public Overrides Sub f(x As Integer, Optional y As String = "") ' End Sub ' End Class ' ' >>> error BC30308: 'Public Overrides Sub f(x As Integer, [y As String = ""])' cannot override ' 'Public Overridable Sub f(x As Integer)' because they differ by optional parameters. ' ' In this sense the method returns True if signatures match enough to be ' considered a candidate of overridden member. ' ' But for new overloading rules (overloading based on optional parameters) introduced in Dev11 ' we also need more detailed info on the two members being compared, namely do their signatures ' also match taking into account total parameter count and parameter optionality (optional/required)? ' We return this information in 'exactMatch' parameter. ' ' So when searching for overridden members we prefer exactly matched candidates in case we could ' find them. This helps properly find overridden members in the following case: ' ' Class Base ' Public Overridable Sub f(x As Integer) ' End Sub ' Public Overridable Sub f(x As Integer, Optional y As String = "") ' End Sub ' End Class ' ' Class Derived ' Inherits Base ' Public Overrides Sub f(x As Integer) ' End Sub ' Public Overrides Sub f(x As Integer, Optional y As String = "") ' << Dev11 Beta reports BC30308 ' End Sub ' End Class ' ' Note that Dev11 Beta wrongly reports BC30308 on the last Sub in this case. ' Public Shared Function SignaturesMatch(sym1 As Symbol, sym2 As Symbol, <Out()> ByRef exactMatch As Boolean, <Out()> ByRef exactMatchIgnoringCustomModifiers As Boolean) As Boolean ' NOTE: we should NOT ignore extra required parameters as for overloading Const mismatchesForOverriding As SymbolComparisonResults = (SymbolComparisonResults.AllMismatches And (Not SymbolComparisonResults.MismatchesForConflictingMethods)) Or SymbolComparisonResults.CustomModifierMismatch ' 'Exact match' means that the number of parameters and ' parameter 'optionality' match on two symbol candidates. Const exactMatchIgnoringCustomModifiersMask As SymbolComparisonResults = SymbolComparisonResults.TotalParameterCountMismatch Or SymbolComparisonResults.OptionalParameterTypeMismatch ' Note that exact match doesn't care about tuple element names. Const exactMatchMask As SymbolComparisonResults = exactMatchIgnoringCustomModifiersMask Or SymbolComparisonResults.CustomModifierMismatch Dim results As SymbolComparisonResults = DetailedSignatureCompare(sym1, sym2, mismatchesForOverriding) ' no match If (results And Not exactMatchMask) <> 0 Then exactMatch = False exactMatchIgnoringCustomModifiers = False Return False End If ' match exactMatch = (results And exactMatchMask) = 0 exactMatchIgnoringCustomModifiers = (results And exactMatchIgnoringCustomModifiersMask) = 0 Debug.Assert(Not exactMatch OrElse exactMatchIgnoringCustomModifiers) Return True End Function Friend Shared Function DetailedSignatureCompare( sym1 As Symbol, sym2 As Symbol, comparisons As SymbolComparisonResults, Optional stopIfAny As SymbolComparisonResults = 0 ) As SymbolComparisonResults If sym1.Kind = SymbolKind.Property Then Return PropertySignatureComparer.DetailedCompare(DirectCast(sym1, PropertySymbol), DirectCast(sym2, PropertySymbol), comparisons, stopIfAny) Else Return MethodSignatureComparer.DetailedCompare(DirectCast(sym1, MethodSymbol), DirectCast(sym2, MethodSymbol), comparisons, stopIfAny) End If End Function ''' <summary> ''' Check each member of container for constraints against the base type. For methods and properties and events, ''' checking overriding and hiding constraints. For other members, just check for hiding issues. ''' </summary> ''' <param name="container">Containing type to check. Should be an original definition.</param> ''' <param name="diagnostics">Place diagnostics here.</param> ''' <remarks></remarks> Private Shared Sub CheckMembersAgainstBaseType(container As SourceMemberContainerTypeSymbol, diagnostics As BindingDiagnosticBag) For Each member In container.GetMembers() If CanOverrideOrHide(member) Then Select Case member.Kind Case SymbolKind.Method Dim methodMember = DirectCast(member, MethodSymbol) If Not methodMember.IsAccessor Then If methodMember.IsOverrides Then OverrideHidingHelper(Of MethodSymbol).CheckOverrideMember(methodMember, methodMember.OverriddenMembers, diagnostics) ElseIf methodMember.IsNotOverridable Then 'Method is not marked as Overrides but is marked as Not Overridable diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_NotOverridableRequiresOverrides), methodMember.Locations(0))) End If End If Case SymbolKind.Property Dim propMember = DirectCast(member, PropertySymbol) If propMember.IsOverrides Then OverrideHidingHelper(Of PropertySymbol).CheckOverrideMember(propMember, propMember.OverriddenMembers, diagnostics) ElseIf propMember.IsNotOverridable Then diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_NotOverridableRequiresOverrides), propMember.Locations(0))) End If End Select ' TODO: only do this check if CheckOverrideMember didn't find an error? CheckShadowing(container, member, diagnostics) End If Next End Sub ''' <summary> ''' If the "container" is a non-MustInherit, make sure it has no MustOverride Members ''' If "container" is a non-MustInherit inheriting from a MustInherit, make sure that all MustOverride members ''' have been overridden. ''' If "container" is a MustInherit inheriting from a MustInherit, make sure that no MustOverride members ''' have been shadowed. ''' </summary> Private Shared Sub CheckAllAbstractsAreOverriddenAndNotHidden(container As NamedTypeSymbol, diagnostics As BindingDiagnosticBag) ' Check that a non-MustInherit class doesn't have any MustOverride members If Not (container.IsMustInherit OrElse container.IsNotInheritable) Then For Each member In container.GetMembers() If member.IsMustOverride Then diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_MustOverridesInClass1, container.Name), container.Locations(0))) Exit For End If Next End If Dim baseType As NamedTypeSymbol = container.BaseTypeNoUseSiteDiagnostics If baseType IsNot Nothing AndAlso baseType.IsMustInherit Then ' Check that all MustOverride members in baseType or one of its bases are overridden/not shadowed somewhere along the chain. ' Do this by accumulating a set of all the methods that have been overridden, if we encounter a MustOverride ' method that is not in the set, then report it. We can do this in a single pass up the base chain. Dim overriddenMembers As HashSet(Of Symbol) = New HashSet(Of Symbol)() Dim unimplementedMembers As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance() Dim currType = container While currType IsNot Nothing For Each member In currType.GetMembers() If CanOverrideOrHide(member) AndAlso Not member.IsAccessor Then ' accessors handled by their containing properties. If member.IsOverrides Then Dim overriddenMember = GetOverriddenMember(member) If overriddenMember IsNot Nothing Then overriddenMembers.Add(GetOverriddenMember(member)) End If End If If member.IsMustOverride AndAlso currType IsNot container Then If Not overriddenMembers.Contains(member) Then unimplementedMembers.Add(member) End If End If End If Next currType = currType.BaseTypeNoUseSiteDiagnostics End While If unimplementedMembers.Any Then If container.IsMustInherit Then ' It is OK for a IsMustInherit type to have unimplemented abstract members. But, it is not allowed ' to shadow them. Check each one to see if it is shadowed by a member of "container". Don't report for ' accessor hiding accessor, because we'll report it on the property. Dim hidingSymbols As New HashSet(Of Symbol) ' don't report more than once per hiding symbols For Each mustOverrideMember In unimplementedMembers For Each hidingMember In container.GetMembers(mustOverrideMember.Name) If DoesHide(hidingMember, mustOverrideMember) AndAlso Not hidingSymbols.Contains(hidingMember) Then ReportShadowingMustOverrideError(hidingMember, mustOverrideMember, diagnostics) hidingSymbols.Add(hidingMember) End If Next Next Else ' This is not a IsMustInherit type. Some members should be been overridden but weren't. ' Create a single error that lists all of the unimplemented members. Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance(unimplementedMembers.Count) For Each member In unimplementedMembers If Not member.IsAccessor Then If member.Kind = SymbolKind.Event Then diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_MustInheritEventNotOverridden, member, CustomSymbolDisplayFormatter.QualifiedName(member.ContainingType), CustomSymbolDisplayFormatter.ShortErrorName(container)), container.Locations(0))) Else diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_UnimplementedMustOverride, member.ContainingType, member)) End If Else ' accessor is reported on the containing property. Debug.Assert(unimplementedMembers.Contains(DirectCast(member, MethodSymbol).AssociatedSymbol)) End If Next If diagnosticInfos.Count > 0 Then diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_BaseOnlyClassesMustBeExplicit2, CustomSymbolDisplayFormatter.ShortErrorName(container), New CompoundDiagnosticInfo(diagnosticInfos.ToArrayAndFree())), container.Locations(0))) Else diagnosticInfos.Free() End If End If End If unimplementedMembers.Free() End If End Sub ' Compare two symbols of the same name to see if one actually does hide the other. Private Shared Function DoesHide(hidingMember As Symbol, hiddenMember As Symbol) As Boolean Debug.Assert(IdentifierComparison.Equals(hidingMember.Name, hiddenMember.Name)) Select Case hidingMember.Kind Case SymbolKind.Method If hidingMember.IsOverloads AndAlso hiddenMember.Kind = SymbolKind.Method Then Dim hidingMethod = DirectCast(hidingMember, MethodSymbol) If hidingMethod.IsOverrides Then ' For Dev10 compatibility, an override is not considered as hiding (see bug 11728) Return False Else Dim exactMatchIgnoringCustomModifiers As Boolean = False Return OverrideHidingHelper(Of MethodSymbol).SignaturesMatch(hidingMethod, DirectCast(hiddenMember, MethodSymbol), Nothing, exactMatchIgnoringCustomModifiers) AndAlso exactMatchIgnoringCustomModifiers End If Else Return True End If Case SymbolKind.Property If hidingMember.IsOverloads AndAlso hiddenMember.Kind = SymbolKind.Property Then Dim hidingProperty = DirectCast(hidingMember, PropertySymbol) If hidingProperty.IsOverrides Then ' For Dev10 compatibility, an override is not considered as hiding (see bug 11728) Return False Else Dim exactMatchIgnoringCustomModifiers As Boolean = False Return OverrideHidingHelper(Of PropertySymbol).SignaturesMatch(hidingProperty, DirectCast(hiddenMember, PropertySymbol), Nothing, exactMatchIgnoringCustomModifiers) AndAlso exactMatchIgnoringCustomModifiers End If Else Return True End If Case Else Return True End Select End Function ''' <summary> ''' Report any diagnostics related to shadowing for a member. ''' </summary> Protected Shared Sub CheckShadowing(container As SourceMemberContainerTypeSymbol, member As Symbol, diagnostics As BindingDiagnosticBag) Dim memberIsOverloads = member.IsOverloads() Dim warnForHiddenMember As Boolean = Not member.ShadowsExplicitly If Not warnForHiddenMember Then Return ' short circuit unnecessary checks. End If If container.IsInterfaceType() Then For Each currentBaseInterface In container.AllInterfacesNoUseSiteDiagnostics CheckShadowingInBaseType(container, member, memberIsOverloads, currentBaseInterface, diagnostics, warnForHiddenMember) Next Else Dim currentBase As NamedTypeSymbol = container.BaseTypeNoUseSiteDiagnostics While currentBase IsNot Nothing CheckShadowingInBaseType(container, member, memberIsOverloads, currentBase, diagnostics, warnForHiddenMember) currentBase = currentBase.BaseTypeNoUseSiteDiagnostics End While End If End Sub ' Check shadowing against members in one base type. Private Shared Sub CheckShadowingInBaseType(container As SourceMemberContainerTypeSymbol, member As Symbol, memberIsOverloads As Boolean, baseType As NamedTypeSymbol, diagnostics As BindingDiagnosticBag, ByRef warnForHiddenMember As Boolean) Debug.Assert(container.IsDefinition) If warnForHiddenMember Then For Each hiddenMember In baseType.GetMembers(member.Name) If AccessCheck.IsSymbolAccessible(hiddenMember, container, Nothing, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso (Not memberIsOverloads OrElse hiddenMember.Kind <> member.Kind OrElse hiddenMember.IsWithEventsProperty OrElse (member.Kind = SymbolKind.Method AndAlso DirectCast(member, MethodSymbol).IsUserDefinedOperator() <> DirectCast(hiddenMember, MethodSymbol).IsUserDefinedOperator()) OrElse member.IsAccessor() <> hiddenMember.IsAccessor) AndAlso Not (member.IsAccessor() AndAlso hiddenMember.IsAccessor) Then 'special case for classes of different arity . Do not warn in such case If member.Kind = SymbolKind.NamedType AndAlso hiddenMember.Kind = SymbolKind.NamedType AndAlso member.GetArity <> hiddenMember.GetArity Then Continue For End If ' Found an accessible member we are hiding and not overloading. ' We don't warn if accessor hides accessor, because we will warn on the containing properties instead. ' Give warning for shadowing hidden member ReportShadowingDiagnostic(member, hiddenMember, diagnostics) warnForHiddenMember = False ' don't warn for more than one hidden member. Exit For End If Next End If End Sub ' Report diagnostic for one member shadowing another, but no Shadows modifier was present. Private Shared Sub ReportShadowingDiagnostic(hidingMember As Symbol, hiddenMember As Symbol, diagnostics As BindingDiagnosticBag) Debug.Assert(Not (hidingMember.IsAccessor() AndAlso hiddenMember.IsAccessor)) Dim associatedhiddenSymbol = hiddenMember.ImplicitlyDefinedBy If associatedhiddenSymbol Is Nothing AndAlso hiddenMember.IsUserDefinedOperator() AndAlso Not hidingMember.IsUserDefinedOperator() Then ' For the purpose of this check, operator methods are treated as implicitly defined by themselves. associatedhiddenSymbol = hiddenMember End If Dim associatedhidingSymbol = hidingMember.ImplicitlyDefinedBy If associatedhidingSymbol Is Nothing AndAlso hidingMember.IsUserDefinedOperator() AndAlso Not hiddenMember.IsUserDefinedOperator() Then ' For the purpose of this check, operator methods are treated as implicitly defined by themselves. associatedhidingSymbol = hidingMember End If If associatedhiddenSymbol IsNot Nothing Then If associatedhidingSymbol IsNot Nothing Then If Not IdentifierComparison.Equals(associatedhiddenSymbol.Name, associatedhidingSymbol.Name) Then ' both members are defined implicitly by members of different names diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_SynthMemberShadowsSynthMember7, associatedhidingSymbol.GetKindText(), AssociatedSymbolName(associatedhidingSymbol), hidingMember.Name, associatedhiddenSymbol.GetKindText(), AssociatedSymbolName(associatedhiddenSymbol), hiddenMember.ContainingType.GetKindText(), CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)), hidingMember.Locations(0))) End If Return End If ' explicitly defined member hiding implicitly defined member diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_MemberShadowsSynthMember6, hidingMember.GetKindText(), hidingMember.Name, associatedhiddenSymbol.GetKindText(), AssociatedSymbolName(associatedhiddenSymbol), hiddenMember.ContainingType.GetKindText(), CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)), hidingMember.Locations(0))) ElseIf associatedhidingSymbol IsNot Nothing Then ' implicitly defined member hiding explicitly defined member diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_SynthMemberShadowsMember5, associatedhidingSymbol.GetKindText(), AssociatedSymbolName(associatedhidingSymbol), hidingMember.Name, hiddenMember.ContainingType.GetKindText(), CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)), associatedhidingSymbol.Locations(0))) ElseIf hidingMember.Kind = hiddenMember.Kind AndAlso (hidingMember.Kind = SymbolKind.Property OrElse hidingMember.Kind = SymbolKind.Method) AndAlso Not (hiddenMember.IsWithEventsProperty OrElse hidingMember.IsWithEventsProperty) Then ' method hiding method or property hiding property; message depends on if hidden symbol is overridable. Dim id As ERRID If hiddenMember.IsOverridable OrElse hiddenMember.IsOverrides OrElse (hiddenMember.IsMustOverride AndAlso Not hiddenMember.ContainingType.IsInterface) Then id = ERRID.WRN_MustOverride2 Else id = ERRID.WRN_MustOverloadBase4 End If diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(id, hidingMember.GetKindText(), hidingMember.Name, hiddenMember.ContainingType.GetKindText(), CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)), hidingMember.Locations(0))) Else ' all other hiding scenarios. Debug.Assert(hidingMember.Locations(0).IsInSource) diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_OverrideType5, hidingMember.GetKindText(), hidingMember.Name, hiddenMember.GetKindText(), hiddenMember.ContainingType.GetKindText(), CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)), hidingMember.Locations(0))) End If End Sub Public Shared Function AssociatedSymbolName(associatedSymbol As Symbol) As String Return If(associatedSymbol.IsUserDefinedOperator(), SyntaxFacts.GetText(OverloadResolution.GetOperatorTokenKind(associatedSymbol.Name)), associatedSymbol.Name) End Function ' Report diagnostic for a member shadowing a MustOverride. Private Shared Sub ReportShadowingMustOverrideError(hidingMember As Symbol, hiddenMember As Symbol, diagnostics As BindingDiagnosticBag) Debug.Assert(hidingMember.Locations(0).IsInSource) If hidingMember.IsAccessor() Then ' accessor hiding non-accessorTODO Dim associatedHidingSymbol = DirectCast(hidingMember, MethodSymbol).AssociatedSymbol diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_SynthMemberShadowsMustOverride5, hidingMember, associatedHidingSymbol.GetKindText(), associatedHidingSymbol.Name, hiddenMember.ContainingType.GetKindText(), CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)), hidingMember.Locations(0))) Else ' Basic hiding case diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_CantShadowAMustOverride1, hidingMember), hidingMember.Locations(0))) End If End Sub ''' <summary> ''' Some symbols do not participate in overriding/hiding (e.g. constructors). Accessors are consider ''' to override or hide. ''' </summary> Friend Shared Function CanOverrideOrHide(sym As Symbol) As Boolean If sym.Kind <> SymbolKind.Method Then Return True Else Select Case DirectCast(sym, MethodSymbol).MethodKind Case MethodKind.LambdaMethod, MethodKind.Constructor, MethodKind.SharedConstructor Return False Case MethodKind.Conversion, MethodKind.DelegateInvoke, MethodKind.UserDefinedOperator, MethodKind.Ordinary, MethodKind.DeclareMethod, MethodKind.EventAdd, MethodKind.EventRaise, MethodKind.EventRemove, MethodKind.PropertyGet, MethodKind.PropertySet Return True Case Else Debug.Assert(False, String.Format("Unexpected method kind '{0}'", DirectCast(sym, MethodSymbol).MethodKind)) Return False End Select End If End Function ' If this member overrides another member, return that overridden member, else return Nothing. Protected Shared Function GetOverriddenMember(sym As Symbol) As Symbol Select Case sym.Kind Case SymbolKind.Method Return DirectCast(sym, MethodSymbol).OverriddenMethod Case SymbolKind.Property Return DirectCast(sym, PropertySymbol).OverriddenProperty Case SymbolKind.Event Return DirectCast(sym, EventSymbol).OverriddenEvent End Select Return Nothing End Function ''' <summary> ''' If a method had a virtual inaccessible override, then an explicit override in metadata is needed ''' to make it really override what it intends to override, and "skip" the inaccessible virtual ''' method. ''' </summary> Public Shared Function RequiresExplicitOverride(method As MethodSymbol) As Boolean If method.IsAccessor Then If TypeOf method.AssociatedSymbol Is EventSymbol Then ' VB does not override events Return False End If Return RequiresExplicitOverride(DirectCast(method.AssociatedSymbol, PropertySymbol)) End If If method.OverriddenMethod IsNot Nothing Then For Each inaccessibleOverride In method.OverriddenMembers.InaccessibleMembers If inaccessibleOverride.IsOverridable OrElse inaccessibleOverride.IsMustOverride OrElse inaccessibleOverride.IsOverrides Then Return True End If Next End If Return False End Function Private Shared Function RequiresExplicitOverride(prop As PropertySymbol) As Boolean If prop.OverriddenProperty IsNot Nothing Then For Each inaccessibleOverride In prop.OverriddenMembers.InaccessibleMembers If inaccessibleOverride.IsOverridable OrElse inaccessibleOverride.IsMustOverride OrElse inaccessibleOverride.IsOverrides Then Return True End If Next End If Return False End Function Private Shared Function RequiresExplicitOverride([event] As EventSymbol) As Boolean If [event].OverriddenEvent IsNot Nothing Then For Each inaccessibleOverride In [event].OverriddenOrHiddenMembers.InaccessibleMembers If inaccessibleOverride.IsOverridable OrElse inaccessibleOverride.IsMustOverride OrElse inaccessibleOverride.IsOverrides Then Return True End If Next End If Return False End Function End Class ''' <summary> ''' Many of the methods want to generically work on properties, methods (and maybe events) as TSymbol. We put all these ''' methods into a generic class for convenience. ''' </summary> Friend Class OverrideHidingHelper(Of TSymbol As Symbol) Inherits OverrideHidingHelper ' Comparer for comparing signatures of TSymbols in a runtime-equivalent way. ' It is not ReadOnly because it is initialized by a Shared Sub New of another instance of this class. #Disable Warning IDE0044 ' Add readonly modifier - Adding readonly generates compile error in the constructor. - see https://github.com/dotnet/roslyn/issues/47197 Private Shared s_runtimeSignatureComparer As IEqualityComparer(Of TSymbol) #Enable Warning IDE0044 ' Add readonly modifier ' Initialize the various kinds of comparers. Shared Sub New() OverrideHidingHelper(Of MethodSymbol).s_runtimeSignatureComparer = MethodSignatureComparer.RuntimeMethodSignatureComparer OverrideHidingHelper(Of PropertySymbol).s_runtimeSignatureComparer = PropertySignatureComparer.RuntimePropertySignatureComparer OverrideHidingHelper(Of EventSymbol).s_runtimeSignatureComparer = EventSignatureComparer.RuntimeEventSignatureComparer End Sub ''' <summary> ''' Walk up the type hierarchy from ContainingType and list members that this ''' method overrides (accessible methods/properties with the same signature, if this ''' method is declared "override"). ''' ''' Methods in the overridden list may not be virtual or may have different ''' accessibilities, types, accessors, etc. They are really candidates to be ''' overridden. ''' ''' All found accessible candidates of overridden members are collected in two ''' builders, those with 'exactly' matching signatures and those with 'generally' ''' or 'inexactly' matching signatures. 'Exact' signature match is a 'general' ''' signature match which also does not have mismatches in total number of parameters ''' and/or types of optional parameters. See also comments on correspondent ''' OverriddenMembersResult(Of TSymbol) properties. ''' ''' 'Inexactly' matching candidates are only collected for reporting Dev10/Dev11 ''' errors like BC30697 and others. We collect 'inexact' matching candidates until ''' we find any 'exact' match. ''' ''' Also remembers inaccessible members that are found, but these do not prevent ''' continuing to search for accessible members. ''' ''' </summary> ''' <remarks> ''' In the presence of non-VB types, the meaning of "same signature" is rather ''' complicated. If this method isn't from source, then it refers to the runtime's ''' notion of signature (i.e. including return type, custom modifiers, etc). ''' If this method is from source, use the VB version of signature. Note that ''' Dev10 C# has a rule that prefers members with less custom modifiers. Dev 10 VB has no ''' such rule, so I'm not adding such a rule here. ''' </remarks> Friend Shared Function MakeOverriddenMembers(overridingSym As TSymbol) As OverriddenMembersResult(Of TSymbol) If Not overridingSym.IsOverrides OrElse Not CanOverrideOrHide(overridingSym) Then Return OverriddenMembersResult(Of TSymbol).Empty End If ' We should not be here for constructed methods, since overriding/hiding doesn't really make sense for them. Debug.Assert(Not (TypeOf overridingSym Is MethodSymbol AndAlso DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).ConstructedFrom <> overridingSym)) ' We should not be here for property accessors (but ok for event accessors). ' TODO: When we support virtual events, that might change. Debug.Assert(Not (TypeOf overridingSym Is MethodSymbol AndAlso (DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).MethodKind = MethodKind.PropertyGet OrElse DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).MethodKind = MethodKind.PropertySet))) ' NOTE: If our goal is to make source references and metadata references indistinguishable, then we should really ' distinguish between the "current" compilation and other compilations, rather than between source and metadata. ' However, doing so would require adding a new parameter to the public API (i.e. which compilation to consider ' "current") and that extra complexity does not seem to provide significant benefit. Our fallback goal is: ' if a source assembly builds successfully, then compilations referencing that assembly should build against ' both source and metadata or fail to build against both source and metadata. Our expectation is that an exact ' match (which is required for successful compilation) should roundtrip through metadata, so this requirement ' should be met. Dim overridingIsFromSomeCompilation As Boolean = overridingSym.Dangerous_IsFromSomeCompilationIncludingRetargeting Dim containingType As NamedTypeSymbol = overridingSym.ContainingType Dim overriddenBuilder As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance() Dim inexactOverriddenMembers As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance() Dim inaccessibleBuilder As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance() Debug.Assert(Not containingType.IsInterface, "An interface member can't be marked overrides") Dim currType As NamedTypeSymbol = containingType.BaseTypeNoUseSiteDiagnostics While currType IsNot Nothing If FindOverriddenMembersInType(overridingSym, overridingIsFromSomeCompilation, containingType, currType, overriddenBuilder, inexactOverriddenMembers, inaccessibleBuilder) Then Exit While ' Once we hit an overriding or hiding member, we're done. End If currType = currType.BaseTypeNoUseSiteDiagnostics End While Return OverriddenMembersResult(Of TSymbol).Create(overriddenBuilder.ToImmutableAndFree(), inexactOverriddenMembers.ToImmutableAndFree(), inaccessibleBuilder.ToImmutableAndFree()) End Function ''' <summary> ''' Look for overridden members in a specific type. Return true if we find an overridden member candidate ''' with 'exact' signature match, or we hit a member that hides. See comments on MakeOverriddenMembers(...) ''' for description of 'exact' and 'inexact' signature matches. ''' ''' Also remember any inaccessible members that we see. ''' </summary> ''' <param name="overridingSym">Syntax that overriding or hiding.</param> ''' <param name="overridingIsFromSomeCompilation">True if "overridingSym" is from source (this.IsFromSomeCompilation).</param> ''' <param name="overridingContainingType">The type that contains this method (this.ContainingType).</param> ''' <param name="currType">The type to search.</param> ''' <param name="overriddenBuilder">Builder to place exactly-matched overridden member candidates in. </param> ''' <param name="inexactOverriddenMembers">Builder to place inexactly-matched overridden member candidates in. </param> ''' <param name="inaccessibleBuilder">Builder to place exactly-matched inaccessible overridden member candidates in. </param> Private Shared Function FindOverriddenMembersInType(overridingSym As TSymbol, overridingIsFromSomeCompilation As Boolean, overridingContainingType As NamedTypeSymbol, currType As NamedTypeSymbol, overriddenBuilder As ArrayBuilder(Of TSymbol), inexactOverriddenMembers As ArrayBuilder(Of TSymbol), inaccessibleBuilder As ArrayBuilder(Of TSymbol)) As Boolean ' Note that overriddenBuilder may contain some non-exact ' matched symbols found in previous iterations ' We should not be here for property accessors (but ok for event accessors). ' TODO: When we support virtual events, that might change. Debug.Assert(Not (TypeOf overridingSym Is MethodSymbol AndAlso (DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).MethodKind = MethodKind.PropertyGet OrElse DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).MethodKind = MethodKind.PropertySet))) Dim stopLookup As Boolean = False Dim haveExactMatch As Boolean = False Dim overriddenInThisType As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance() For Each sym In currType.GetMembers(overridingSym.Name) ProcessMemberWithMatchingName(sym, overridingSym, overridingIsFromSomeCompilation, overridingContainingType, inexactOverriddenMembers, inaccessibleBuilder, overriddenInThisType, stopLookup, haveExactMatch) Next If overridingSym.Kind = SymbolKind.Property Then Dim prop = DirectCast(DirectCast(overridingSym, Object), PropertySymbol) If prop.IsImplicitlyDeclared AndAlso prop.IsWithEvents Then For Each sym In currType.GetSynthesizedWithEventsOverrides() If sym.Name.Equals(prop.Name) Then ProcessMemberWithMatchingName(sym, overridingSym, overridingIsFromSomeCompilation, overridingContainingType, inexactOverriddenMembers, inaccessibleBuilder, overriddenInThisType, stopLookup, haveExactMatch) End If Next End If End If If overriddenInThisType.Count > 1 Then RemoveMembersWithConflictingAccessibility(overriddenInThisType) End If If overriddenInThisType.Count > 0 Then If haveExactMatch Then Debug.Assert(stopLookup) overriddenBuilder.Clear() End If If overriddenBuilder.Count = 0 Then overriddenBuilder.AddRange(overriddenInThisType) End If End If overriddenInThisType.Free() Return stopLookup End Function Private Shared Sub ProcessMemberWithMatchingName( sym As Symbol, overridingSym As TSymbol, overridingIsFromSomeCompilation As Boolean, overridingContainingType As NamedTypeSymbol, inexactOverriddenMembers As ArrayBuilder(Of TSymbol), inaccessibleBuilder As ArrayBuilder(Of TSymbol), overriddenInThisType As ArrayBuilder(Of TSymbol), ByRef stopLookup As Boolean, ByRef haveExactMatch As Boolean ) ' Use original definition for accessibility check, because substitutions can cause ' reductions in accessibility that aren't appropriate (see bug #12038 for example). Dim accessible = AccessCheck.IsSymbolAccessible(sym.OriginalDefinition, overridingContainingType.OriginalDefinition, Nothing, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If sym.Kind = overridingSym.Kind AndAlso CanOverrideOrHide(sym) Then Dim member As TSymbol = DirectCast(sym, TSymbol) Dim exactMatch As Boolean = True ' considered to be True for all runtime signature comparisons Dim exactMatchIgnoringCustomModifiers As Boolean = True ' considered to be True for all runtime signature comparisons If If(overridingIsFromSomeCompilation, sym.IsWithEventsProperty = overridingSym.IsWithEventsProperty AndAlso SignaturesMatch(overridingSym, member, exactMatch, exactMatchIgnoringCustomModifiers), s_runtimeSignatureComparer.Equals(overridingSym, member)) Then If accessible Then If exactMatchIgnoringCustomModifiers Then If exactMatch Then If Not haveExactMatch Then haveExactMatch = True stopLookup = True overriddenInThisType.Clear() End If overriddenInThisType.Add(member) ElseIf Not haveExactMatch Then overriddenInThisType.Add(member) End If Else ' Add only if not hidden by signature AddMemberToABuilder(member, inexactOverriddenMembers) End If Else If exactMatchIgnoringCustomModifiers Then ' only exact matched methods are to be added inaccessibleBuilder.Add(member) End If End If ElseIf Not member.IsOverloads() AndAlso accessible Then ' hiding symbol by name stopLookup = True End If ElseIf accessible Then ' Any accessible symbol of different kind stops further lookup stopLookup = True End If End Sub Private Shared Sub AddMemberToABuilder(member As TSymbol, builder As ArrayBuilder(Of TSymbol)) ' We should only add a member to a builder if it does not match any ' symbols from previously processed (derived) classes ' This is supposed to help avoid adding multiple symbols one of ' which overrides another one, in the following case ' C1 ' Overridable Sub S(x As Integer, Optional y As Integer = 1) ' ' C2: C1 ' Overridable Sub S(x As Integer) ' ' C3: C2 ' Overrides Sub S(x As Integer) ' ' C4: C3 ' Overrides Sub S(x As Integer, Optional y As Integer = 1) ' In the case above we should not add 'S(x As Integer)' twice ' We don't use 'OverriddenMethod' property on MethodSymbol because ' right now it does not cache the result, so we want to avoid ' unnecessary nested calls to 'MakeOverriddenMembers' Dim memberContainingType As NamedTypeSymbol = member.ContainingType For i = 0 To builder.Count - 1 Dim exactMatchIgnoringCustomModifiers As Boolean = False If Not TypeSymbol.Equals(builder(i).ContainingType, memberContainingType, TypeCompareKind.ConsiderEverything) AndAlso SignaturesMatch(builder(i), member, Nothing, exactMatchIgnoringCustomModifiers) AndAlso exactMatchIgnoringCustomModifiers Then ' Do NOT add Exit Sub End If Next builder.Add(member) End Sub ' Check a member that is marked Override against it's base and report any necessary diagnostics. The already computed ' overridden members are passed in. Friend Shared Sub CheckOverrideMember(member As TSymbol, overriddenMembersResult As OverriddenMembersResult(Of TSymbol), diagnostics As BindingDiagnosticBag) Debug.Assert(overriddenMembersResult IsNot Nothing) Dim memberIsShadows As Boolean = member.ShadowsExplicitly Dim memberIsOverloads As Boolean = member.IsOverloads() Dim overriddenMembers As ImmutableArray(Of TSymbol) = overriddenMembersResult.OverriddenMembers ' If there are no overridden members (those with 'exactly' matching signature) ' analyze overridden member candidates with 'generally' matching signature If overriddenMembers.IsEmpty Then overriddenMembers = overriddenMembersResult.InexactOverriddenMembers End If If overriddenMembers.Length = 0 Then ' Did not have member to override. But there might have been an inaccessible one. If overriddenMembersResult.InaccessibleMembers.Length > 0 Then ReportBadOverriding(ERRID.ERR_CannotOverrideInAccessibleMember, member, overriddenMembersResult.InaccessibleMembers(0), diagnostics) Else diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_OverrideNotNeeded3, member.GetKindText(), member.Name), member.Locations(0))) End If ElseIf overriddenMembers.Length > 1 Then ' Multiple members we could be overriding. Create a single error message that lists them all. Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance(overriddenMembers.Length) For Each overriddenMemb In overriddenMembers diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverriddenCandidate1, overriddenMemb.OriginalDefinition)) Next diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_AmbiguousOverrides3, overriddenMembers(0), CustomSymbolDisplayFormatter.ShortErrorName(overriddenMembers(0).ContainingType), New CompoundDiagnosticInfo(diagnosticInfos.ToArrayAndFree())), member.Locations(0))) Else ' overriding exactly one member. Dim overriddenMember As TSymbol = overriddenMembers(0) Dim comparisonResults As SymbolComparisonResults = DetailedSignatureCompare(member, overriddenMember, SymbolComparisonResults.AllMismatches) Dim errorId As ERRID If overriddenMember.IsNotOverridable Then ReportBadOverriding(ERRID.ERR_CantOverrideNotOverridable2, member, overriddenMember, diagnostics) ElseIf Not (overriddenMember.IsOverridable Or overriddenMember.IsMustOverride Or overriddenMember.IsOverrides) Then ReportBadOverriding(ERRID.ERR_CantOverride4, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.ParameterByrefMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverrideWithByref2, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.OptionalParameterMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverrideWithOptional2, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.ReturnTypeMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_InvalidOverrideDueToReturn2, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.PropertyAccessorMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverridingPropertyKind2, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.PropertyInitOnlyMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverridingInitOnlyProperty, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.ParamArrayMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverrideWithArrayVsParamArray2, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.OptionalParameterTypeMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverrideWithOptionalTypes2, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.OptionalParameterValueMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverrideWithDefault2, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.ConstraintMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverrideWithConstraintMismatch2, member, overriddenMember, diagnostics) ElseIf Not ConsistentAccessibility(member, overriddenMember, errorId) Then ReportBadOverriding(errorId, member, overriddenMember, diagnostics) ElseIf member.ContainsTupleNames() AndAlso (comparisonResults And SymbolComparisonResults.TupleNamesMismatch) <> 0 Then ' it is ok to override with no tuple names, for compatibility with VB 14, but otherwise names should match ReportBadOverriding(ERRID.WRN_InvalidOverrideDueToTupleNames2, member, overriddenMember, diagnostics) Else For Each inaccessibleMember In overriddenMembersResult.InaccessibleMembers If inaccessibleMember.DeclaredAccessibility = Accessibility.Friend AndAlso inaccessibleMember.OverriddenMember = overriddenMember Then ' We have an inaccessible friend member that overrides the member we're trying to override. ' We can't do that, so issue an error. diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_InAccessibleOverridingMethod5, member, member.ContainingType, overriddenMember, overriddenMember.ContainingType, inaccessibleMember.ContainingType), member.Locations(0))) End If Next Dim useSiteInfo = overriddenMember.GetUseSiteInfo() If Not diagnostics.Add(useSiteInfo, member.Locations(0)) AndAlso member.Kind = SymbolKind.Property Then ' No overriding errors found in member. If its a property, its accessors might have issues. Dim overridingProperty As PropertySymbol = DirectCast(DirectCast(member, Symbol), PropertySymbol) Dim overriddenProperty As PropertySymbol = DirectCast(DirectCast(overriddenMember, Symbol), PropertySymbol) CheckOverridePropertyAccessor(overridingProperty.GetMethod, overriddenProperty.GetMethod, diagnostics) CheckOverridePropertyAccessor(overridingProperty.SetMethod, overriddenProperty.SetMethod, diagnostics) End If End If End If End Sub ' Imported types can have multiple members with the same signature (case insensitive) and different accessibilities. VB prefers ' members that are "more accessible". This is a very rare code path if members has > 1 element so we don't worry about performance. Private Shared Sub RemoveMembersWithConflictingAccessibility(members As ArrayBuilder(Of TSymbol)) If members.Count < 2 Then Return End If Const significantDifferences As SymbolComparisonResults = SymbolComparisonResults.AllMismatches And Not SymbolComparisonResults.MismatchesForConflictingMethods Dim nonConflicting As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance() For Each sym In members Dim isWorseThanAnother As Boolean = False For Each otherSym In members If sym IsNot otherSym Then Dim originalSym = sym.OriginalDefinition Dim originalOther = otherSym.OriginalDefinition ' Two original definitions with identical signatures in same containing types are compared by accessibility, and ' more accessible wins. If TypeSymbol.Equals(originalSym.ContainingType, originalOther.ContainingType, TypeCompareKind.ConsiderEverything) AndAlso DetailedSignatureCompare(originalSym, originalOther, significantDifferences) = 0 AndAlso LookupResult.CompareAccessibilityOfSymbolsConflictingInSameContainer(originalSym, originalOther) < 0 Then ' sym is worse than otherSym isWorseThanAnother = True Exit For End If End If Next If Not isWorseThanAnother Then nonConflicting.Add(sym) End If Next If nonConflicting.Count <> members.Count Then members.Clear() members.AddRange(nonConflicting) End If nonConflicting.Free() End Sub ' Check an accessor with respect to its overridden accessor and report any diagnostics Friend Shared Sub CheckOverridePropertyAccessor(overridingAccessor As MethodSymbol, overriddenAccessor As MethodSymbol, diagnostics As BindingDiagnosticBag) ' CONSIDER: it is possible for an accessor to have a use site error even when the property ' does not but, in general, we have not been handling cases where property and accessor ' signatures are mismatched (e.g. different modopts). If overridingAccessor IsNot Nothing AndAlso overriddenAccessor IsNot Nothing Then ' Use original definition for accessibility check, because substitutions can cause ' reductions in accessibility that aren't appropriate (see bug #12038 for example). If Not AccessCheck.IsSymbolAccessible(overriddenAccessor.OriginalDefinition, overridingAccessor.ContainingType, Nothing, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then ReportBadOverriding(ERRID.ERR_CannotOverrideInAccessibleMember, overridingAccessor, overriddenAccessor, diagnostics) Else Dim errorId As ERRID If Not ConsistentAccessibility(overridingAccessor, overriddenAccessor, errorId) Then ReportBadOverriding(errorId, overridingAccessor, overriddenAccessor, diagnostics) End If End If diagnostics.Add(overriddenAccessor.GetUseSiteInfo(), overridingAccessor.Locations(0)) End If End Sub ' Report an error with overriding Private Shared Sub ReportBadOverriding(id As ERRID, overridingMember As Symbol, overriddenMember As Symbol, diagnostics As BindingDiagnosticBag) diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(id, overridingMember, overriddenMember), overridingMember.Locations(0))) End Sub ' Are the declared accessibility of the two symbols consistent? If not, return the error code to use. Private Shared Function ConsistentAccessibility(overriding As Symbol, overridden As Symbol, ByRef errorId As ERRID) As Boolean If overridden.DeclaredAccessibility = Accessibility.ProtectedOrFriend And Not overriding.ContainingAssembly = overridden.ContainingAssembly Then errorId = ERRID.ERR_FriendAssemblyBadAccessOverride2 Return overriding.DeclaredAccessibility = Accessibility.Protected Else errorId = ERRID.ERR_BadOverrideAccess2 Return overridden.DeclaredAccessibility = overriding.DeclaredAccessibility End If 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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Methods, Properties, and Events all can override or hide members. ''' This class has helper methods and extensions for sharing by multiple symbol types. ''' </summary> Friend Class OverrideHidingHelper ''' <summary> ''' Check for overriding and hiding errors in container and report them via diagnostics. ''' </summary> ''' <param name="container">Containing type to check. Should be an original definition.</param> ''' <param name="diagnostics">Place diagnostics here.</param> Public Shared Sub CheckHidingAndOverridingForType(container As SourceMemberContainerTypeSymbol, diagnostics As BindingDiagnosticBag) Debug.Assert(container.IsDefinition) ' Don't do this on constructed types Select Case container.TypeKind Case TypeKind.Class, TypeKind.Interface, TypeKind.Structure CheckMembersAgainstBaseType(container, diagnostics) CheckAllAbstractsAreOverriddenAndNotHidden(container, diagnostics) Case Else ' Modules, Enums and Delegates have nothing to do. End Select End Sub ' Determine if two method or property signatures match, using the rules in 4.1.1, i.e., ByRef mismatches, ' differences in optional parameters, custom modifiers, return type are not considered. An optional parameter ' matches if the corresponding parameter in the other signature is not there, optional of any type, ' or non-optional of matching type. ' ' Note that this sense of matching is not transitive. I.e. ' A) f(x as integer) ' B) f(x as integer, optional y as String = "") ' C) f(x as integer, y As String) ' A matches B, B matches C, but A doesn't match C ' ' Note that (A) and (B) above do match in terms of Dev10 behavior when we look for overridden ' methods/properties. We still keep this behavior in Roslyn to be able to generate the same ' error in the following case: ' ' Class Base ' Public Overridable Sub f(x As Integer) ' End Sub ' End Class ' ' Class Derived ' Inherits Base ' Public Overrides Sub f(x As Integer, Optional y As String = "") ' End Sub ' End Class ' ' >>> error BC30308: 'Public Overrides Sub f(x As Integer, [y As String = ""])' cannot override ' 'Public Overridable Sub f(x As Integer)' because they differ by optional parameters. ' ' In this sense the method returns True if signatures match enough to be ' considered a candidate of overridden member. ' ' But for new overloading rules (overloading based on optional parameters) introduced in Dev11 ' we also need more detailed info on the two members being compared, namely do their signatures ' also match taking into account total parameter count and parameter optionality (optional/required)? ' We return this information in 'exactMatch' parameter. ' ' So when searching for overridden members we prefer exactly matched candidates in case we could ' find them. This helps properly find overridden members in the following case: ' ' Class Base ' Public Overridable Sub f(x As Integer) ' End Sub ' Public Overridable Sub f(x As Integer, Optional y As String = "") ' End Sub ' End Class ' ' Class Derived ' Inherits Base ' Public Overrides Sub f(x As Integer) ' End Sub ' Public Overrides Sub f(x As Integer, Optional y As String = "") ' << Dev11 Beta reports BC30308 ' End Sub ' End Class ' ' Note that Dev11 Beta wrongly reports BC30308 on the last Sub in this case. ' Public Shared Function SignaturesMatch(sym1 As Symbol, sym2 As Symbol, <Out()> ByRef exactMatch As Boolean, <Out()> ByRef exactMatchIgnoringCustomModifiers As Boolean) As Boolean ' NOTE: we should NOT ignore extra required parameters as for overloading Const mismatchesForOverriding As SymbolComparisonResults = (SymbolComparisonResults.AllMismatches And (Not SymbolComparisonResults.MismatchesForConflictingMethods)) Or SymbolComparisonResults.CustomModifierMismatch ' 'Exact match' means that the number of parameters and ' parameter 'optionality' match on two symbol candidates. Const exactMatchIgnoringCustomModifiersMask As SymbolComparisonResults = SymbolComparisonResults.TotalParameterCountMismatch Or SymbolComparisonResults.OptionalParameterTypeMismatch ' Note that exact match doesn't care about tuple element names. Const exactMatchMask As SymbolComparisonResults = exactMatchIgnoringCustomModifiersMask Or SymbolComparisonResults.CustomModifierMismatch Dim results As SymbolComparisonResults = DetailedSignatureCompare(sym1, sym2, mismatchesForOverriding) ' no match If (results And Not exactMatchMask) <> 0 Then exactMatch = False exactMatchIgnoringCustomModifiers = False Return False End If ' match exactMatch = (results And exactMatchMask) = 0 exactMatchIgnoringCustomModifiers = (results And exactMatchIgnoringCustomModifiersMask) = 0 Debug.Assert(Not exactMatch OrElse exactMatchIgnoringCustomModifiers) Return True End Function Friend Shared Function DetailedSignatureCompare( sym1 As Symbol, sym2 As Symbol, comparisons As SymbolComparisonResults, Optional stopIfAny As SymbolComparisonResults = 0 ) As SymbolComparisonResults If sym1.Kind = SymbolKind.Property Then Return PropertySignatureComparer.DetailedCompare(DirectCast(sym1, PropertySymbol), DirectCast(sym2, PropertySymbol), comparisons, stopIfAny) Else Return MethodSignatureComparer.DetailedCompare(DirectCast(sym1, MethodSymbol), DirectCast(sym2, MethodSymbol), comparisons, stopIfAny) End If End Function ''' <summary> ''' Check each member of container for constraints against the base type. For methods and properties and events, ''' checking overriding and hiding constraints. For other members, just check for hiding issues. ''' </summary> ''' <param name="container">Containing type to check. Should be an original definition.</param> ''' <param name="diagnostics">Place diagnostics here.</param> ''' <remarks></remarks> Private Shared Sub CheckMembersAgainstBaseType(container As SourceMemberContainerTypeSymbol, diagnostics As BindingDiagnosticBag) For Each member In container.GetMembers() If CanOverrideOrHide(member) Then Select Case member.Kind Case SymbolKind.Method Dim methodMember = DirectCast(member, MethodSymbol) If Not methodMember.IsAccessor Then If methodMember.IsOverrides Then OverrideHidingHelper(Of MethodSymbol).CheckOverrideMember(methodMember, methodMember.OverriddenMembers, diagnostics) ElseIf methodMember.IsNotOverridable Then 'Method is not marked as Overrides but is marked as Not Overridable diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_NotOverridableRequiresOverrides), methodMember.Locations(0))) End If End If Case SymbolKind.Property Dim propMember = DirectCast(member, PropertySymbol) If propMember.IsOverrides Then OverrideHidingHelper(Of PropertySymbol).CheckOverrideMember(propMember, propMember.OverriddenMembers, diagnostics) ElseIf propMember.IsNotOverridable Then diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_NotOverridableRequiresOverrides), propMember.Locations(0))) End If End Select ' TODO: only do this check if CheckOverrideMember didn't find an error? CheckShadowing(container, member, diagnostics) End If Next End Sub ''' <summary> ''' If the "container" is a non-MustInherit, make sure it has no MustOverride Members ''' If "container" is a non-MustInherit inheriting from a MustInherit, make sure that all MustOverride members ''' have been overridden. ''' If "container" is a MustInherit inheriting from a MustInherit, make sure that no MustOverride members ''' have been shadowed. ''' </summary> Private Shared Sub CheckAllAbstractsAreOverriddenAndNotHidden(container As NamedTypeSymbol, diagnostics As BindingDiagnosticBag) ' Check that a non-MustInherit class doesn't have any MustOverride members If Not (container.IsMustInherit OrElse container.IsNotInheritable) Then For Each member In container.GetMembers() If member.IsMustOverride Then diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_MustOverridesInClass1, container.Name), container.Locations(0))) Exit For End If Next End If Dim baseType As NamedTypeSymbol = container.BaseTypeNoUseSiteDiagnostics If baseType IsNot Nothing AndAlso baseType.IsMustInherit Then ' Check that all MustOverride members in baseType or one of its bases are overridden/not shadowed somewhere along the chain. ' Do this by accumulating a set of all the methods that have been overridden, if we encounter a MustOverride ' method that is not in the set, then report it. We can do this in a single pass up the base chain. Dim overriddenMembers As HashSet(Of Symbol) = New HashSet(Of Symbol)() Dim unimplementedMembers As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance() Dim currType = container While currType IsNot Nothing For Each member In currType.GetMembers() If CanOverrideOrHide(member) AndAlso Not member.IsAccessor Then ' accessors handled by their containing properties. If member.IsOverrides Then Dim overriddenMember = GetOverriddenMember(member) If overriddenMember IsNot Nothing Then overriddenMembers.Add(GetOverriddenMember(member)) End If End If If member.IsMustOverride AndAlso currType IsNot container Then If Not overriddenMembers.Contains(member) Then unimplementedMembers.Add(member) End If End If End If Next currType = currType.BaseTypeNoUseSiteDiagnostics End While If unimplementedMembers.Any Then If container.IsMustInherit Then ' It is OK for a IsMustInherit type to have unimplemented abstract members. But, it is not allowed ' to shadow them. Check each one to see if it is shadowed by a member of "container". Don't report for ' accessor hiding accessor, because we'll report it on the property. Dim hidingSymbols As New HashSet(Of Symbol) ' don't report more than once per hiding symbols For Each mustOverrideMember In unimplementedMembers For Each hidingMember In container.GetMembers(mustOverrideMember.Name) If DoesHide(hidingMember, mustOverrideMember) AndAlso Not hidingSymbols.Contains(hidingMember) Then ReportShadowingMustOverrideError(hidingMember, mustOverrideMember, diagnostics) hidingSymbols.Add(hidingMember) End If Next Next Else ' This is not a IsMustInherit type. Some members should be been overridden but weren't. ' Create a single error that lists all of the unimplemented members. Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance(unimplementedMembers.Count) For Each member In unimplementedMembers If Not member.IsAccessor Then If member.Kind = SymbolKind.Event Then diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_MustInheritEventNotOverridden, member, CustomSymbolDisplayFormatter.QualifiedName(member.ContainingType), CustomSymbolDisplayFormatter.ShortErrorName(container)), container.Locations(0))) Else diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_UnimplementedMustOverride, member.ContainingType, member)) End If Else ' accessor is reported on the containing property. Debug.Assert(unimplementedMembers.Contains(DirectCast(member, MethodSymbol).AssociatedSymbol)) End If Next If diagnosticInfos.Count > 0 Then diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_BaseOnlyClassesMustBeExplicit2, CustomSymbolDisplayFormatter.ShortErrorName(container), New CompoundDiagnosticInfo(diagnosticInfos.ToArrayAndFree())), container.Locations(0))) Else diagnosticInfos.Free() End If End If End If unimplementedMembers.Free() End If End Sub ' Compare two symbols of the same name to see if one actually does hide the other. Private Shared Function DoesHide(hidingMember As Symbol, hiddenMember As Symbol) As Boolean Debug.Assert(IdentifierComparison.Equals(hidingMember.Name, hiddenMember.Name)) Select Case hidingMember.Kind Case SymbolKind.Method If hidingMember.IsOverloads AndAlso hiddenMember.Kind = SymbolKind.Method Then Dim hidingMethod = DirectCast(hidingMember, MethodSymbol) If hidingMethod.IsOverrides Then ' For Dev10 compatibility, an override is not considered as hiding (see bug 11728) Return False Else Dim exactMatchIgnoringCustomModifiers As Boolean = False Return OverrideHidingHelper(Of MethodSymbol).SignaturesMatch(hidingMethod, DirectCast(hiddenMember, MethodSymbol), Nothing, exactMatchIgnoringCustomModifiers) AndAlso exactMatchIgnoringCustomModifiers End If Else Return True End If Case SymbolKind.Property If hidingMember.IsOverloads AndAlso hiddenMember.Kind = SymbolKind.Property Then Dim hidingProperty = DirectCast(hidingMember, PropertySymbol) If hidingProperty.IsOverrides Then ' For Dev10 compatibility, an override is not considered as hiding (see bug 11728) Return False Else Dim exactMatchIgnoringCustomModifiers As Boolean = False Return OverrideHidingHelper(Of PropertySymbol).SignaturesMatch(hidingProperty, DirectCast(hiddenMember, PropertySymbol), Nothing, exactMatchIgnoringCustomModifiers) AndAlso exactMatchIgnoringCustomModifiers End If Else Return True End If Case Else Return True End Select End Function ''' <summary> ''' Report any diagnostics related to shadowing for a member. ''' </summary> Protected Shared Sub CheckShadowing(container As SourceMemberContainerTypeSymbol, member As Symbol, diagnostics As BindingDiagnosticBag) Dim memberIsOverloads = member.IsOverloads() Dim warnForHiddenMember As Boolean = Not member.ShadowsExplicitly If Not warnForHiddenMember Then Return ' short circuit unnecessary checks. End If If container.IsInterfaceType() Then For Each currentBaseInterface In container.AllInterfacesNoUseSiteDiagnostics CheckShadowingInBaseType(container, member, memberIsOverloads, currentBaseInterface, diagnostics, warnForHiddenMember) Next Else Dim currentBase As NamedTypeSymbol = container.BaseTypeNoUseSiteDiagnostics While currentBase IsNot Nothing CheckShadowingInBaseType(container, member, memberIsOverloads, currentBase, diagnostics, warnForHiddenMember) currentBase = currentBase.BaseTypeNoUseSiteDiagnostics End While End If End Sub ' Check shadowing against members in one base type. Private Shared Sub CheckShadowingInBaseType(container As SourceMemberContainerTypeSymbol, member As Symbol, memberIsOverloads As Boolean, baseType As NamedTypeSymbol, diagnostics As BindingDiagnosticBag, ByRef warnForHiddenMember As Boolean) Debug.Assert(container.IsDefinition) If warnForHiddenMember Then For Each hiddenMember In baseType.GetMembers(member.Name) If AccessCheck.IsSymbolAccessible(hiddenMember, container, Nothing, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso (Not memberIsOverloads OrElse hiddenMember.Kind <> member.Kind OrElse hiddenMember.IsWithEventsProperty OrElse (member.Kind = SymbolKind.Method AndAlso DirectCast(member, MethodSymbol).IsUserDefinedOperator() <> DirectCast(hiddenMember, MethodSymbol).IsUserDefinedOperator()) OrElse member.IsAccessor() <> hiddenMember.IsAccessor) AndAlso Not (member.IsAccessor() AndAlso hiddenMember.IsAccessor) Then 'special case for classes of different arity . Do not warn in such case If member.Kind = SymbolKind.NamedType AndAlso hiddenMember.Kind = SymbolKind.NamedType AndAlso member.GetArity <> hiddenMember.GetArity Then Continue For End If ' Found an accessible member we are hiding and not overloading. ' We don't warn if accessor hides accessor, because we will warn on the containing properties instead. ' Give warning for shadowing hidden member ReportShadowingDiagnostic(member, hiddenMember, diagnostics) warnForHiddenMember = False ' don't warn for more than one hidden member. Exit For End If Next End If End Sub ' Report diagnostic for one member shadowing another, but no Shadows modifier was present. Private Shared Sub ReportShadowingDiagnostic(hidingMember As Symbol, hiddenMember As Symbol, diagnostics As BindingDiagnosticBag) Debug.Assert(Not (hidingMember.IsAccessor() AndAlso hiddenMember.IsAccessor)) Dim associatedhiddenSymbol = hiddenMember.ImplicitlyDefinedBy If associatedhiddenSymbol Is Nothing AndAlso hiddenMember.IsUserDefinedOperator() AndAlso Not hidingMember.IsUserDefinedOperator() Then ' For the purpose of this check, operator methods are treated as implicitly defined by themselves. associatedhiddenSymbol = hiddenMember End If Dim associatedhidingSymbol = hidingMember.ImplicitlyDefinedBy If associatedhidingSymbol Is Nothing AndAlso hidingMember.IsUserDefinedOperator() AndAlso Not hiddenMember.IsUserDefinedOperator() Then ' For the purpose of this check, operator methods are treated as implicitly defined by themselves. associatedhidingSymbol = hidingMember End If If associatedhiddenSymbol IsNot Nothing Then If associatedhidingSymbol IsNot Nothing Then If Not IdentifierComparison.Equals(associatedhiddenSymbol.Name, associatedhidingSymbol.Name) Then ' both members are defined implicitly by members of different names diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_SynthMemberShadowsSynthMember7, associatedhidingSymbol.GetKindText(), AssociatedSymbolName(associatedhidingSymbol), hidingMember.Name, associatedhiddenSymbol.GetKindText(), AssociatedSymbolName(associatedhiddenSymbol), hiddenMember.ContainingType.GetKindText(), CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)), hidingMember.Locations(0))) End If Return End If ' explicitly defined member hiding implicitly defined member diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_MemberShadowsSynthMember6, hidingMember.GetKindText(), hidingMember.Name, associatedhiddenSymbol.GetKindText(), AssociatedSymbolName(associatedhiddenSymbol), hiddenMember.ContainingType.GetKindText(), CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)), hidingMember.Locations(0))) ElseIf associatedhidingSymbol IsNot Nothing Then ' implicitly defined member hiding explicitly defined member diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_SynthMemberShadowsMember5, associatedhidingSymbol.GetKindText(), AssociatedSymbolName(associatedhidingSymbol), hidingMember.Name, hiddenMember.ContainingType.GetKindText(), CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)), associatedhidingSymbol.Locations(0))) ElseIf hidingMember.Kind = hiddenMember.Kind AndAlso (hidingMember.Kind = SymbolKind.Property OrElse hidingMember.Kind = SymbolKind.Method) AndAlso Not (hiddenMember.IsWithEventsProperty OrElse hidingMember.IsWithEventsProperty) Then ' method hiding method or property hiding property; message depends on if hidden symbol is overridable. Dim id As ERRID If hiddenMember.IsOverridable OrElse hiddenMember.IsOverrides OrElse (hiddenMember.IsMustOverride AndAlso Not hiddenMember.ContainingType.IsInterface) Then id = ERRID.WRN_MustOverride2 Else id = ERRID.WRN_MustOverloadBase4 End If diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(id, hidingMember.GetKindText(), hidingMember.Name, hiddenMember.ContainingType.GetKindText(), CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)), hidingMember.Locations(0))) Else ' all other hiding scenarios. Debug.Assert(hidingMember.Locations(0).IsInSource) diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_OverrideType5, hidingMember.GetKindText(), hidingMember.Name, hiddenMember.GetKindText(), hiddenMember.ContainingType.GetKindText(), CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)), hidingMember.Locations(0))) End If End Sub Public Shared Function AssociatedSymbolName(associatedSymbol As Symbol) As String Return If(associatedSymbol.IsUserDefinedOperator(), SyntaxFacts.GetText(OverloadResolution.GetOperatorTokenKind(associatedSymbol.Name)), associatedSymbol.Name) End Function ' Report diagnostic for a member shadowing a MustOverride. Private Shared Sub ReportShadowingMustOverrideError(hidingMember As Symbol, hiddenMember As Symbol, diagnostics As BindingDiagnosticBag) Debug.Assert(hidingMember.Locations(0).IsInSource) If hidingMember.IsAccessor() Then ' accessor hiding non-accessorTODO Dim associatedHidingSymbol = DirectCast(hidingMember, MethodSymbol).AssociatedSymbol diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_SynthMemberShadowsMustOverride5, hidingMember, associatedHidingSymbol.GetKindText(), associatedHidingSymbol.Name, hiddenMember.ContainingType.GetKindText(), CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)), hidingMember.Locations(0))) Else ' Basic hiding case diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_CantShadowAMustOverride1, hidingMember), hidingMember.Locations(0))) End If End Sub ''' <summary> ''' Some symbols do not participate in overriding/hiding (e.g. constructors). Accessors are consider ''' to override or hide. ''' </summary> Friend Shared Function CanOverrideOrHide(sym As Symbol) As Boolean If sym.Kind <> SymbolKind.Method Then Return True Else Select Case DirectCast(sym, MethodSymbol).MethodKind Case MethodKind.LambdaMethod, MethodKind.Constructor, MethodKind.SharedConstructor Return False Case MethodKind.Conversion, MethodKind.DelegateInvoke, MethodKind.UserDefinedOperator, MethodKind.Ordinary, MethodKind.DeclareMethod, MethodKind.EventAdd, MethodKind.EventRaise, MethodKind.EventRemove, MethodKind.PropertyGet, MethodKind.PropertySet Return True Case Else Debug.Assert(False, String.Format("Unexpected method kind '{0}'", DirectCast(sym, MethodSymbol).MethodKind)) Return False End Select End If End Function ' If this member overrides another member, return that overridden member, else return Nothing. Protected Shared Function GetOverriddenMember(sym As Symbol) As Symbol Select Case sym.Kind Case SymbolKind.Method Return DirectCast(sym, MethodSymbol).OverriddenMethod Case SymbolKind.Property Return DirectCast(sym, PropertySymbol).OverriddenProperty Case SymbolKind.Event Return DirectCast(sym, EventSymbol).OverriddenEvent End Select Return Nothing End Function ''' <summary> ''' If a method had a virtual inaccessible override, then an explicit override in metadata is needed ''' to make it really override what it intends to override, and "skip" the inaccessible virtual ''' method. ''' </summary> Public Shared Function RequiresExplicitOverride(method As MethodSymbol) As Boolean If method.IsAccessor Then If TypeOf method.AssociatedSymbol Is EventSymbol Then ' VB does not override events Return False End If Return RequiresExplicitOverride(DirectCast(method.AssociatedSymbol, PropertySymbol)) End If If method.OverriddenMethod IsNot Nothing Then For Each inaccessibleOverride In method.OverriddenMembers.InaccessibleMembers If inaccessibleOverride.IsOverridable OrElse inaccessibleOverride.IsMustOverride OrElse inaccessibleOverride.IsOverrides Then Return True End If Next End If Return False End Function Private Shared Function RequiresExplicitOverride(prop As PropertySymbol) As Boolean If prop.OverriddenProperty IsNot Nothing Then For Each inaccessibleOverride In prop.OverriddenMembers.InaccessibleMembers If inaccessibleOverride.IsOverridable OrElse inaccessibleOverride.IsMustOverride OrElse inaccessibleOverride.IsOverrides Then Return True End If Next End If Return False End Function Private Shared Function RequiresExplicitOverride([event] As EventSymbol) As Boolean If [event].OverriddenEvent IsNot Nothing Then For Each inaccessibleOverride In [event].OverriddenOrHiddenMembers.InaccessibleMembers If inaccessibleOverride.IsOverridable OrElse inaccessibleOverride.IsMustOverride OrElse inaccessibleOverride.IsOverrides Then Return True End If Next End If Return False End Function End Class ''' <summary> ''' Many of the methods want to generically work on properties, methods (and maybe events) as TSymbol. We put all these ''' methods into a generic class for convenience. ''' </summary> Friend Class OverrideHidingHelper(Of TSymbol As Symbol) Inherits OverrideHidingHelper ' Comparer for comparing signatures of TSymbols in a runtime-equivalent way. ' It is not ReadOnly because it is initialized by a Shared Sub New of another instance of this class. #Disable Warning IDE0044 ' Add readonly modifier - Adding readonly generates compile error in the constructor. - see https://github.com/dotnet/roslyn/issues/47197 Private Shared s_runtimeSignatureComparer As IEqualityComparer(Of TSymbol) #Enable Warning IDE0044 ' Add readonly modifier ' Initialize the various kinds of comparers. Shared Sub New() OverrideHidingHelper(Of MethodSymbol).s_runtimeSignatureComparer = MethodSignatureComparer.RuntimeMethodSignatureComparer OverrideHidingHelper(Of PropertySymbol).s_runtimeSignatureComparer = PropertySignatureComparer.RuntimePropertySignatureComparer OverrideHidingHelper(Of EventSymbol).s_runtimeSignatureComparer = EventSignatureComparer.RuntimeEventSignatureComparer End Sub ''' <summary> ''' Walk up the type hierarchy from ContainingType and list members that this ''' method overrides (accessible methods/properties with the same signature, if this ''' method is declared "override"). ''' ''' Methods in the overridden list may not be virtual or may have different ''' accessibilities, types, accessors, etc. They are really candidates to be ''' overridden. ''' ''' All found accessible candidates of overridden members are collected in two ''' builders, those with 'exactly' matching signatures and those with 'generally' ''' or 'inexactly' matching signatures. 'Exact' signature match is a 'general' ''' signature match which also does not have mismatches in total number of parameters ''' and/or types of optional parameters. See also comments on correspondent ''' OverriddenMembersResult(Of TSymbol) properties. ''' ''' 'Inexactly' matching candidates are only collected for reporting Dev10/Dev11 ''' errors like BC30697 and others. We collect 'inexact' matching candidates until ''' we find any 'exact' match. ''' ''' Also remembers inaccessible members that are found, but these do not prevent ''' continuing to search for accessible members. ''' ''' </summary> ''' <remarks> ''' In the presence of non-VB types, the meaning of "same signature" is rather ''' complicated. If this method isn't from source, then it refers to the runtime's ''' notion of signature (i.e. including return type, custom modifiers, etc). ''' If this method is from source, use the VB version of signature. Note that ''' Dev10 C# has a rule that prefers members with less custom modifiers. Dev 10 VB has no ''' such rule, so I'm not adding such a rule here. ''' </remarks> Friend Shared Function MakeOverriddenMembers(overridingSym As TSymbol) As OverriddenMembersResult(Of TSymbol) If Not overridingSym.IsOverrides OrElse Not CanOverrideOrHide(overridingSym) Then Return OverriddenMembersResult(Of TSymbol).Empty End If ' We should not be here for constructed methods, since overriding/hiding doesn't really make sense for them. Debug.Assert(Not (TypeOf overridingSym Is MethodSymbol AndAlso DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).ConstructedFrom <> overridingSym)) ' We should not be here for property accessors (but ok for event accessors). ' TODO: When we support virtual events, that might change. Debug.Assert(Not (TypeOf overridingSym Is MethodSymbol AndAlso (DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).MethodKind = MethodKind.PropertyGet OrElse DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).MethodKind = MethodKind.PropertySet))) ' NOTE: If our goal is to make source references and metadata references indistinguishable, then we should really ' distinguish between the "current" compilation and other compilations, rather than between source and metadata. ' However, doing so would require adding a new parameter to the public API (i.e. which compilation to consider ' "current") and that extra complexity does not seem to provide significant benefit. Our fallback goal is: ' if a source assembly builds successfully, then compilations referencing that assembly should build against ' both source and metadata or fail to build against both source and metadata. Our expectation is that an exact ' match (which is required for successful compilation) should roundtrip through metadata, so this requirement ' should be met. Dim overridingIsFromSomeCompilation As Boolean = overridingSym.Dangerous_IsFromSomeCompilationIncludingRetargeting Dim containingType As NamedTypeSymbol = overridingSym.ContainingType Dim overriddenBuilder As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance() Dim inexactOverriddenMembers As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance() Dim inaccessibleBuilder As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance() Debug.Assert(Not containingType.IsInterface, "An interface member can't be marked overrides") Dim currType As NamedTypeSymbol = containingType.BaseTypeNoUseSiteDiagnostics While currType IsNot Nothing If FindOverriddenMembersInType(overridingSym, overridingIsFromSomeCompilation, containingType, currType, overriddenBuilder, inexactOverriddenMembers, inaccessibleBuilder) Then Exit While ' Once we hit an overriding or hiding member, we're done. End If currType = currType.BaseTypeNoUseSiteDiagnostics End While Return OverriddenMembersResult(Of TSymbol).Create(overriddenBuilder.ToImmutableAndFree(), inexactOverriddenMembers.ToImmutableAndFree(), inaccessibleBuilder.ToImmutableAndFree()) End Function ''' <summary> ''' Look for overridden members in a specific type. Return true if we find an overridden member candidate ''' with 'exact' signature match, or we hit a member that hides. See comments on MakeOverriddenMembers(...) ''' for description of 'exact' and 'inexact' signature matches. ''' ''' Also remember any inaccessible members that we see. ''' </summary> ''' <param name="overridingSym">Syntax that overriding or hiding.</param> ''' <param name="overridingIsFromSomeCompilation">True if "overridingSym" is from source (this.IsFromSomeCompilation).</param> ''' <param name="overridingContainingType">The type that contains this method (this.ContainingType).</param> ''' <param name="currType">The type to search.</param> ''' <param name="overriddenBuilder">Builder to place exactly-matched overridden member candidates in. </param> ''' <param name="inexactOverriddenMembers">Builder to place inexactly-matched overridden member candidates in. </param> ''' <param name="inaccessibleBuilder">Builder to place exactly-matched inaccessible overridden member candidates in. </param> Private Shared Function FindOverriddenMembersInType(overridingSym As TSymbol, overridingIsFromSomeCompilation As Boolean, overridingContainingType As NamedTypeSymbol, currType As NamedTypeSymbol, overriddenBuilder As ArrayBuilder(Of TSymbol), inexactOverriddenMembers As ArrayBuilder(Of TSymbol), inaccessibleBuilder As ArrayBuilder(Of TSymbol)) As Boolean ' Note that overriddenBuilder may contain some non-exact ' matched symbols found in previous iterations ' We should not be here for property accessors (but ok for event accessors). ' TODO: When we support virtual events, that might change. Debug.Assert(Not (TypeOf overridingSym Is MethodSymbol AndAlso (DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).MethodKind = MethodKind.PropertyGet OrElse DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).MethodKind = MethodKind.PropertySet))) Dim stopLookup As Boolean = False Dim haveExactMatch As Boolean = False Dim overriddenInThisType As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance() For Each sym In currType.GetMembers(overridingSym.Name) ProcessMemberWithMatchingName(sym, overridingSym, overridingIsFromSomeCompilation, overridingContainingType, inexactOverriddenMembers, inaccessibleBuilder, overriddenInThisType, stopLookup, haveExactMatch) Next If overridingSym.Kind = SymbolKind.Property Then Dim prop = DirectCast(DirectCast(overridingSym, Object), PropertySymbol) If prop.IsImplicitlyDeclared AndAlso prop.IsWithEvents Then For Each sym In currType.GetSynthesizedWithEventsOverrides() If sym.Name.Equals(prop.Name) Then ProcessMemberWithMatchingName(sym, overridingSym, overridingIsFromSomeCompilation, overridingContainingType, inexactOverriddenMembers, inaccessibleBuilder, overriddenInThisType, stopLookup, haveExactMatch) End If Next End If End If If overriddenInThisType.Count > 1 Then RemoveMembersWithConflictingAccessibility(overriddenInThisType) End If If overriddenInThisType.Count > 0 Then If haveExactMatch Then Debug.Assert(stopLookup) overriddenBuilder.Clear() End If If overriddenBuilder.Count = 0 Then overriddenBuilder.AddRange(overriddenInThisType) End If End If overriddenInThisType.Free() Return stopLookup End Function Private Shared Sub ProcessMemberWithMatchingName( sym As Symbol, overridingSym As TSymbol, overridingIsFromSomeCompilation As Boolean, overridingContainingType As NamedTypeSymbol, inexactOverriddenMembers As ArrayBuilder(Of TSymbol), inaccessibleBuilder As ArrayBuilder(Of TSymbol), overriddenInThisType As ArrayBuilder(Of TSymbol), ByRef stopLookup As Boolean, ByRef haveExactMatch As Boolean ) ' Use original definition for accessibility check, because substitutions can cause ' reductions in accessibility that aren't appropriate (see bug #12038 for example). Dim accessible = AccessCheck.IsSymbolAccessible(sym.OriginalDefinition, overridingContainingType.OriginalDefinition, Nothing, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If sym.Kind = overridingSym.Kind AndAlso CanOverrideOrHide(sym) Then Dim member As TSymbol = DirectCast(sym, TSymbol) Dim exactMatch As Boolean = True ' considered to be True for all runtime signature comparisons Dim exactMatchIgnoringCustomModifiers As Boolean = True ' considered to be True for all runtime signature comparisons If If(overridingIsFromSomeCompilation, sym.IsWithEventsProperty = overridingSym.IsWithEventsProperty AndAlso SignaturesMatch(overridingSym, member, exactMatch, exactMatchIgnoringCustomModifiers), s_runtimeSignatureComparer.Equals(overridingSym, member)) Then If accessible Then If exactMatchIgnoringCustomModifiers Then If exactMatch Then If Not haveExactMatch Then haveExactMatch = True stopLookup = True overriddenInThisType.Clear() End If overriddenInThisType.Add(member) ElseIf Not haveExactMatch Then overriddenInThisType.Add(member) End If Else ' Add only if not hidden by signature AddMemberToABuilder(member, inexactOverriddenMembers) End If Else If exactMatchIgnoringCustomModifiers Then ' only exact matched methods are to be added inaccessibleBuilder.Add(member) End If End If ElseIf Not member.IsOverloads() AndAlso accessible Then ' hiding symbol by name stopLookup = True End If ElseIf accessible Then ' Any accessible symbol of different kind stops further lookup stopLookup = True End If End Sub Private Shared Sub AddMemberToABuilder(member As TSymbol, builder As ArrayBuilder(Of TSymbol)) ' We should only add a member to a builder if it does not match any ' symbols from previously processed (derived) classes ' This is supposed to help avoid adding multiple symbols one of ' which overrides another one, in the following case ' C1 ' Overridable Sub S(x As Integer, Optional y As Integer = 1) ' ' C2: C1 ' Overridable Sub S(x As Integer) ' ' C3: C2 ' Overrides Sub S(x As Integer) ' ' C4: C3 ' Overrides Sub S(x As Integer, Optional y As Integer = 1) ' In the case above we should not add 'S(x As Integer)' twice ' We don't use 'OverriddenMethod' property on MethodSymbol because ' right now it does not cache the result, so we want to avoid ' unnecessary nested calls to 'MakeOverriddenMembers' Dim memberContainingType As NamedTypeSymbol = member.ContainingType For i = 0 To builder.Count - 1 Dim exactMatchIgnoringCustomModifiers As Boolean = False If Not TypeSymbol.Equals(builder(i).ContainingType, memberContainingType, TypeCompareKind.ConsiderEverything) AndAlso SignaturesMatch(builder(i), member, Nothing, exactMatchIgnoringCustomModifiers) AndAlso exactMatchIgnoringCustomModifiers Then ' Do NOT add Exit Sub End If Next builder.Add(member) End Sub ' Check a member that is marked Override against it's base and report any necessary diagnostics. The already computed ' overridden members are passed in. Friend Shared Sub CheckOverrideMember(member As TSymbol, overriddenMembersResult As OverriddenMembersResult(Of TSymbol), diagnostics As BindingDiagnosticBag) Debug.Assert(overriddenMembersResult IsNot Nothing) Dim memberIsShadows As Boolean = member.ShadowsExplicitly Dim memberIsOverloads As Boolean = member.IsOverloads() Dim overriddenMembers As ImmutableArray(Of TSymbol) = overriddenMembersResult.OverriddenMembers ' If there are no overridden members (those with 'exactly' matching signature) ' analyze overridden member candidates with 'generally' matching signature If overriddenMembers.IsEmpty Then overriddenMembers = overriddenMembersResult.InexactOverriddenMembers End If If overriddenMembers.Length = 0 Then ' Did not have member to override. But there might have been an inaccessible one. If overriddenMembersResult.InaccessibleMembers.Length > 0 Then ReportBadOverriding(ERRID.ERR_CannotOverrideInAccessibleMember, member, overriddenMembersResult.InaccessibleMembers(0), diagnostics) Else diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_OverrideNotNeeded3, member.GetKindText(), member.Name), member.Locations(0))) End If ElseIf overriddenMembers.Length > 1 Then ' Multiple members we could be overriding. Create a single error message that lists them all. Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance(overriddenMembers.Length) For Each overriddenMemb In overriddenMembers diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverriddenCandidate1, overriddenMemb.OriginalDefinition)) Next diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_AmbiguousOverrides3, overriddenMembers(0), CustomSymbolDisplayFormatter.ShortErrorName(overriddenMembers(0).ContainingType), New CompoundDiagnosticInfo(diagnosticInfos.ToArrayAndFree())), member.Locations(0))) Else ' overriding exactly one member. Dim overriddenMember As TSymbol = overriddenMembers(0) Dim comparisonResults As SymbolComparisonResults = DetailedSignatureCompare(member, overriddenMember, SymbolComparisonResults.AllMismatches) Dim errorId As ERRID If overriddenMember.IsNotOverridable Then ReportBadOverriding(ERRID.ERR_CantOverrideNotOverridable2, member, overriddenMember, diagnostics) ElseIf Not (overriddenMember.IsOverridable Or overriddenMember.IsMustOverride Or overriddenMember.IsOverrides) Then ReportBadOverriding(ERRID.ERR_CantOverride4, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.ParameterByrefMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverrideWithByref2, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.OptionalParameterMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverrideWithOptional2, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.ReturnTypeMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_InvalidOverrideDueToReturn2, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.PropertyAccessorMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverridingPropertyKind2, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.PropertyInitOnlyMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverridingInitOnlyProperty, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.ParamArrayMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverrideWithArrayVsParamArray2, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.OptionalParameterTypeMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverrideWithOptionalTypes2, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.OptionalParameterValueMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverrideWithDefault2, member, overriddenMember, diagnostics) ElseIf (comparisonResults And SymbolComparisonResults.ConstraintMismatch) <> 0 Then ReportBadOverriding(ERRID.ERR_OverrideWithConstraintMismatch2, member, overriddenMember, diagnostics) ElseIf Not ConsistentAccessibility(member, overriddenMember, errorId) Then ReportBadOverriding(errorId, member, overriddenMember, diagnostics) ElseIf member.ContainsTupleNames() AndAlso (comparisonResults And SymbolComparisonResults.TupleNamesMismatch) <> 0 Then ' it is ok to override with no tuple names, for compatibility with VB 14, but otherwise names should match ReportBadOverriding(ERRID.WRN_InvalidOverrideDueToTupleNames2, member, overriddenMember, diagnostics) Else For Each inaccessibleMember In overriddenMembersResult.InaccessibleMembers If inaccessibleMember.DeclaredAccessibility = Accessibility.Friend AndAlso inaccessibleMember.OverriddenMember = overriddenMember Then ' We have an inaccessible friend member that overrides the member we're trying to override. ' We can't do that, so issue an error. diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_InAccessibleOverridingMethod5, member, member.ContainingType, overriddenMember, overriddenMember.ContainingType, inaccessibleMember.ContainingType), member.Locations(0))) End If Next Dim useSiteInfo = overriddenMember.GetUseSiteInfo() If Not diagnostics.Add(useSiteInfo, member.Locations(0)) AndAlso member.Kind = SymbolKind.Property Then ' No overriding errors found in member. If its a property, its accessors might have issues. Dim overridingProperty As PropertySymbol = DirectCast(DirectCast(member, Symbol), PropertySymbol) Dim overriddenProperty As PropertySymbol = DirectCast(DirectCast(overriddenMember, Symbol), PropertySymbol) CheckOverridePropertyAccessor(overridingProperty.GetMethod, overriddenProperty.GetMethod, diagnostics) CheckOverridePropertyAccessor(overridingProperty.SetMethod, overriddenProperty.SetMethod, diagnostics) End If End If End If End Sub ' Imported types can have multiple members with the same signature (case insensitive) and different accessibilities. VB prefers ' members that are "more accessible". This is a very rare code path if members has > 1 element so we don't worry about performance. Private Shared Sub RemoveMembersWithConflictingAccessibility(members As ArrayBuilder(Of TSymbol)) If members.Count < 2 Then Return End If Const significantDifferences As SymbolComparisonResults = SymbolComparisonResults.AllMismatches And Not SymbolComparisonResults.MismatchesForConflictingMethods Dim nonConflicting As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance() For Each sym In members Dim isWorseThanAnother As Boolean = False For Each otherSym In members If sym IsNot otherSym Then Dim originalSym = sym.OriginalDefinition Dim originalOther = otherSym.OriginalDefinition ' Two original definitions with identical signatures in same containing types are compared by accessibility, and ' more accessible wins. If TypeSymbol.Equals(originalSym.ContainingType, originalOther.ContainingType, TypeCompareKind.ConsiderEverything) AndAlso DetailedSignatureCompare(originalSym, originalOther, significantDifferences) = 0 AndAlso LookupResult.CompareAccessibilityOfSymbolsConflictingInSameContainer(originalSym, originalOther) < 0 Then ' sym is worse than otherSym isWorseThanAnother = True Exit For End If End If Next If Not isWorseThanAnother Then nonConflicting.Add(sym) End If Next If nonConflicting.Count <> members.Count Then members.Clear() members.AddRange(nonConflicting) End If nonConflicting.Free() End Sub ' Check an accessor with respect to its overridden accessor and report any diagnostics Friend Shared Sub CheckOverridePropertyAccessor(overridingAccessor As MethodSymbol, overriddenAccessor As MethodSymbol, diagnostics As BindingDiagnosticBag) ' CONSIDER: it is possible for an accessor to have a use site error even when the property ' does not but, in general, we have not been handling cases where property and accessor ' signatures are mismatched (e.g. different modopts). If overridingAccessor IsNot Nothing AndAlso overriddenAccessor IsNot Nothing Then ' Use original definition for accessibility check, because substitutions can cause ' reductions in accessibility that aren't appropriate (see bug #12038 for example). If Not AccessCheck.IsSymbolAccessible(overriddenAccessor.OriginalDefinition, overridingAccessor.ContainingType, Nothing, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then ReportBadOverriding(ERRID.ERR_CannotOverrideInAccessibleMember, overridingAccessor, overriddenAccessor, diagnostics) Else Dim errorId As ERRID If Not ConsistentAccessibility(overridingAccessor, overriddenAccessor, errorId) Then ReportBadOverriding(errorId, overridingAccessor, overriddenAccessor, diagnostics) End If End If diagnostics.Add(overriddenAccessor.GetUseSiteInfo(), overridingAccessor.Locations(0)) End If End Sub ' Report an error with overriding Private Shared Sub ReportBadOverriding(id As ERRID, overridingMember As Symbol, overriddenMember As Symbol, diagnostics As BindingDiagnosticBag) diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(id, overridingMember, overriddenMember), overridingMember.Locations(0))) End Sub ' Are the declared accessibility of the two symbols consistent? If not, return the error code to use. Private Shared Function ConsistentAccessibility(overriding As Symbol, overridden As Symbol, ByRef errorId As ERRID) As Boolean If overridden.DeclaredAccessibility = Accessibility.ProtectedOrFriend And Not overriding.ContainingAssembly = overridden.ContainingAssembly Then errorId = ERRID.ERR_FriendAssemblyBadAccessOverride2 Return overriding.DeclaredAccessibility = Accessibility.Protected Else errorId = ERRID.ERR_BadOverrideAccess2 Return overridden.DeclaredAccessibility = overriding.DeclaredAccessibility End If 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/VisualBasic/Portable/Binding/Binder_Lookup.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.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ' Handler the parts of binding for member lookup. Partial Friend Class Binder Friend Sub LookupMember(lookupResult As LookupResult, container As NamespaceOrTypeSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.Lookup(lookupResult, container, name, arity, options, Me, useSiteInfo) End Sub Friend Sub LookupMember(lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) Dim tempResult = lookupResult.GetInstance() MemberLookup.Lookup(lookupResult, container, name, arity, options, Me, tempResult, useSiteInfo) tempResult.Free() End Sub Friend Sub LookupMember(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.Lookup(lookupResult, container, name, arity, options, Me, useSiteInfo) End Sub Friend Sub LookupMemberImmediate(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.LookupImmediate(lookupResult, container, name, arity, options, Me, useSiteInfo) End Sub Friend Sub LookupExtensionMethods( lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(options.IsValid()) Debug.Assert(lookupResult.IsClear) options = BinderSpecificLookupOptions(options) MemberLookup.LookupForExtensionMethods(lookupResult, container, name, arity, options, Me, useSiteInfo) End Sub Friend Sub LookupMemberInModules(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.LookupInModules(lookupResult, container, name, arity, options, Me, useSiteInfo) End Sub Friend Sub AddMemberLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As NamespaceOrTypeSymbol, options As LookupOptions) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.AddLookupSymbolsInfo(nameSet, container, options, Me) End Sub ' Validates a symbol to check if it ' a) has the right arity ' b) is accessible. (accessThroughType is passed in for protected access checks) ' c) matches the lookup options. ' A non-empty SingleLookupResult with the result is returned. ' ' For symbols from outside of this compilation the method also checks ' if the symbol is marked with 'Microsoft.VisualBasic.Embedded' or 'Microsoft.CodeAnalysis.Embedded' attributes. ' ' If arity passed in is -1, no arity checks are done. Friend Function CheckViability(sym As Symbol, arity As Integer, options As LookupOptions, accessThroughType As TypeSymbol, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As SingleLookupResult Debug.Assert(sym IsNot Nothing) If Not sym.CanBeReferencedByNameIgnoringIllegalCharacters Then Return SingleLookupResult.Empty End If If (options And LookupOptions.LabelsOnly) <> 0 Then ' If LabelsOnly is set then the symbol must be a label otherwise return empty If options = LookupOptions.LabelsOnly AndAlso sym.Kind = SymbolKind.Label Then Return SingleLookupResult.Good(sym) End If ' Mixing LabelsOnly with any other flag returns an empty result Return SingleLookupResult.Empty End If If (options And LookupOptions.MustNotBeReturnValueVariable) <> 0 Then '§11.4.4 Simple Name Expressions ' If the identifier matches a local variable, the local variable matched is ' the implicit function or Get accessor return local variable, and the expression ' is part of an invocation expression, invocation statement, or an AddressOf ' expression, then no match occurs and resolution continues. ' ' LookupOptions.MustNotBeReturnValueVariable is set if "the expression ' is part of an invocation expression, invocation statement, or an AddressOf ' expression", and we then skip return value variables. ' We'll always bind to the containing method or property instead further on in the lookup process. If sym.Kind = SymbolKind.Local AndAlso DirectCast(sym, LocalSymbol).IsFunctionValue Then Return SingleLookupResult.Empty End If End If Dim unwrappedSym = sym Dim asAlias = TryCast(sym, AliasSymbol) If asAlias IsNot Nothing Then unwrappedSym = asAlias.Target End If ' Check for external symbols marked with 'Microsoft.VisualBasic.Embedded' or 'Microsoft.CodeAnalysis.Embedded' attributes If unwrappedSym.ContainingModule IsNot Me.ContainingModule Then If unwrappedSym.IsHiddenByVisualBasicEmbeddedAttribute() OrElse unwrappedSym.IsHiddenByCodeAnalysisEmbeddedAttribute() Then Return SingleLookupResult.Empty End If End If If unwrappedSym.Kind = SymbolKind.NamedType AndAlso unwrappedSym.EmbeddedSymbolKind = EmbeddedSymbolKind.EmbeddedAttribute AndAlso Me.SyntaxTree IsNot Nothing AndAlso Me.SyntaxTree.GetEmbeddedKind = EmbeddedSymbolKind.None Then ' Only allow direct access to Microsoft.VisualBasic.Embedded attribute ' from user code if current compilation embeds Vb Core If Not Me.Compilation.Options.EmbedVbCoreRuntime Then Return SingleLookupResult.Empty End If End If ' Do arity checking, unless specifically asked not to. ' Only types and namespaces in VB shadow by arity. All other members shadow ' regardless of arity. So, we only check arity on types. If arity <> -1 Then Select Case sym.Kind Case SymbolKind.NamedType, SymbolKind.ErrorType Dim actualArity As Integer = DirectCast(sym, NamedTypeSymbol).Arity If actualArity <> arity Then Return SingleLookupResult.WrongArity(sym, WrongArityErrid(actualArity, arity)) End If Case SymbolKind.TypeParameter, SymbolKind.Namespace If arity <> 0 Then ' type parameters and namespaces are always arity 0 Return SingleLookupResult.WrongArity(unwrappedSym, WrongArityErrid(0, arity)) End If Case SymbolKind.Alias ' Since raw generics cannot be imported, the import aliases would always refer to ' constructed types when referring to generics. So any other generic arity besides ' -1 or 0 are invalid. If arity <> 0 Then ' aliases are always arity 0, but error refers to the target ' Note, Dev11 doesn't stop lookup in case of arity mismatch for an alias. Return SingleLookupResult.WrongArity(unwrappedSym, WrongArityErrid(0, arity)) End If Case SymbolKind.Method ' Unlike types and namespaces, we always stop looking if we find a method with the right name but wrong arity. ' The arity matching rules for methods are customizable for the LookupOptions; when binding expressions ' we always pass AllMethodsOfAnyArity and allow overload resolution to filter methods. The other flags ' are for binding API scenarios. Dim actualArity As Integer = DirectCast(sym, MethodSymbol).Arity If actualArity <> arity AndAlso Not ((options And LookupOptions.AllMethodsOfAnyArity) <> 0) Then Return SingleLookupResult.WrongArityAndStopLookup(sym, WrongArityErrid(actualArity, arity)) End If Case Else ' Unlike types and namespace, we stop looking if we find other symbols with wrong arity. ' All these symbols have arity 0. If arity <> 0 Then Return SingleLookupResult.WrongArityAndStopLookup(sym, WrongArityErrid(0, arity)) End If End Select End If If (options And LookupOptions.IgnoreAccessibility) = 0 Then Dim accessCheckResult = CheckAccessibility(unwrappedSym, useSiteInfo, If((options And LookupOptions.UseBaseReferenceAccessibility) <> 0, Nothing, accessThroughType)) ' Check if we are in 'MyBase' resolving mode and we need to ignore 'accessThroughType' to make protected members accessed If accessCheckResult <> VisualBasic.AccessCheckResult.Accessible Then Return SingleLookupResult.Inaccessible(sym, GetInaccessibleErrorInfo(sym)) End If End If If (options And Global.Microsoft.CodeAnalysis.VisualBasic.LookupOptions.MustNotBeInstance) <> 0 AndAlso sym.IsInstanceMember Then Return Global.Microsoft.CodeAnalysis.VisualBasic.SingleLookupResult.MustNotBeInstance(sym, Global.Microsoft.CodeAnalysis.VisualBasic.ERRID.ERR_ObjectReferenceNotSupplied) ElseIf (options And Global.Microsoft.CodeAnalysis.VisualBasic.LookupOptions.MustBeInstance) <> 0 AndAlso Not sym.IsInstanceMember Then Return Global.Microsoft.CodeAnalysis.VisualBasic.SingleLookupResult.MustBeInstance(sym) ' there is no error message for this End If Return SingleLookupResult.Good(sym) End Function Friend Function GetInaccessibleErrorInfo(sym As Symbol) As DiagnosticInfo Dim unwrappedSym = sym Dim asAlias = TryCast(sym, AliasSymbol) If asAlias IsNot Nothing Then unwrappedSym = asAlias.Target ElseIf sym.Kind = SymbolKind.Method Then sym = DirectCast(sym, MethodSymbol).ConstructedFrom End If Dim diagInfo As DiagnosticInfo ' for inaccessible members (in e.g. AddressOf expressions, DEV10 shows a ERR_InaccessibleMember3 diagnostic) ' TODO maybe this condition needs to be adjusted to be shown in cases of e.g. inaccessible properties If unwrappedSym.Kind = SymbolKind.Method AndAlso unwrappedSym.ContainingSymbol IsNot Nothing Then diagInfo = New BadSymbolDiagnostic(sym, ERRID.ERR_InaccessibleMember3, sym.ContainingSymbol.Name, sym, AccessCheck.GetAccessibilityForErrorMessage(sym, Me.Compilation.Assembly)) Else diagInfo = New BadSymbolDiagnostic(sym, ERRID.ERR_InaccessibleSymbol2, CustomSymbolDisplayFormatter.QualifiedName(sym), AccessCheck.GetAccessibilityForErrorMessage(sym, sym.ContainingAssembly)) End If Debug.Assert(diagInfo.Severity = DiagnosticSeverity.Error) Return diagInfo End Function ''' <summary> ''' Used by Add*LookupSymbolsInfo* to determine whether the symbol is of interest. ''' Distinguish from <see cref="CheckViability"/>, which performs an analogous task for LookupSymbols*. ''' </summary> ''' <remarks> ''' Does not consider <see cref="Symbol.CanBeReferencedByName"/> - that is left to the caller. ''' </remarks> Friend Function CanAddLookupSymbolInfo(sym As Symbol, options As LookupOptions, nameSet As LookupSymbolsInfo, accessThroughType As TypeSymbol) As Boolean Debug.Assert(sym IsNot Nothing) If Not nameSet.CanBeAdded(sym.Name) Then Return False End If Dim singleResult = CheckViability(sym, -1, options, accessThroughType, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If (options And LookupOptions.MethodsOnly) <> 0 AndAlso sym.Kind <> SymbolKind.Method Then Return False End If If singleResult.IsGoodOrAmbiguous Then ' Its possible there is an error (ambiguity, wrong arity) associated with result. ' We still return true here, because binding finds that symbol and doesn't continue. ' NOTE: We're going to let the SemanticModel check for symbols that can't be ' referenced by name. That way, it can either filter them or not, depending ' on whether a name was passed to LookupSymbols. Return True End If Return False End Function ' return the error id for mismatched arity. Private Shared Function WrongArityErrid(actualArity As Integer, arity As Integer) As ERRID If actualArity < arity Then If actualArity = 0 Then Return ERRID.ERR_TypeOrMemberNotGeneric1 Else Return ERRID.ERR_TooManyGenericArguments1 End If Else Debug.Assert(actualArity > arity, "arities shouldn't match") Return ERRID.ERR_TooFewGenericArguments1 End If End Function ''' <summary> ''' This class handles binding of members of namespaces and types. ''' The key member is Lookup, which handles looking up a name ''' in a namespace or type, by name and arity, and produces a ''' lookup result. ''' </summary> Private Class MemberLookup ''' <summary> ''' Lookup a member name in a namespace or type, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. The supplied binder is used for accessibility ''' checked and base class suppression. ''' </summary> Public Shared Sub Lookup(lookupResult As LookupResult, container As NamespaceOrTypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) If container.IsNamespace Then Lookup(lookupResult, DirectCast(container, NamespaceSymbol), name, arity, options, binder, useSiteInfo) Else Dim tempResult = lookupResult.GetInstance() Lookup(lookupResult, DirectCast(container, TypeSymbol), name, arity, options, binder, tempResult, useSiteInfo) tempResult.Free() End If End Sub ' Lookup all the names available on the given container, that match the given lookup options. ' The supplied binder is used for accessibility checking. Public Shared Sub AddLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As NamespaceOrTypeSymbol, options As LookupOptions, binder As Binder) If container.IsNamespace Then AddLookupSymbolsInfo(nameSet, DirectCast(container, NamespaceSymbol), options, binder) Else AddLookupSymbolsInfo(nameSet, DirectCast(container, TypeSymbol), options, binder) End If End Sub ''' <summary> ''' Lookup a member name in a namespace, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. The supplied binder is used for accessibility ''' checked and base class suppression. ''' </summary> Public Shared Sub Lookup(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) LookupImmediate(lookupResult, container, name, arity, options, binder, useSiteInfo) ' Result in the namespace takes precedence over results in containing modules. If lookupResult.StopFurtherLookup Then Return End If Dim currentResult = lookupResult.GetInstance() LookupInModules(currentResult, container, name, arity, options, binder, useSiteInfo) lookupResult.MergeAmbiguous(currentResult, s_ambiguousInModuleError) currentResult.Free() End Sub ''' <summary> ''' Lookup an immediate (without descending into modules) member name in a namespace, ''' returning a LookupResult that summarizes the results of the lookup. ''' See LookupResult structure for a detailed discussion of the meaning of the results. ''' The supplied binder is used for accessibility checks and base class suppression. ''' </summary> Public Shared Sub LookupImmediate(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) Dim sourceModule = binder.Compilation.SourceModule ' Handle a case of being able to refer to System.Int32 through System.Integer. ' Same for other intrinsic types with intrinsic name different from emitted name. If (options And LookupOptions.AllowIntrinsicAliases) <> 0 AndAlso arity = 0 Then Dim containingNs = container.ContainingNamespace If containingNs IsNot Nothing AndAlso containingNs.IsGlobalNamespace AndAlso CaseInsensitiveComparison.Equals(container.Name, MetadataHelpers.SystemString) Then Dim specialType = GetTypeForIntrinsicAlias(name) If specialType <> specialType.None Then Dim candidate = binder.Compilation.GetSpecialType(specialType) ' Intrinsic alias works only if type is available If Not candidate.IsErrorType() Then lookupResult.MergeMembersOfTheSameNamespace(binder.CheckViability(candidate, arity, options, Nothing, useSiteInfo), sourceModule, options) End If End If End If End If #If DEBUG Then Dim haveSeenNamespace As Boolean = False #End If For Each sym In container.GetMembers(name) #If DEBUG Then If sym.Kind = SymbolKind.Namespace Then Debug.Assert(Not haveSeenNamespace, "Expected namespaces to be merged into a single symbol.") haveSeenNamespace = True End If #End If Dim currentResult As SingleLookupResult = binder.CheckViability(sym, arity, options, Nothing, useSiteInfo) lookupResult.MergeMembersOfTheSameNamespace(currentResult, sourceModule, options) Next End Sub Public Shared Function GetTypeForIntrinsicAlias(possibleAlias As String) As SpecialType Dim aliasAsKeyword As SyntaxKind = SyntaxFacts.GetKeywordKind(possibleAlias) Select Case aliasAsKeyword Case SyntaxKind.DateKeyword Return SpecialType.System_DateTime Case SyntaxKind.UShortKeyword Return SpecialType.System_UInt16 Case SyntaxKind.ShortKeyword Return SpecialType.System_Int16 Case SyntaxKind.UIntegerKeyword Return SpecialType.System_UInt32 Case SyntaxKind.IntegerKeyword Return SpecialType.System_Int32 Case SyntaxKind.ULongKeyword Return SpecialType.System_UInt64 Case SyntaxKind.LongKeyword Return SpecialType.System_Int64 Case Else Return SpecialType.None End Select End Function ''' <summary> ''' Lookup a member name in modules of a namespace, ''' returning a LookupResult that summarizes the results of the lookup. ''' See LookupResult structure for a detailed discussion of the meaning of the results. ''' The supplied binder is used for accessibility checks and base class suppression. ''' </summary> Public Shared Sub LookupInModules(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) Dim firstModule As Boolean = True Dim sourceModule = binder.Compilation.SourceModule ' NOTE: while looking up the symbol in modules we should ignore base class options = options Or LookupOptions.IgnoreExtensionMethods Or LookupOptions.NoBaseClassLookup Dim currentResult As LookupResult = Nothing Dim tempResult = lookupResult.GetInstance() ' Next, do a lookup in each contained module and merge the results. For Each containedModule As NamedTypeSymbol In container.GetModuleMembers() If firstModule Then Lookup(lookupResult, containedModule, name, arity, options, binder, tempResult, useSiteInfo) firstModule = False Else If currentResult Is Nothing Then currentResult = lookupResult.GetInstance() Else currentResult.Clear() End If Lookup(currentResult, containedModule, name, arity, options, binder, tempResult, useSiteInfo) ' Symbols in source take priority over symbols in a referenced assembly. If currentResult.StopFurtherLookup AndAlso currentResult.Symbols.Count > 0 AndAlso lookupResult.StopFurtherLookup AndAlso lookupResult.Symbols.Count > 0 Then Dim currentFromSource = currentResult.Symbols(0).ContainingModule Is sourceModule Dim contenderFromSource = lookupResult.Symbols(0).ContainingModule Is sourceModule If currentFromSource Then If Not contenderFromSource Then ' current is better lookupResult.SetFrom(currentResult) Continue For End If ElseIf contenderFromSource Then ' contender is better Continue For End If End If lookupResult.MergeAmbiguous(currentResult, s_ambiguousInModuleError) End If Next tempResult.Free() currentResult?.Free() End Sub Private Shared Sub AddLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As NamespaceSymbol, options As LookupOptions, binder As Binder) ' Add names from the namespace For Each sym In container.GetMembersUnordered() ' UNDONE: filter by options If binder.CanAddLookupSymbolInfo(sym, options, nameSet, Nothing) Then nameSet.AddSymbol(sym, sym.Name, sym.GetArity()) End If Next ' Next, add names from each contained module. For Each containedModule As NamedTypeSymbol In container.GetModuleMembers() AddLookupSymbolsInfo(nameSet, containedModule, options, binder) Next End Sub ' Create a diagnostic for ambiguous names in multiple modules. Private Shared ReadOnly s_ambiguousInModuleError As Func(Of ImmutableArray(Of Symbol), AmbiguousSymbolDiagnostic) = Function(syms As ImmutableArray(Of Symbol)) As AmbiguousSymbolDiagnostic Dim name As String = syms(0).Name Dim deferredFormattedList As New FormattedSymbolList(syms.Select(Function(sym) sym.ContainingType)) Return New AmbiguousSymbolDiagnostic(ERRID.ERR_AmbiguousInModules2, syms, name, deferredFormattedList) End Function ''' <summary> ''' Lookup a member name in a type, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. The supplied binder is used for accessibility ''' checked and base class suppression. ''' </summary> Friend Shared Sub Lookup(lookupResult As LookupResult, type As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) Select Case type.TypeKind Case TypeKind.Class, TypeKind.Module, TypeKind.Structure, TypeKind.Delegate, TypeKind.Array, TypeKind.Enum LookupInClass(lookupResult, type, name, arity, options, type, binder, tempResult, useSiteInfo) Case TypeKind.Submission LookupInSubmissions(lookupResult, type, name, arity, options, binder, useSiteInfo) Case TypeKind.Interface LookupInInterface(lookupResult, DirectCast(type, NamedTypeSymbol), name, arity, options, binder, tempResult, useSiteInfo) Case TypeKind.TypeParameter LookupInTypeParameter(lookupResult, DirectCast(type, TypeParameterSymbol), name, arity, options, binder, tempResult, useSiteInfo) Case TypeKind.Error ' Error types have no members. Return Case Else Throw ExceptionUtilities.UnexpectedValue(type.TypeKind) End Select End Sub Private Shared Sub AddLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As TypeSymbol, options As LookupOptions, binder As Binder) Select Case container.TypeKind Case TypeKind.Class, TypeKind.Structure, TypeKind.Delegate, TypeKind.Array, TypeKind.Enum AddLookupSymbolsInfoInClass(nameSet, container, options, binder) Case TypeKind.Module AddLookupSymbolsInfoInClass(nameSet, container, options Or LookupOptions.NoBaseClassLookup, binder) Case TypeKind.Submission AddLookupSymbolsInfoInSubmissions(nameSet, container, options, binder) Case TypeKind.Interface AddLookupSymbolsInfoInInterface(nameSet, DirectCast(container, NamedTypeSymbol), options, binder) Case TypeKind.TypeParameter AddLookupSymbolsInfoInTypeParameter(nameSet, DirectCast(container, TypeParameterSymbol), options, binder) Case TypeKind.Error ' Error types have no members. Return Case Else Throw ExceptionUtilities.UnexpectedValue(container.TypeKind) End Select End Sub ''' <summary> ''' Lookup a member name in a module, class, struct, enum, or delegate, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. The supplied binder is used for accessibility ''' checks and base class suppression. ''' </summary> Private Shared Sub LookupInClass(result As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, accessThroughType As TypeSymbol, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(result.IsClear) Dim methodsOnly As Boolean = CheckAndClearMethodsOnlyOption(options) ' Lookup proceeds up the base class chain. Dim currentType = container Do tempResult.Clear() Dim hitNonoverloadingSymbol As Boolean = False LookupWithoutInheritance(tempResult, currentType, name, arity, options, accessThroughType, binder, useSiteInfo) If result.IsGoodOrAmbiguous AndAlso tempResult.IsGoodOrAmbiguous AndAlso Not LookupResult.CanOverload(result.Symbols(0), tempResult.Symbols(0)) Then ' We hit another good symbol that can't overload this one. That doesn't affect the lookup result, but means we have to stop ' looking for more members. See bug #14078 for example. hitNonoverloadingSymbol = True End If result.MergeOverloadedOrPrioritized(tempResult, True) ' If the type is from a winmd file and implements any of the special WinRT collection ' projections, then we may need to add projected interface members Dim namedType = TryCast(currentType, NamedTypeSymbol) If namedType IsNot Nothing AndAlso namedType.ShouldAddWinRTMembers Then FindWinRTMembers(result, namedType, binder, tempResult, useSiteInfo, lookupMembersNotDefaultProperties:=True, name:=name, arity:=arity, options:=options) End If If hitNonoverloadingSymbol Then Exit Do ' still do extension methods. End If If result.StopFurtherLookup Then ' If we found a non-overloadable symbol, we can stop now. Note that even if we find a method without the Overloads ' modifier, we cannot stop because we need to check for extension methods. If result.HasSymbol Then If Not result.Symbols.First.IsOverloadable Then If methodsOnly Then Exit Do ' Need to look for extension methods. End If Return End If End If End If ' Go to base type, unless that would case infinite recursion or the options or the binder ' disallows it. If (options And LookupOptions.NoBaseClassLookup) <> 0 OrElse binder.IgnoreBaseClassesInLookup Then currentType = Nothing Else currentType = currentType.GetDirectBaseTypeWithDefinitionUseSiteDiagnostics(binder.BasesBeingResolved, useSiteInfo) End If If currentType Is Nothing Then Exit Do End If Loop ClearLookupResultIfNotMethods(methodsOnly, result) LookupForExtensionMethodsIfNeedTo(result, container, name, arity, options, binder, tempResult, useSiteInfo) End Sub Public Delegate Sub WinRTLookupDelegate(iface As NamedTypeSymbol, binder As Binder, result As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) ''' <summary> ''' This function generalizes the idea of producing a set of non-conflicting ''' WinRT members of a given type based on the results of some arbitrary lookup ''' closure (which produces a LookupResult signifying success as IsGood). ''' ''' A non-conflicting WinRT member lookup looks for all members of projected ''' WinRT interfaces which are implemented by a given type, discarding any ''' which have equal signatures. ''' ''' If <paramref name="lookupMembersNotDefaultProperties" /> is true then ''' this function lookups up members with the given <paramref name="name" />, ''' <paramref name="arity" />, and <paramref name="options" />. Otherwise, it looks for default properties. ''' </summary> Private Shared Sub FindWinRTMembers(result As LookupResult, type As NamedTypeSymbol, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), lookupMembersNotDefaultProperties As Boolean, Optional name As String = Nothing, Optional arity As Integer = -1, Optional options As LookupOptions = Nothing) ' If we have no conflict with existing members, we also have to check ' if we have a conflict with other interface members. An example would be ' a type which implements both IIterable (IEnumerable) and IMap ' (IDictionary).There are two different GetEnumerator methods from each ' interface. Thus, we don't know which method to choose. The solution? ' Don't add any GetEnumerator method. Dim comparer = MemberSignatureComparer.WinRTComparer Dim allMembers = New HashSet(Of Symbol)(comparer) Dim conflictingMembers = New HashSet(Of Symbol)(comparer) ' Add all viable members from type lookup If result.IsGood Then For Each sym In result.Symbols ' Fields can't be present in the HashSet because they can't be compared ' with a MemberSignatureComparer ' TODO: Add field support in the C# and VB member comparers and then ' delete this check If sym.Kind <> SymbolKind.Field Then allMembers.Add(sym) End If Next End If Dim tmp = LookupResult.GetInstance() ' Dev11 searches all declared and undeclared base interfaces For Each iface In type.AllInterfacesWithDefinitionUseSiteDiagnostics(useSiteInfo) If IsWinRTProjectedInterface(iface, binder.Compilation) Then If lookupMembersNotDefaultProperties Then Debug.Assert(name IsNot Nothing) LookupWithoutInheritance(tmp, iface, name, arity, options, iface, binder, useSiteInfo) Else LookupDefaultPropertyInSingleType(tmp, iface, iface, binder, tempResult, useSiteInfo) End If ' only add viable members If tmp.IsGood Then For Each sym In tmp.Symbols If Not allMembers.Add(sym) Then conflictingMembers.Add(sym) End If Next End If tmp.Clear() End If Next tmp.Free() If result.IsGood Then For Each sym In result.Symbols If sym.Kind <> SymbolKind.Field Then allMembers.Remove(sym) conflictingMembers.Remove(sym) End If Next End If For Each sym In allMembers If Not conflictingMembers.Contains(sym) Then ' since we only added viable members, every lookupresult should be viable result.MergeOverloadedOrPrioritized( New SingleLookupResult(LookupResultKind.Good, sym, Nothing), checkIfCurrentHasOverloads:=False) End If Next End Sub Private Shared Function IsWinRTProjectedInterface(iFace As NamedTypeSymbol, compilation As VisualBasicCompilation) As Boolean Dim idictSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IDictionary_KV) Dim iroDictSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IReadOnlyDictionary_KV) Dim iListSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_IList) Dim iCollectionSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_ICollection) Dim inccSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_Specialized_INotifyCollectionChanged) Dim inpcSymbol = compilation.GetWellKnownType(WellKnownType.System_ComponentModel_INotifyPropertyChanged) Dim iFaceOriginal = iFace.OriginalDefinition Dim iFaceSpecial = iFaceOriginal.SpecialType ' Types match the list given in dev11 IMPORTER::GetWindowsRuntimeInterfacesToFake Return iFaceSpecial = SpecialType.System_Collections_Generic_IEnumerable_T OrElse iFaceSpecial = SpecialType.System_Collections_Generic_IList_T OrElse iFaceSpecial = SpecialType.System_Collections_Generic_ICollection_T OrElse TypeSymbol.Equals(iFaceOriginal, idictSymbol, TypeCompareKind.ConsiderEverything) OrElse iFaceSpecial = SpecialType.System_Collections_Generic_IReadOnlyList_T OrElse iFaceSpecial = SpecialType.System_Collections_Generic_IReadOnlyCollection_T OrElse TypeSymbol.Equals(iFaceOriginal, iroDictSymbol, TypeCompareKind.ConsiderEverything) OrElse iFaceSpecial = SpecialType.System_Collections_IEnumerable OrElse TypeSymbol.Equals(iFaceOriginal, iListSymbol, TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(iFaceOriginal, iCollectionSymbol, TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(iFaceOriginal, inccSymbol, TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(iFaceOriginal, inpcSymbol, TypeCompareKind.ConsiderEverything) End Function ''' <summary> ''' Lookup a member name in a submission chain. ''' </summary> ''' <remarks> ''' We start with the current submission class and walk the submission chain back to the first submission. ''' The search has two phases ''' 1) We are looking for any symbol matching the given name, arity, and options. If we don't find any the search is over. ''' If we find an overloadable symbol(s) (a method or a property) we start looking for overloads of this kind ''' (lookingForOverloadsOfKind) of symbol in phase 2. ''' 2) If a visited submission contains a matching member of a kind different from lookingForOverloadsOfKind we stop ''' looking further. Otherwise, if we find viable overload(s) we add them into the result. Overloads modifier is ignored. ''' </remarks> Private Shared Sub LookupInSubmissions(result As LookupResult, submissionClass As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(result.IsClear) Dim submissionSymbols = LookupResult.GetInstance() Dim nonViable = LookupResult.GetInstance() Dim lookingForOverloadsOfKind As SymbolKind? = Nothing Dim submission = binder.Compilation Do submissionSymbols.Clear() If submission.ScriptClass IsNot Nothing Then LookupWithoutInheritance(submissionSymbols, submission.ScriptClass, name, arity, options, submissionClass, binder, useSiteInfo) End If ' TODO (tomat): import aliases If lookingForOverloadsOfKind Is Nothing Then If Not submissionSymbols.IsGoodOrAmbiguous Then ' skip non-viable members, but remember them in case no viable members are found in previous submissions: nonViable.MergePrioritized(submissionSymbols) submission = submission.PreviousSubmission Continue Do End If ' always overload (ignore Overloads modifier): result.MergeOverloadedOrPrioritized(submissionSymbols, checkIfCurrentHasOverloads:=False) Dim first = submissionSymbols.Symbols.First If Not first.IsOverloadable Then Exit Do End If ' we are now looking for any kind of member regardless of the original binding restrictions: options = options And Not LookupOptions.NamespacesOrTypesOnly lookingForOverloadsOfKind = first.Kind Else ' found a member we are not looking for - the overload set is final now If submissionSymbols.HasSymbol AndAlso submissionSymbols.Symbols.First.Kind <> lookingForOverloadsOfKind.Value Then Exit Do End If ' found a viable overload If submissionSymbols.IsGoodOrAmbiguous Then ' merge overloads Debug.Assert(result.Symbols.All(Function(s) s.IsOverloadable)) ' always overload (ignore Overloads modifier): result.MergeOverloadedOrPrioritized(submissionSymbols, checkIfCurrentHasOverloads:=False) End If End If submission = submission.PreviousSubmission Loop Until submission Is Nothing If Not result.HasSymbol Then result.SetFrom(nonViable) End If ' TODO (tomat): extension methods submissionSymbols.Free() nonViable.Free() End Sub Public Shared Sub LookupDefaultProperty(result As LookupResult, container As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Select Case container.TypeKind Case TypeKind.Class, TypeKind.Module, TypeKind.Structure Dim tempResult = LookupResult.GetInstance() LookupDefaultPropertyInClass(result, DirectCast(container, NamedTypeSymbol), binder, tempResult, useSiteInfo) tempResult.Free() Case TypeKind.Interface Dim tempResult = LookupResult.GetInstance() LookupDefaultPropertyInInterface(result, DirectCast(container, NamedTypeSymbol), binder, tempResult, useSiteInfo) tempResult.Free() Case TypeKind.TypeParameter Dim tempResult = LookupResult.GetInstance() LookupDefaultPropertyInTypeParameter(result, DirectCast(container, TypeParameterSymbol), binder, tempResult, useSiteInfo) tempResult.Free() End Select End Sub Private Shared Sub LookupDefaultPropertyInClass( result As LookupResult, type As NamedTypeSymbol, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(type.IsClassType OrElse type.IsModuleType OrElse type.IsStructureType OrElse type.IsDelegateType) Dim accessThroughType As NamedTypeSymbol = type While type IsNot Nothing If LookupDefaultPropertyInSingleType(result, type, accessThroughType, binder, tempResult, useSiteInfo) Then Return End If ' If this is a WinRT type, we should also look for default properties in the ' implemented projected interfaces If type.ShouldAddWinRTMembers Then FindWinRTMembers(result, type, binder, tempResult, useSiteInfo, lookupMembersNotDefaultProperties:=False) If result.IsGood Then Return End If End If type = type.BaseTypeWithDefinitionUseSiteDiagnostics(useSiteInfo) End While End Sub ' See Semantics::LookupDefaultPropertyInInterface. Private Shared Sub LookupDefaultPropertyInInterface( result As LookupResult, [interface] As NamedTypeSymbol, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert([interface].IsInterfaceType) If LookupDefaultPropertyInSingleType(result, [interface], [interface], binder, tempResult, useSiteInfo) Then Return End If For Each baseInterface In [interface].InterfacesNoUseSiteDiagnostics baseInterface.OriginalDefinition.AddUseSiteInfo(useSiteInfo) LookupDefaultPropertyInBaseInterface(result, baseInterface, binder, tempResult, useSiteInfo) If result.HasDiagnostic Then Return End If Next End Sub Private Shared Sub LookupDefaultPropertyInTypeParameter( result As LookupResult, typeParameter As TypeParameterSymbol, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) ' Look up in class constraint. Dim constraintClass = typeParameter.GetClassConstraint(useSiteInfo) If constraintClass IsNot Nothing Then LookupDefaultPropertyInClass(result, constraintClass, binder, tempResult, useSiteInfo) If Not result.IsClear Then Return End If End If ' Look up in interface constraints. Dim lookIn As Queue(Of InterfaceInfo) = Nothing Dim processed As HashSet(Of InterfaceInfo) = Nothing AddInterfaceConstraints(typeParameter, lookIn, processed, useSiteInfo) If lookIn IsNot Nothing Then For Each baseInterface In lookIn LookupDefaultPropertyInBaseInterface(result, baseInterface.InterfaceType, binder, tempResult, useSiteInfo) If result.HasDiagnostic Then Return End If Next End If End Sub ' See Semantics::LookupDefaultPropertyInBaseInterface. Private Shared Sub LookupDefaultPropertyInBaseInterface( result As LookupResult, type As NamedTypeSymbol, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) If type.IsErrorType() Then Return End If Debug.Assert(type.IsInterfaceType) Debug.Assert(Not result.HasDiagnostic) Dim tmpResult = LookupResult.GetInstance() Try LookupDefaultPropertyInInterface(tmpResult, type, binder, tempResult, useSiteInfo) If Not tmpResult.HasSymbol Then Return End If If tmpResult.HasDiagnostic OrElse Not result.HasSymbol Then result.SetFrom(tmpResult) Return End If ' At least one member was found on another interface. ' Report an ambiguity error if the two interfaces are distinct. Dim symbolA = result.Symbols(0) Dim symbolB = tmpResult.Symbols(0) If symbolA.ContainingSymbol <> symbolB.ContainingSymbol Then result.MergeAmbiguous(tmpResult, AddressOf GenerateAmbiguousDefaultPropertyDiagnostic) End If Finally tmpResult.Free() End Try End Sub ' Return True if a default property is defined on the type. Private Shared Function LookupDefaultPropertyInSingleType( result As LookupResult, type As NamedTypeSymbol, accessThroughType As TypeSymbol, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) As Boolean Dim defaultPropertyName = type.DefaultPropertyName If String.IsNullOrEmpty(defaultPropertyName) Then Return False End If Select Case type.TypeKind Case TypeKind.Class, TypeKind.Module, TypeKind.Structure LookupInClass( result, type, defaultPropertyName, arity:=0, options:=LookupOptions.Default, accessThroughType:=accessThroughType, binder:=binder, tempResult:=tempResult, useSiteInfo:=useSiteInfo) Case TypeKind.Interface Debug.Assert(accessThroughType Is type) LookupInInterface( result, type, defaultPropertyName, arity:=0, options:=LookupOptions.Default, binder:=binder, tempResult:=tempResult, useSiteInfo:=useSiteInfo) Case TypeKind.TypeParameter Throw ExceptionUtilities.UnexpectedValue(type.TypeKind) End Select Return result.HasSymbol End Function Private Shared Function GenerateAmbiguousDefaultPropertyDiagnostic(symbols As ImmutableArray(Of Symbol)) As AmbiguousSymbolDiagnostic Debug.Assert(symbols.Length > 1) Dim symbolA = symbols(0) Dim containingSymbolA = symbolA.ContainingSymbol For i = 1 To symbols.Length - 1 Dim symbolB = symbols(i) Dim containingSymbolB = symbolB.ContainingSymbol If containingSymbolA <> containingSymbolB Then ' "Default property access is ambiguous between the inherited interface members '{0}' of interface '{1}' and '{2}' of interface '{3}'." Return New AmbiguousSymbolDiagnostic(ERRID.ERR_DefaultPropertyAmbiguousAcrossInterfaces4, symbols, symbolA, containingSymbolA, symbolB, containingSymbolB) End If Next ' Expected ambiguous symbols Throw ExceptionUtilities.Unreachable End Function Private Shared Sub LookupForExtensionMethodsIfNeedTo( result As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) If result.IsGood AndAlso ((options And LookupOptions.EagerlyLookupExtensionMethods) = 0 OrElse result.Symbols(0).Kind <> SymbolKind.Method) Then Return End If tempResult.Clear() LookupForExtensionMethods(tempResult, container, name, arity, options, binder, useSiteInfo) MergeInternalXmlHelperValueIfNecessary(tempResult, container, name, arity, options, binder, useSiteInfo) result.MergeOverloadedOrPrioritized(tempResult, checkIfCurrentHasOverloads:=False) End Sub Private Shared Function ShouldLookupExtensionMethods(options As LookupOptions, container As TypeSymbol) As Boolean Return options.ShouldLookupExtensionMethods AndAlso Not container.IsObjectType() AndAlso Not container.IsShared AndAlso Not container.IsModuleType() End Function Public Shared Sub LookupForExtensionMethods( lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(lookupResult.IsClear) If Not ShouldLookupExtensionMethods(options, container) Then lookupResult.SetFrom(SingleLookupResult.Empty) Return End If ' Proceed up the chain of binders, collecting extension methods Dim originalBinder = binder Dim currentBinder = binder Dim methods = ArrayBuilder(Of MethodSymbol).GetInstance() Dim proximity As Integer = 0 ' We don't want to process the same methods more than once, but the same extension method ' might be in scope in several different binders. For example, within a type, within ' imported the same type, within imported namespace containing the type. ' So, taking into consideration the fact that CollectProbableExtensionMethodsInSingleBinder ' groups methods from the same containing type together, we will keep track of the types and ' will process all the methods from the same containing type at once. Dim seenContainingTypes As New HashSet(Of NamedTypeSymbol)() Do methods.Clear() currentBinder.CollectProbableExtensionMethodsInSingleBinder(name, methods, originalBinder) Dim i As Integer = 0 Dim count As Integer = methods.Count While i < count Dim containingType As NamedTypeSymbol = methods(i).ContainingType If seenContainingTypes.Add(containingType) AndAlso ((options And LookupOptions.IgnoreAccessibility) <> 0 OrElse AccessCheck.IsSymbolAccessible(containingType, binder.Compilation.Assembly, useSiteInfo)) Then ' Process all methods from the same type together. Do ' Try to reduce this method and merge with the current result Dim reduced As MethodSymbol = methods(i).ReduceExtensionMethod(container, proximity, useSiteInfo) If reduced IsNot Nothing Then lookupResult.MergeOverloadedOrPrioritizedExtensionMethods(binder.CheckViability(reduced, arity, options, reduced.ContainingType, useSiteInfo)) End If i += 1 Loop While i < count AndAlso containingType Is methods(i).ContainingSymbol Else ' We already processed extension methods from this container before or the whole container is not accessible, ' skip the whole group of methods from this containing type. Do i += 1 Loop While i < count AndAlso containingType Is methods(i).ContainingSymbol End If End While ' Continue to containing binders. proximity += 1 currentBinder = currentBinder.m_containingBinder Loop While currentBinder IsNot Nothing methods.Free() End Sub ''' <summary> ''' Include the InternalXmlHelper.Value extension property in the LookupResult ''' if the container implements IEnumerable(Of XElement), the name is "Value", ''' and the arity is 0. ''' </summary> Private Shared Sub MergeInternalXmlHelperValueIfNecessary( lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) If (arity <> 0) OrElse Not IdentifierComparison.Equals(name, StringConstants.ValueProperty) Then Return End If Dim compilation = binder.Compilation If (options And LookupOptions.NamespacesOrTypesOnly) <> 0 OrElse Not container.IsOrImplementsIEnumerableOfXElement(compilation, useSiteInfo) Then Return End If Dim symbol = binder.GetInternalXmlHelperValueExtensionProperty() Dim singleResult As SingleLookupResult If symbol Is Nothing Then ' Match the native compiler which reports ERR_XmlFeaturesNotAvailable in this case. Dim useSiteError = ErrorFactory.ErrorInfo(ERRID.ERR_XmlFeaturesNotAvailable) singleResult = New SingleLookupResult(LookupResultKind.NotReferencable, binder.GetErrorSymbol(name, useSiteError), useSiteError) Else Dim reduced = New ReducedExtensionPropertySymbol(DirectCast(symbol, PropertySymbol)) singleResult = binder.CheckViability(reduced, arity, options, reduced.ContainingType, useSiteInfo) End If lookupResult.MergePrioritized(singleResult) End Sub Private Shared Sub AddLookupSymbolsInfoOfExtensionMethods(nameSet As LookupSymbolsInfo, container As TypeSymbol, newInfo As LookupSymbolsInfo, binder As Binder) Dim lookup = LookupResult.GetInstance() For Each name In newInfo.Names lookup.Clear() LookupForExtensionMethods(lookup, container, name, 0, LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreAccessibility, binder, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If lookup.IsGood Then For Each method As MethodSymbol In lookup.Symbols nameSet.AddSymbol(method, method.Name, method.Arity) Next End If Next lookup.Free() End Sub Public Shared Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As TypeSymbol, options As LookupOptions, binder As Binder) If Not ShouldLookupExtensionMethods(options, container) Then Return End If ' We will not reduce extension methods for the purpose of this operation, ' they will still be shared methods. options = options And (Not Global.Microsoft.CodeAnalysis.VisualBasic.LookupOptions.MustBeInstance) ' Proceed up the chain of binders, collecting names of extension methods Dim currentBinder As Binder = binder Dim newInfo = LookupSymbolsInfo.GetInstance() Do currentBinder.AddExtensionMethodLookupSymbolsInfoInSingleBinder(newInfo, options, binder) ' Continue to containing binders. currentBinder = currentBinder.m_containingBinder Loop While currentBinder IsNot Nothing AddLookupSymbolsInfoOfExtensionMethods(nameSet, container, newInfo, binder) newInfo.Free() ' Include "Value" for InternalXmlHelper.Value if necessary. Dim compilation = binder.Compilation Dim useSiteInfo = CompoundUseSiteInfo(Of AssemblySymbol).DiscardedDependencies If container.IsOrImplementsIEnumerableOfXElement(compilation, useSiteInfo) AndAlso useSiteInfo.Diagnostics.IsNullOrEmpty Then nameSet.AddSymbol(Nothing, StringConstants.ValueProperty, 0) End If End Sub ''' <summary> ''' Checks if two interfaces have a base-derived relationship ''' </summary> Private Shared Function IsDerivedInterface( base As NamedTypeSymbol, derived As NamedTypeSymbol, basesBeingResolved As BasesBeingResolved, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) As Boolean Debug.Assert(base.IsInterface) Debug.Assert(derived.IsInterface) If TypeSymbol.Equals(derived.OriginalDefinition, base.OriginalDefinition, TypeCompareKind.ConsiderEverything) Then Return False End If ' if we are not resolving bases we can just go through AllInterfaces list If basesBeingResolved.InheritsBeingResolvedOpt Is Nothing Then For Each i In derived.AllInterfacesWithDefinitionUseSiteDiagnostics(useSiteInfo) If TypeSymbol.Equals(i, base, TypeCompareKind.ConsiderEverything) Then Return True End If Next Return False End If ' we are resolving bases so should use a private helper that relies only on Declared interfaces Return IsDerivedInterface(base, derived, basesBeingResolved, New HashSet(Of Symbol), useSiteInfo) End Function Private Shared Function IsDerivedInterface( base As NamedTypeSymbol, derived As NamedTypeSymbol, basesBeingResolved As BasesBeingResolved, verified As HashSet(Of Symbol), <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) As Boolean Debug.Assert(Not TypeSymbol.Equals(base, derived, TypeCompareKind.ConsiderEverything), "should already be verified for equality") Debug.Assert(base.IsInterface) Debug.Assert(derived.IsInterface) verified.Add(derived) ' not afraid of cycles here as we will not verify same symbol twice Dim interfaces = derived.GetDeclaredInterfacesWithDefinitionUseSiteDiagnostics(basesBeingResolved, useSiteInfo) If Not interfaces.IsDefaultOrEmpty Then For Each i In interfaces If TypeSymbol.Equals(i, base, TypeCompareKind.ConsiderEverything) Then Return True End If If verified.Contains(i) Then ' seen this already Continue For End If If IsDerivedInterface( base, i, basesBeingResolved, verified, useSiteInfo) Then Return True End If Next End If Return False End Function Private Structure InterfaceInfo Implements IEquatable(Of InterfaceInfo) Public ReadOnly InterfaceType As NamedTypeSymbol Public ReadOnly InComInterfaceContext As Boolean Public ReadOnly DescendantDefinitions As ImmutableHashSet(Of NamedTypeSymbol) Public Sub New(interfaceType As NamedTypeSymbol, inComInterfaceContext As Boolean, Optional descendantDefinitions As ImmutableHashSet(Of NamedTypeSymbol) = Nothing) Me.InterfaceType = interfaceType Me.InComInterfaceContext = inComInterfaceContext Me.DescendantDefinitions = descendantDefinitions End Sub Public Overrides Function GetHashCode() As Integer Return Hash.Combine(Me.InterfaceType.GetHashCode(), Me.InComInterfaceContext.GetHashCode()) End Function Public Overloads Overrides Function Equals(obj As Object) As Boolean Return TypeOf obj Is InterfaceInfo AndAlso Equals(DirectCast(obj, InterfaceInfo)) End Function Public Overloads Function Equals(other As InterfaceInfo) As Boolean Implements IEquatable(Of InterfaceInfo).Equals Return Me.InterfaceType.Equals(other.InterfaceType) AndAlso Me.InComInterfaceContext = other.InComInterfaceContext End Function End Structure Private Shared Sub LookupInInterface(lookupResult As LookupResult, container As NamedTypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(lookupResult.IsClear) Dim methodsOnly As Boolean = CheckAndClearMethodsOnlyOption(options) ' look in these types. Start with container, add more accordingly. Dim info As New InterfaceInfo(container, False) Dim lookIn As New Queue(Of InterfaceInfo) lookIn.Enqueue(info) Dim processed As New HashSet(Of InterfaceInfo) processed.Add(info) LookupInInterfaces(lookupResult, container, lookIn, processed, name, arity, options, binder, methodsOnly, useSiteInfo) ' If no viable or ambiguous results, look in Object. If Not lookupResult.IsGoodOrAmbiguous AndAlso (options And LookupOptions.NoSystemObjectLookupForInterfaces) = 0 Then Dim currentResult = lookupResult.GetInstance() Dim obj As NamedTypeSymbol = binder.SourceModule.ContainingAssembly.GetSpecialType(SpecialType.System_Object) LookupInClass(currentResult, obj, name, arity, options Or LookupOptions.IgnoreExtensionMethods, obj, binder, tempResult, useSiteInfo) If currentResult.IsGood Then lookupResult.SetFrom(currentResult) End If currentResult.Free() End If ClearLookupResultIfNotMethods(methodsOnly, lookupResult) LookupForExtensionMethodsIfNeedTo(lookupResult, container, name, arity, options, binder, tempResult, useSiteInfo) Return End Sub Private Shared Sub LookupInInterfaces(lookupResult As LookupResult, container As TypeSymbol, lookIn As Queue(Of InterfaceInfo), processed As HashSet(Of InterfaceInfo), name As String, arity As Integer, options As LookupOptions, binder As Binder, methodsOnly As Boolean, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(lookupResult.IsClear) Dim basesBeingResolved As BasesBeingResolved = binder.BasesBeingResolved() Dim isEventsOnlySpecified As Boolean = (options And LookupOptions.EventsOnly) <> 0 Dim currentResult = lookupResult.GetInstance() Do Dim info As InterfaceInfo = lookIn.Dequeue() Debug.Assert(processed.Contains(info)) Debug.Assert(currentResult.IsClear) LookupWithoutInheritance(currentResult, info.InterfaceType, name, arity, options, container, binder, useSiteInfo) ' if result does not shadow we will have bases to visit If Not (currentResult.StopFurtherLookup AndAlso AnyShadows(currentResult)) Then If (options And LookupOptions.NoBaseClassLookup) = 0 AndAlso Not binder.IgnoreBaseClassesInLookup Then AddBaseInterfacesToTheSearch(binder, info, lookIn, processed, useSiteInfo) End If End If Dim leaveEventsOnly As Boolean? = Nothing If info.InComInterfaceContext Then leaveEventsOnly = isEventsOnlySpecified End If If lookupResult.IsGood AndAlso currentResult.IsGood Then ' We have _another_ viable result while lookupResult is already viable. Use special interface merging rules. MergeInterfaceLookupResults(lookupResult, currentResult, basesBeingResolved, leaveEventsOnly, useSiteInfo) Else If currentResult.IsGood AndAlso leaveEventsOnly.HasValue Then FilterSymbolsInLookupResult(currentResult, SymbolKind.Event, leaveInsteadOfRemoving:=leaveEventsOnly.Value) End If lookupResult.MergePrioritized(currentResult) End If currentResult.Clear() Loop While lookIn.Count <> 0 currentResult.Free() If methodsOnly AndAlso lookupResult.IsGood Then ' We need to filter out non-method symbols from 'currentResult' ' before merging with 'lookupResult' FilterSymbolsInLookupResult(lookupResult, SymbolKind.Method, leaveInsteadOfRemoving:=True) End If ' it may look like a Good result, but it may have ambiguities inside ' so we need to check that to be sure. If lookupResult.IsGood Then Dim ambiguityDiagnostics As AmbiguousSymbolDiagnostic = Nothing Dim symbols As ArrayBuilder(Of Symbol) = lookupResult.Symbols For i As Integer = 0 To symbols.Count - 2 Dim interface1 = DirectCast(symbols(i).ContainingType, NamedTypeSymbol) For j As Integer = i + 1 To symbols.Count - 1 If Not lookupResult.CanOverload(symbols(i), symbols(j)) Then ' Symbols cannot overload each other. ' If they were from the same interface, LookupWithoutInheritance would make the result ambiguous. ' If they were from interfaces related through inheritance, one of them would shadow another, ' MergeInterfaceLookupResults handles that. ' Therefore, this symbols are from unrelated interfaces. ambiguityDiagnostics = New AmbiguousSymbolDiagnostic( ERRID.ERR_AmbiguousAcrossInterfaces3, symbols.ToImmutable, name, CustomSymbolDisplayFormatter.DefaultErrorFormat(symbols(i).ContainingType), CustomSymbolDisplayFormatter.DefaultErrorFormat(symbols(j).ContainingType)) GoTo ExitForFor End If Next Next ExitForFor: If ambiguityDiagnostics IsNot Nothing Then lookupResult.SetFrom(New SingleLookupResult(LookupResultKind.Ambiguous, symbols.First, ambiguityDiagnostics)) End If End If End Sub Private Shared Sub FilterSymbolsInLookupResult(result As LookupResult, kind As SymbolKind, leaveInsteadOfRemoving As Boolean) Debug.Assert(result.IsGood) Dim resultSymbols As ArrayBuilder(Of Symbol) = result.Symbols Debug.Assert(resultSymbols.Count > 0) Dim i As Integer = 0 Dim j As Integer = 0 While j < resultSymbols.Count Dim symbol As Symbol = resultSymbols(j) If (symbol.Kind = kind) = leaveInsteadOfRemoving Then resultSymbols(i) = resultSymbols(j) i += 1 End If j += 1 End While resultSymbols.Clip(i) If i = 0 Then result.Clear() End If End Sub Private Shared Sub LookupInTypeParameter(lookupResult As LookupResult, typeParameter As TypeParameterSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Dim methodsOnly = CheckAndClearMethodsOnlyOption(options) LookupInTypeParameterNoExtensionMethods(lookupResult, typeParameter, name, arity, options, binder, tempResult, useSiteInfo) ClearLookupResultIfNotMethods(methodsOnly, lookupResult) LookupForExtensionMethodsIfNeedTo(lookupResult, typeParameter, name, arity, options, binder, tempResult, useSiteInfo) End Sub Private Shared Sub LookupInTypeParameterNoExtensionMethods(result As LookupResult, typeParameter As TypeParameterSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert((options And LookupOptions.MethodsOnly) = 0) options = options Or LookupOptions.IgnoreExtensionMethods ' §4.9.2: "the class constraint hides members in interface constraints, which ' hide members in System.ValueType (if Structure constraint is specified), ' which hides members in Object." ' Look up in class constraint. Dim constraintClass = typeParameter.GetClassConstraint(useSiteInfo) If constraintClass IsNot Nothing Then LookupInClass(result, constraintClass, name, arity, options, constraintClass, binder, tempResult, useSiteInfo) If result.StopFurtherLookup Then Return End If End If ' Look up in interface constraints. Dim lookIn As Queue(Of InterfaceInfo) = Nothing Dim processed As HashSet(Of InterfaceInfo) = Nothing AddInterfaceConstraints(typeParameter, lookIn, processed, useSiteInfo) If lookIn IsNot Nothing Then ' §4.9.2: "If a member with the same name appears in more than one interface ' constraint the member is unavailable (as in multiple interface inheritance)" Dim interfaceResult = LookupResult.GetInstance() Debug.Assert((options And LookupOptions.MethodsOnly) = 0) LookupInInterfaces(interfaceResult, typeParameter, lookIn, processed, name, arity, options, binder, False, useSiteInfo) result.MergePrioritized(interfaceResult) interfaceResult.Free() If Not result.IsClear Then Return End If End If ' Look up in System.ValueType or System.Object. If constraintClass Is Nothing Then Debug.Assert(result.IsClear) Dim baseType = GetTypeParameterBaseType(typeParameter) LookupInClass(result, baseType, name, arity, options, baseType, binder, tempResult, useSiteInfo) End If End Sub Private Shared Function CheckAndClearMethodsOnlyOption(ByRef options As LookupOptions) As Boolean If (options And LookupOptions.MethodsOnly) <> 0 Then options = CType(options And (Not LookupOptions.MethodsOnly), LookupOptions) Return True End If Return False End Function Private Shared Sub ClearLookupResultIfNotMethods(methodsOnly As Boolean, lookupResult As LookupResult) If methodsOnly AndAlso lookupResult.HasSymbol AndAlso lookupResult.Symbols(0).Kind <> SymbolKind.Method Then lookupResult.Clear() End If End Sub Private Shared Sub AddInterfaceConstraints(typeParameter As TypeParameterSymbol, ByRef allInterfaces As Queue(Of InterfaceInfo), ByRef processedInterfaces As HashSet(Of InterfaceInfo), <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) For Each constraintType In typeParameter.ConstraintTypesWithDefinitionUseSiteDiagnostics(useSiteInfo) Select Case constraintType.TypeKind Case TypeKind.Interface Dim newInfo As New InterfaceInfo(DirectCast(constraintType, NamedTypeSymbol), False) If processedInterfaces Is Nothing OrElse Not processedInterfaces.Contains(newInfo) Then If processedInterfaces Is Nothing Then allInterfaces = New Queue(Of InterfaceInfo) processedInterfaces = New HashSet(Of InterfaceInfo) End If allInterfaces.Enqueue(newInfo) processedInterfaces.Add(newInfo) End If Case TypeKind.TypeParameter AddInterfaceConstraints(DirectCast(constraintType, TypeParameterSymbol), allInterfaces, processedInterfaces, useSiteInfo) End Select Next End Sub ''' <summary> ''' Merges two lookup results while eliminating symbols that are shadowed. ''' Note that the final result may contain unrelated and possibly conflicting symbols as ''' this helper is not intended to catch ambiguities. ''' </summary> ''' <param name="leaveEventsOnly"> ''' If is not Nothing and False filters out all Event symbols, and if is not Nothing ''' and True filters out all non-Event symbols, nos not have any effect otherwise. ''' Is used for special handling of Events inside COM interfaces. ''' </param> Private Shared Sub MergeInterfaceLookupResults( knownResult As LookupResult, newResult As LookupResult, BasesBeingResolved As BasesBeingResolved, leaveEventsOnly As Boolean?, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(knownResult.Kind = newResult.Kind) Dim knownSymbols As ArrayBuilder(Of Symbol) = knownResult.Symbols Dim newSymbols As ArrayBuilder(Of Symbol) = newResult.Symbols Dim newSymbolContainer = newSymbols.First().ContainingType For i As Integer = 0 To knownSymbols.Count - 1 Dim knownSymbol = knownSymbols(i) ' Nothing means that the symbol has been eliminated via shadowing If knownSymbol Is Nothing Then Continue For End If Dim knownSymbolContainer = knownSymbol.ContainingType For j As Integer = 0 To newSymbols.Count - 1 Dim newSymbol As Symbol = newSymbols(j) ' Nothing means that the symbol has been eliminated via shadowing If newSymbol Is Nothing Then Continue For End If ' Special-case events in case we are inside COM interface If leaveEventsOnly.HasValue AndAlso (newSymbol.Kind = SymbolKind.Event) <> leaveEventsOnly.Value Then newSymbols(j) = Nothing Continue For End If If knownSymbol = newSymbol Then ' this is the same result as we already have, remove from the new set newSymbols(j) = Nothing Continue For End If ' container of the first new symbol should be container of all others Debug.Assert(TypeSymbol.Equals(newSymbolContainer, newSymbol.ContainingType, TypeCompareKind.ConsiderEverything)) ' Are the known and new symbols of the right kinds to overload? Dim cantOverloadEachOther = Not LookupResult.CanOverload(knownSymbol, newSymbol) If IsDerivedInterface(base:=newSymbolContainer, derived:=knownSymbolContainer, basesBeingResolved:=BasesBeingResolved, useSiteInfo:=useSiteInfo) Then ' if currently known is more derived and shadows the new one ' it shadows all the new ones and we are done If IsShadows(knownSymbol) OrElse cantOverloadEachOther Then ' no need to continue with merge. new symbols are all shadowed ' and they cannot shadow anything in the old set Debug.Assert(Not knownSymbols.Any(Function(s) s Is Nothing)) newResult.Clear() Return End If ElseIf IsDerivedInterface(base:=knownSymbolContainer, derived:=newSymbolContainer, basesBeingResolved:=BasesBeingResolved, useSiteInfo:=useSiteInfo) Then ' if new is more derived and shadows ' the current one should be dropped ' NOTE that we continue iterating as more known symbols may be "shadowed out" by the current. If IsShadows(newSymbol) OrElse cantOverloadEachOther Then knownSymbols(i) = Nothing ' all following known symbols in the same container are shadowed by the new one ' we can do a quick check and remove them here For k = i + 1 To knownSymbols.Count - 1 Dim otherKnown As Symbol = knownSymbols(k) If otherKnown IsNot Nothing AndAlso TypeSymbol.Equals(otherKnown.ContainingType, knownSymbolContainer, TypeCompareKind.ConsiderEverything) Then knownSymbols(k) = Nothing End If Next End If End If ' we can get here if results are completely unrelated. ' However we do not know if they are conflicting as either one could be "shadowed out" in later iterations. ' for now we let both known and new stay Next Next CompactAndAppend(knownSymbols, newSymbols) newResult.Clear() End Sub ''' <summary> ''' first.Where(t IsNot Nothing).Concat(second.Where(t IsNot Nothing)) ''' </summary> Private Shared Sub CompactAndAppend(first As ArrayBuilder(Of Symbol), second As ArrayBuilder(Of Symbol)) Dim i As Integer = 0 ' skip non nulls While i < first.Count If first(i) Is Nothing Then Exit While End If i += 1 End While ' compact the rest Dim j As Integer = i + 1 While j < first.Count Dim item As Symbol = first(j) If item IsNot Nothing Then first(i) = item i += 1 End If j += 1 End While ' clip to compacted size first.Clip(i) ' append non nulls from second i = 0 While i < second.Count Dim items As Symbol = second(i) If items IsNot Nothing Then first.Add(items) End If i += 1 End While End Sub ''' <summary> ''' ''' </summary> Private Shared Sub AddBaseInterfacesToTheSearch(binder As Binder, currentInfo As InterfaceInfo, lookIn As Queue(Of InterfaceInfo), processed As HashSet(Of InterfaceInfo), <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Dim interfaces As ImmutableArray(Of NamedTypeSymbol) = currentInfo.InterfaceType.GetDirectBaseInterfacesNoUseSiteDiagnostics(binder.BasesBeingResolved) If Not interfaces.IsDefaultOrEmpty Then Dim inComInterfaceContext As Boolean = currentInfo.InComInterfaceContext OrElse currentInfo.InterfaceType.CoClassType IsNot Nothing Dim descendants As ImmutableHashSet(Of NamedTypeSymbol) If binder.BasesBeingResolved.InheritsBeingResolvedOpt Is Nothing Then descendants = Nothing Else ' We need to watch out for cycles in inheritance chain since they are not broken while bases are being resolved. If currentInfo.DescendantDefinitions Is Nothing Then descendants = ImmutableHashSet.Create(currentInfo.InterfaceType.OriginalDefinition) Else descendants = currentInfo.DescendantDefinitions.Add(currentInfo.InterfaceType.OriginalDefinition) End If End If For Each i In interfaces If descendants IsNot Nothing AndAlso descendants.Contains(i.OriginalDefinition) Then ' About to get in an inheritance cycle Continue For End If i.OriginalDefinition.AddUseSiteInfo(useSiteInfo) Dim newInfo As New InterfaceInfo(i, inComInterfaceContext, descendants) If processed.Add(newInfo) Then lookIn.Enqueue(newInfo) End If Next End If End Sub ''' <summary> ''' if any symbol in the list Shadows. This implies that name is not visible through the base. ''' </summary> Private Shared Function AnyShadows(result As LookupResult) As Boolean For Each sym As Symbol In result.Symbols If sym.IsShadows Then Return True End If Next Return False End Function ' Find all names in a non-interface type, consider inheritance. Private Shared Sub AddLookupSymbolsInfoInClass(nameSet As LookupSymbolsInfo, container As TypeSymbol, options As LookupOptions, binder As Binder) ' We need a check for SpecialType.System_Void as its base type is ' ValueType but we don't wish to return any members for void type If container IsNot Nothing And container.SpecialType = SpecialType.System_Void Then Return End If ' Lookup proceeds up the base class chain. Dim currentType = container Do AddLookupSymbolsInfoWithoutInheritance(nameSet, currentType, options, container, binder) ' If the type is from a winmd file and implements any of the special WinRT collection ' projections, then we may need to add projected interface members Dim namedType = TryCast(currentType, NamedTypeSymbol) If namedType IsNot Nothing AndAlso namedType.ShouldAddWinRTMembers Then AddWinRTMembersLookupSymbolsInfo(nameSet, namedType, options, container, binder) End If ' Go to base type, unless that would case infinite recursion or the options or the binder ' disallows it. If (options And LookupOptions.NoBaseClassLookup) <> 0 OrElse binder.IgnoreBaseClassesInLookup Then currentType = Nothing Else currentType = currentType.GetDirectBaseTypeNoUseSiteDiagnostics(binder.BasesBeingResolved) End If Loop While currentType IsNot Nothing ' Search for extension methods. AddExtensionMethodLookupSymbolsInfo(nameSet, container, options, binder) ' Special case: if we're in a constructor of a class or structure, then we can call constructors on ourself or our immediate base ' (via Me.New or MyClass.New or MyBase.New). We don't have enough info to check the constraints that the constructor must be ' the specific tokens Me, MyClass, or MyBase, or that its the first statement in the constructor, so services must do ' that check if it wants to show that. ' Roslyn Bug 9701. Dim containingMethod = TryCast(binder.ContainingMember, MethodSymbol) If containingMethod IsNot Nothing AndAlso containingMethod.MethodKind = MethodKind.Constructor AndAlso (container.TypeKind = TypeKind.Class OrElse container.TypeKind = TypeKind.Structure) AndAlso (TypeSymbol.Equals(containingMethod.ContainingType, container, TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(containingMethod.ContainingType.BaseTypeNoUseSiteDiagnostics, container, TypeCompareKind.ConsiderEverything)) Then nameSet.AddSymbol(Nothing, WellKnownMemberNames.InstanceConstructorName, 0) End If End Sub Private Shared Sub AddLookupSymbolsInfoInSubmissions(nameSet As LookupSymbolsInfo, submissionClass As TypeSymbol, options As LookupOptions, binder As Binder) Dim submission = binder.Compilation Do ' TODO (tomat): import aliases If submission.ScriptClass IsNot Nothing Then AddLookupSymbolsInfoWithoutInheritance(nameSet, submission.ScriptClass, options, submissionClass, binder) End If submission = submission.PreviousSubmission Loop Until submission Is Nothing ' TODO (tomat): extension methods End Sub ' Find all names in an interface type, consider inheritance. Private Shared Sub AddLookupSymbolsInfoInInterface(nameSet As LookupSymbolsInfo, container As NamedTypeSymbol, options As LookupOptions, binder As Binder) Dim info As New InterfaceInfo(container, False) Dim lookIn As New Queue(Of InterfaceInfo) lookIn.Enqueue(info) Dim processed As New HashSet(Of InterfaceInfo) processed.Add(info) AddLookupSymbolsInfoInInterfaces(nameSet, container, lookIn, processed, options, binder) ' Look in Object. AddLookupSymbolsInfoInClass(nameSet, binder.SourceModule.ContainingAssembly.GetSpecialType(SpecialType.System_Object), options Or LookupOptions.IgnoreExtensionMethods, binder) ' Search for extension methods. AddExtensionMethodLookupSymbolsInfo(nameSet, container, options, binder) End Sub Private Shared Sub AddLookupSymbolsInfoInInterfaces(nameSet As LookupSymbolsInfo, container As TypeSymbol, lookIn As Queue(Of InterfaceInfo), processed As HashSet(Of InterfaceInfo), options As LookupOptions, binder As Binder) Dim useSiteInfo = CompoundUseSiteInfo(Of AssemblySymbol).Discarded Do Dim currentType As InterfaceInfo = lookIn.Dequeue AddLookupSymbolsInfoWithoutInheritance(nameSet, currentType.InterfaceType, options, container, binder) ' Go to base type, unless that would case infinite recursion or the options or the binder ' disallows it. If (options And LookupOptions.NoBaseClassLookup) = 0 AndAlso Not binder.IgnoreBaseClassesInLookup Then AddBaseInterfacesToTheSearch(binder, currentType, lookIn, processed, useSiteInfo) End If Loop While lookIn.Count <> 0 End Sub Private Shared Sub AddLookupSymbolsInfoInTypeParameter(nameSet As LookupSymbolsInfo, typeParameter As TypeParameterSymbol, options As LookupOptions, binder As Binder) If typeParameter.TypeParameterKind = TypeParameterKind.Cref Then Return End If AddLookupSymbolsInfoInTypeParameterNoExtensionMethods(nameSet, typeParameter, options, binder) ' Search for extension methods. AddExtensionMethodLookupSymbolsInfo(nameSet, typeParameter, options, binder) End Sub Private Shared Sub AddLookupSymbolsInfoInTypeParameterNoExtensionMethods(nameSet As LookupSymbolsInfo, typeParameter As TypeParameterSymbol, options As LookupOptions, binder As Binder) options = options Or LookupOptions.IgnoreExtensionMethods ' Look up in class constraint. Dim constraintClass = typeParameter.GetClassConstraint(CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If constraintClass IsNot Nothing Then AddLookupSymbolsInfoInClass(nameSet, constraintClass, options, binder) End If ' Look up in interface constraints. Dim lookIn As Queue(Of InterfaceInfo) = Nothing Dim processed As HashSet(Of InterfaceInfo) = Nothing AddInterfaceConstraints(typeParameter, lookIn, processed, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If lookIn IsNot Nothing Then AddLookupSymbolsInfoInInterfaces(nameSet, typeParameter, lookIn, processed, options, binder) End If ' Look up in System.ValueType or System.Object. If constraintClass Is Nothing Then Dim baseType = GetTypeParameterBaseType(typeParameter) AddLookupSymbolsInfoInClass(nameSet, baseType, options, binder) End If End Sub ''' <summary> ''' Lookup a member name in a type without considering inheritance, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. ''' </summary> Private Shared Sub LookupWithoutInheritance(lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, accessThroughType As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Dim members As ImmutableArray(Of Symbol) = ImmutableArray(Of Symbol).Empty If (options And (LookupOptions.NamespacesOrTypesOnly Or LookupOptions.LabelsOnly)) = LookupOptions.NamespacesOrTypesOnly Then ' Only named types have members that are types. Go through all the types in this type and ' validate them. If there's multiple, give an error. If TypeOf container Is NamedTypeSymbol Then members = ImmutableArray(Of Symbol).CastUp(container.GetTypeMembers(name)) End If ElseIf (options And LookupOptions.LabelsOnly) = 0 Then members = container.GetMembers(name) End If Debug.Assert(lookupResult.IsClear) ' Go through each member of the type, and combine them into a single result. Overloadable members ' are combined together, while other duplicates cause an ambiguity error. If Not members.IsDefaultOrEmpty Then Dim imported As Boolean = container.ContainingModule IsNot binder.SourceModule For Each sym In members lookupResult.MergeMembersOfTheSameType(binder.CheckViability(sym, arity, options, accessThroughType, useSiteInfo), imported) Next End If End Sub ' Find all names in a type, without considering inheritance. Private Shared Sub AddLookupSymbolsInfoWithoutInheritance(nameSet As LookupSymbolsInfo, container As TypeSymbol, options As LookupOptions, accessThroughType As TypeSymbol, binder As Binder) ' UNDONE: validate symbols with something that looks like ValidateSymbol. If (options And (LookupOptions.NamespacesOrTypesOnly Or LookupOptions.LabelsOnly)) = LookupOptions.NamespacesOrTypesOnly Then ' Only named types have members that are types. Go through all the types in this type and ' validate them. If TypeOf container Is NamedTypeSymbol Then For Each sym In container.GetTypeMembersUnordered() If binder.CanAddLookupSymbolInfo(sym, options, nameSet, accessThroughType) Then nameSet.AddSymbol(sym, sym.Name, sym.Arity) End If Next End If ElseIf (options And LookupOptions.LabelsOnly) = 0 Then ' Go through each member of the type. For Each sym In container.GetMembersUnordered() If binder.CanAddLookupSymbolInfo(sym, options, nameSet, accessThroughType) Then nameSet.AddSymbol(sym, sym.Name, sym.GetArity()) End If Next End If End Sub Private Shared Sub AddWinRTMembersLookupSymbolsInfo( nameSet As LookupSymbolsInfo, type As NamedTypeSymbol, options As LookupOptions, accessThroughType As TypeSymbol, binder As Binder ) ' Dev11 searches all declared and undeclared base interfaces For Each iface In type.AllInterfacesNoUseSiteDiagnostics If IsWinRTProjectedInterface(iface, binder.Compilation) Then AddLookupSymbolsInfoWithoutInheritance(nameSet, iface, options, accessThroughType, binder) End If Next End Sub Private Shared Function GetTypeParameterBaseType(typeParameter As TypeParameterSymbol) As NamedTypeSymbol ' The default base type should only be used if there is no explicit class constraint. Debug.Assert(typeParameter.GetClassConstraint(CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Is Nothing) Return typeParameter.ContainingAssembly.GetSpecialType(If(typeParameter.HasValueTypeConstraint, SpecialType.System_ValueType, SpecialType.System_Object)) 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.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ' Handler the parts of binding for member lookup. Partial Friend Class Binder Friend Sub LookupMember(lookupResult As LookupResult, container As NamespaceOrTypeSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.Lookup(lookupResult, container, name, arity, options, Me, useSiteInfo) End Sub Friend Sub LookupMember(lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) Dim tempResult = lookupResult.GetInstance() MemberLookup.Lookup(lookupResult, container, name, arity, options, Me, tempResult, useSiteInfo) tempResult.Free() End Sub Friend Sub LookupMember(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.Lookup(lookupResult, container, name, arity, options, Me, useSiteInfo) End Sub Friend Sub LookupMemberImmediate(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.LookupImmediate(lookupResult, container, name, arity, options, Me, useSiteInfo) End Sub Friend Sub LookupExtensionMethods( lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(options.IsValid()) Debug.Assert(lookupResult.IsClear) options = BinderSpecificLookupOptions(options) MemberLookup.LookupForExtensionMethods(lookupResult, container, name, arity, options, Me, useSiteInfo) End Sub Friend Sub LookupMemberInModules(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.LookupInModules(lookupResult, container, name, arity, options, Me, useSiteInfo) End Sub Friend Sub AddMemberLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As NamespaceOrTypeSymbol, options As LookupOptions) Debug.Assert(options.IsValid()) options = BinderSpecificLookupOptions(options) MemberLookup.AddLookupSymbolsInfo(nameSet, container, options, Me) End Sub ' Validates a symbol to check if it ' a) has the right arity ' b) is accessible. (accessThroughType is passed in for protected access checks) ' c) matches the lookup options. ' A non-empty SingleLookupResult with the result is returned. ' ' For symbols from outside of this compilation the method also checks ' if the symbol is marked with 'Microsoft.VisualBasic.Embedded' or 'Microsoft.CodeAnalysis.Embedded' attributes. ' ' If arity passed in is -1, no arity checks are done. Friend Function CheckViability(sym As Symbol, arity As Integer, options As LookupOptions, accessThroughType As TypeSymbol, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As SingleLookupResult Debug.Assert(sym IsNot Nothing) If Not sym.CanBeReferencedByNameIgnoringIllegalCharacters Then Return SingleLookupResult.Empty End If If (options And LookupOptions.LabelsOnly) <> 0 Then ' If LabelsOnly is set then the symbol must be a label otherwise return empty If options = LookupOptions.LabelsOnly AndAlso sym.Kind = SymbolKind.Label Then Return SingleLookupResult.Good(sym) End If ' Mixing LabelsOnly with any other flag returns an empty result Return SingleLookupResult.Empty End If If (options And LookupOptions.MustNotBeReturnValueVariable) <> 0 Then '§11.4.4 Simple Name Expressions ' If the identifier matches a local variable, the local variable matched is ' the implicit function or Get accessor return local variable, and the expression ' is part of an invocation expression, invocation statement, or an AddressOf ' expression, then no match occurs and resolution continues. ' ' LookupOptions.MustNotBeReturnValueVariable is set if "the expression ' is part of an invocation expression, invocation statement, or an AddressOf ' expression", and we then skip return value variables. ' We'll always bind to the containing method or property instead further on in the lookup process. If sym.Kind = SymbolKind.Local AndAlso DirectCast(sym, LocalSymbol).IsFunctionValue Then Return SingleLookupResult.Empty End If End If Dim unwrappedSym = sym Dim asAlias = TryCast(sym, AliasSymbol) If asAlias IsNot Nothing Then unwrappedSym = asAlias.Target End If ' Check for external symbols marked with 'Microsoft.VisualBasic.Embedded' or 'Microsoft.CodeAnalysis.Embedded' attributes If unwrappedSym.ContainingModule IsNot Me.ContainingModule Then If unwrappedSym.IsHiddenByVisualBasicEmbeddedAttribute() OrElse unwrappedSym.IsHiddenByCodeAnalysisEmbeddedAttribute() Then Return SingleLookupResult.Empty End If End If If unwrappedSym.Kind = SymbolKind.NamedType AndAlso unwrappedSym.EmbeddedSymbolKind = EmbeddedSymbolKind.EmbeddedAttribute AndAlso Me.SyntaxTree IsNot Nothing AndAlso Me.SyntaxTree.GetEmbeddedKind = EmbeddedSymbolKind.None Then ' Only allow direct access to Microsoft.VisualBasic.Embedded attribute ' from user code if current compilation embeds Vb Core If Not Me.Compilation.Options.EmbedVbCoreRuntime Then Return SingleLookupResult.Empty End If End If ' Do arity checking, unless specifically asked not to. ' Only types and namespaces in VB shadow by arity. All other members shadow ' regardless of arity. So, we only check arity on types. If arity <> -1 Then Select Case sym.Kind Case SymbolKind.NamedType, SymbolKind.ErrorType Dim actualArity As Integer = DirectCast(sym, NamedTypeSymbol).Arity If actualArity <> arity Then Return SingleLookupResult.WrongArity(sym, WrongArityErrid(actualArity, arity)) End If Case SymbolKind.TypeParameter, SymbolKind.Namespace If arity <> 0 Then ' type parameters and namespaces are always arity 0 Return SingleLookupResult.WrongArity(unwrappedSym, WrongArityErrid(0, arity)) End If Case SymbolKind.Alias ' Since raw generics cannot be imported, the import aliases would always refer to ' constructed types when referring to generics. So any other generic arity besides ' -1 or 0 are invalid. If arity <> 0 Then ' aliases are always arity 0, but error refers to the target ' Note, Dev11 doesn't stop lookup in case of arity mismatch for an alias. Return SingleLookupResult.WrongArity(unwrappedSym, WrongArityErrid(0, arity)) End If Case SymbolKind.Method ' Unlike types and namespaces, we always stop looking if we find a method with the right name but wrong arity. ' The arity matching rules for methods are customizable for the LookupOptions; when binding expressions ' we always pass AllMethodsOfAnyArity and allow overload resolution to filter methods. The other flags ' are for binding API scenarios. Dim actualArity As Integer = DirectCast(sym, MethodSymbol).Arity If actualArity <> arity AndAlso Not ((options And LookupOptions.AllMethodsOfAnyArity) <> 0) Then Return SingleLookupResult.WrongArityAndStopLookup(sym, WrongArityErrid(actualArity, arity)) End If Case Else ' Unlike types and namespace, we stop looking if we find other symbols with wrong arity. ' All these symbols have arity 0. If arity <> 0 Then Return SingleLookupResult.WrongArityAndStopLookup(sym, WrongArityErrid(0, arity)) End If End Select End If If (options And LookupOptions.IgnoreAccessibility) = 0 Then Dim accessCheckResult = CheckAccessibility(unwrappedSym, useSiteInfo, If((options And LookupOptions.UseBaseReferenceAccessibility) <> 0, Nothing, accessThroughType)) ' Check if we are in 'MyBase' resolving mode and we need to ignore 'accessThroughType' to make protected members accessed If accessCheckResult <> VisualBasic.AccessCheckResult.Accessible Then Return SingleLookupResult.Inaccessible(sym, GetInaccessibleErrorInfo(sym)) End If End If If (options And Global.Microsoft.CodeAnalysis.VisualBasic.LookupOptions.MustNotBeInstance) <> 0 AndAlso sym.IsInstanceMember Then Return Global.Microsoft.CodeAnalysis.VisualBasic.SingleLookupResult.MustNotBeInstance(sym, Global.Microsoft.CodeAnalysis.VisualBasic.ERRID.ERR_ObjectReferenceNotSupplied) ElseIf (options And Global.Microsoft.CodeAnalysis.VisualBasic.LookupOptions.MustBeInstance) <> 0 AndAlso Not sym.IsInstanceMember Then Return Global.Microsoft.CodeAnalysis.VisualBasic.SingleLookupResult.MustBeInstance(sym) ' there is no error message for this End If Return SingleLookupResult.Good(sym) End Function Friend Function GetInaccessibleErrorInfo(sym As Symbol) As DiagnosticInfo Dim unwrappedSym = sym Dim asAlias = TryCast(sym, AliasSymbol) If asAlias IsNot Nothing Then unwrappedSym = asAlias.Target ElseIf sym.Kind = SymbolKind.Method Then sym = DirectCast(sym, MethodSymbol).ConstructedFrom End If Dim diagInfo As DiagnosticInfo ' for inaccessible members (in e.g. AddressOf expressions, DEV10 shows a ERR_InaccessibleMember3 diagnostic) ' TODO maybe this condition needs to be adjusted to be shown in cases of e.g. inaccessible properties If unwrappedSym.Kind = SymbolKind.Method AndAlso unwrappedSym.ContainingSymbol IsNot Nothing Then diagInfo = New BadSymbolDiagnostic(sym, ERRID.ERR_InaccessibleMember3, sym.ContainingSymbol.Name, sym, AccessCheck.GetAccessibilityForErrorMessage(sym, Me.Compilation.Assembly)) Else diagInfo = New BadSymbolDiagnostic(sym, ERRID.ERR_InaccessibleSymbol2, CustomSymbolDisplayFormatter.QualifiedName(sym), AccessCheck.GetAccessibilityForErrorMessage(sym, sym.ContainingAssembly)) End If Debug.Assert(diagInfo.Severity = DiagnosticSeverity.Error) Return diagInfo End Function ''' <summary> ''' Used by Add*LookupSymbolsInfo* to determine whether the symbol is of interest. ''' Distinguish from <see cref="CheckViability"/>, which performs an analogous task for LookupSymbols*. ''' </summary> ''' <remarks> ''' Does not consider <see cref="Symbol.CanBeReferencedByName"/> - that is left to the caller. ''' </remarks> Friend Function CanAddLookupSymbolInfo(sym As Symbol, options As LookupOptions, nameSet As LookupSymbolsInfo, accessThroughType As TypeSymbol) As Boolean Debug.Assert(sym IsNot Nothing) If Not nameSet.CanBeAdded(sym.Name) Then Return False End If Dim singleResult = CheckViability(sym, -1, options, accessThroughType, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If (options And LookupOptions.MethodsOnly) <> 0 AndAlso sym.Kind <> SymbolKind.Method Then Return False End If If singleResult.IsGoodOrAmbiguous Then ' Its possible there is an error (ambiguity, wrong arity) associated with result. ' We still return true here, because binding finds that symbol and doesn't continue. ' NOTE: We're going to let the SemanticModel check for symbols that can't be ' referenced by name. That way, it can either filter them or not, depending ' on whether a name was passed to LookupSymbols. Return True End If Return False End Function ' return the error id for mismatched arity. Private Shared Function WrongArityErrid(actualArity As Integer, arity As Integer) As ERRID If actualArity < arity Then If actualArity = 0 Then Return ERRID.ERR_TypeOrMemberNotGeneric1 Else Return ERRID.ERR_TooManyGenericArguments1 End If Else Debug.Assert(actualArity > arity, "arities shouldn't match") Return ERRID.ERR_TooFewGenericArguments1 End If End Function ''' <summary> ''' This class handles binding of members of namespaces and types. ''' The key member is Lookup, which handles looking up a name ''' in a namespace or type, by name and arity, and produces a ''' lookup result. ''' </summary> Private Class MemberLookup ''' <summary> ''' Lookup a member name in a namespace or type, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. The supplied binder is used for accessibility ''' checked and base class suppression. ''' </summary> Public Shared Sub Lookup(lookupResult As LookupResult, container As NamespaceOrTypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) If container.IsNamespace Then Lookup(lookupResult, DirectCast(container, NamespaceSymbol), name, arity, options, binder, useSiteInfo) Else Dim tempResult = lookupResult.GetInstance() Lookup(lookupResult, DirectCast(container, TypeSymbol), name, arity, options, binder, tempResult, useSiteInfo) tempResult.Free() End If End Sub ' Lookup all the names available on the given container, that match the given lookup options. ' The supplied binder is used for accessibility checking. Public Shared Sub AddLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As NamespaceOrTypeSymbol, options As LookupOptions, binder As Binder) If container.IsNamespace Then AddLookupSymbolsInfo(nameSet, DirectCast(container, NamespaceSymbol), options, binder) Else AddLookupSymbolsInfo(nameSet, DirectCast(container, TypeSymbol), options, binder) End If End Sub ''' <summary> ''' Lookup a member name in a namespace, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. The supplied binder is used for accessibility ''' checked and base class suppression. ''' </summary> Public Shared Sub Lookup(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) LookupImmediate(lookupResult, container, name, arity, options, binder, useSiteInfo) ' Result in the namespace takes precedence over results in containing modules. If lookupResult.StopFurtherLookup Then Return End If Dim currentResult = lookupResult.GetInstance() LookupInModules(currentResult, container, name, arity, options, binder, useSiteInfo) lookupResult.MergeAmbiguous(currentResult, s_ambiguousInModuleError) currentResult.Free() End Sub ''' <summary> ''' Lookup an immediate (without descending into modules) member name in a namespace, ''' returning a LookupResult that summarizes the results of the lookup. ''' See LookupResult structure for a detailed discussion of the meaning of the results. ''' The supplied binder is used for accessibility checks and base class suppression. ''' </summary> Public Shared Sub LookupImmediate(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) Dim sourceModule = binder.Compilation.SourceModule ' Handle a case of being able to refer to System.Int32 through System.Integer. ' Same for other intrinsic types with intrinsic name different from emitted name. If (options And LookupOptions.AllowIntrinsicAliases) <> 0 AndAlso arity = 0 Then Dim containingNs = container.ContainingNamespace If containingNs IsNot Nothing AndAlso containingNs.IsGlobalNamespace AndAlso CaseInsensitiveComparison.Equals(container.Name, MetadataHelpers.SystemString) Then Dim specialType = GetTypeForIntrinsicAlias(name) If specialType <> specialType.None Then Dim candidate = binder.Compilation.GetSpecialType(specialType) ' Intrinsic alias works only if type is available If Not candidate.IsErrorType() Then lookupResult.MergeMembersOfTheSameNamespace(binder.CheckViability(candidate, arity, options, Nothing, useSiteInfo), sourceModule, options) End If End If End If End If #If DEBUG Then Dim haveSeenNamespace As Boolean = False #End If For Each sym In container.GetMembers(name) #If DEBUG Then If sym.Kind = SymbolKind.Namespace Then Debug.Assert(Not haveSeenNamespace, "Expected namespaces to be merged into a single symbol.") haveSeenNamespace = True End If #End If Dim currentResult As SingleLookupResult = binder.CheckViability(sym, arity, options, Nothing, useSiteInfo) lookupResult.MergeMembersOfTheSameNamespace(currentResult, sourceModule, options) Next End Sub Public Shared Function GetTypeForIntrinsicAlias(possibleAlias As String) As SpecialType Dim aliasAsKeyword As SyntaxKind = SyntaxFacts.GetKeywordKind(possibleAlias) Select Case aliasAsKeyword Case SyntaxKind.DateKeyword Return SpecialType.System_DateTime Case SyntaxKind.UShortKeyword Return SpecialType.System_UInt16 Case SyntaxKind.ShortKeyword Return SpecialType.System_Int16 Case SyntaxKind.UIntegerKeyword Return SpecialType.System_UInt32 Case SyntaxKind.IntegerKeyword Return SpecialType.System_Int32 Case SyntaxKind.ULongKeyword Return SpecialType.System_UInt64 Case SyntaxKind.LongKeyword Return SpecialType.System_Int64 Case Else Return SpecialType.None End Select End Function ''' <summary> ''' Lookup a member name in modules of a namespace, ''' returning a LookupResult that summarizes the results of the lookup. ''' See LookupResult structure for a detailed discussion of the meaning of the results. ''' The supplied binder is used for accessibility checks and base class suppression. ''' </summary> Public Shared Sub LookupInModules(lookupResult As LookupResult, container As NamespaceSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) Dim firstModule As Boolean = True Dim sourceModule = binder.Compilation.SourceModule ' NOTE: while looking up the symbol in modules we should ignore base class options = options Or LookupOptions.IgnoreExtensionMethods Or LookupOptions.NoBaseClassLookup Dim currentResult As LookupResult = Nothing Dim tempResult = lookupResult.GetInstance() ' Next, do a lookup in each contained module and merge the results. For Each containedModule As NamedTypeSymbol In container.GetModuleMembers() If firstModule Then Lookup(lookupResult, containedModule, name, arity, options, binder, tempResult, useSiteInfo) firstModule = False Else If currentResult Is Nothing Then currentResult = lookupResult.GetInstance() Else currentResult.Clear() End If Lookup(currentResult, containedModule, name, arity, options, binder, tempResult, useSiteInfo) ' Symbols in source take priority over symbols in a referenced assembly. If currentResult.StopFurtherLookup AndAlso currentResult.Symbols.Count > 0 AndAlso lookupResult.StopFurtherLookup AndAlso lookupResult.Symbols.Count > 0 Then Dim currentFromSource = currentResult.Symbols(0).ContainingModule Is sourceModule Dim contenderFromSource = lookupResult.Symbols(0).ContainingModule Is sourceModule If currentFromSource Then If Not contenderFromSource Then ' current is better lookupResult.SetFrom(currentResult) Continue For End If ElseIf contenderFromSource Then ' contender is better Continue For End If End If lookupResult.MergeAmbiguous(currentResult, s_ambiguousInModuleError) End If Next tempResult.Free() currentResult?.Free() End Sub Private Shared Sub AddLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As NamespaceSymbol, options As LookupOptions, binder As Binder) ' Add names from the namespace For Each sym In container.GetMembersUnordered() ' UNDONE: filter by options If binder.CanAddLookupSymbolInfo(sym, options, nameSet, Nothing) Then nameSet.AddSymbol(sym, sym.Name, sym.GetArity()) End If Next ' Next, add names from each contained module. For Each containedModule As NamedTypeSymbol In container.GetModuleMembers() AddLookupSymbolsInfo(nameSet, containedModule, options, binder) Next End Sub ' Create a diagnostic for ambiguous names in multiple modules. Private Shared ReadOnly s_ambiguousInModuleError As Func(Of ImmutableArray(Of Symbol), AmbiguousSymbolDiagnostic) = Function(syms As ImmutableArray(Of Symbol)) As AmbiguousSymbolDiagnostic Dim name As String = syms(0).Name Dim deferredFormattedList As New FormattedSymbolList(syms.Select(Function(sym) sym.ContainingType)) Return New AmbiguousSymbolDiagnostic(ERRID.ERR_AmbiguousInModules2, syms, name, deferredFormattedList) End Function ''' <summary> ''' Lookup a member name in a type, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. The supplied binder is used for accessibility ''' checked and base class suppression. ''' </summary> Friend Shared Sub Lookup(lookupResult As LookupResult, type As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) Select Case type.TypeKind Case TypeKind.Class, TypeKind.Module, TypeKind.Structure, TypeKind.Delegate, TypeKind.Array, TypeKind.Enum LookupInClass(lookupResult, type, name, arity, options, type, binder, tempResult, useSiteInfo) Case TypeKind.Submission LookupInSubmissions(lookupResult, type, name, arity, options, binder, useSiteInfo) Case TypeKind.Interface LookupInInterface(lookupResult, DirectCast(type, NamedTypeSymbol), name, arity, options, binder, tempResult, useSiteInfo) Case TypeKind.TypeParameter LookupInTypeParameter(lookupResult, DirectCast(type, TypeParameterSymbol), name, arity, options, binder, tempResult, useSiteInfo) Case TypeKind.Error ' Error types have no members. Return Case Else Throw ExceptionUtilities.UnexpectedValue(type.TypeKind) End Select End Sub Private Shared Sub AddLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As TypeSymbol, options As LookupOptions, binder As Binder) Select Case container.TypeKind Case TypeKind.Class, TypeKind.Structure, TypeKind.Delegate, TypeKind.Array, TypeKind.Enum AddLookupSymbolsInfoInClass(nameSet, container, options, binder) Case TypeKind.Module AddLookupSymbolsInfoInClass(nameSet, container, options Or LookupOptions.NoBaseClassLookup, binder) Case TypeKind.Submission AddLookupSymbolsInfoInSubmissions(nameSet, container, options, binder) Case TypeKind.Interface AddLookupSymbolsInfoInInterface(nameSet, DirectCast(container, NamedTypeSymbol), options, binder) Case TypeKind.TypeParameter AddLookupSymbolsInfoInTypeParameter(nameSet, DirectCast(container, TypeParameterSymbol), options, binder) Case TypeKind.Error ' Error types have no members. Return Case Else Throw ExceptionUtilities.UnexpectedValue(container.TypeKind) End Select End Sub ''' <summary> ''' Lookup a member name in a module, class, struct, enum, or delegate, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. The supplied binder is used for accessibility ''' checks and base class suppression. ''' </summary> Private Shared Sub LookupInClass(result As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, accessThroughType As TypeSymbol, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(result.IsClear) Dim methodsOnly As Boolean = CheckAndClearMethodsOnlyOption(options) ' Lookup proceeds up the base class chain. Dim currentType = container Do tempResult.Clear() Dim hitNonoverloadingSymbol As Boolean = False LookupWithoutInheritance(tempResult, currentType, name, arity, options, accessThroughType, binder, useSiteInfo) If result.IsGoodOrAmbiguous AndAlso tempResult.IsGoodOrAmbiguous AndAlso Not LookupResult.CanOverload(result.Symbols(0), tempResult.Symbols(0)) Then ' We hit another good symbol that can't overload this one. That doesn't affect the lookup result, but means we have to stop ' looking for more members. See bug #14078 for example. hitNonoverloadingSymbol = True End If result.MergeOverloadedOrPrioritized(tempResult, True) ' If the type is from a winmd file and implements any of the special WinRT collection ' projections, then we may need to add projected interface members Dim namedType = TryCast(currentType, NamedTypeSymbol) If namedType IsNot Nothing AndAlso namedType.ShouldAddWinRTMembers Then FindWinRTMembers(result, namedType, binder, tempResult, useSiteInfo, lookupMembersNotDefaultProperties:=True, name:=name, arity:=arity, options:=options) End If If hitNonoverloadingSymbol Then Exit Do ' still do extension methods. End If If result.StopFurtherLookup Then ' If we found a non-overloadable symbol, we can stop now. Note that even if we find a method without the Overloads ' modifier, we cannot stop because we need to check for extension methods. If result.HasSymbol Then If Not result.Symbols.First.IsOverloadable Then If methodsOnly Then Exit Do ' Need to look for extension methods. End If Return End If End If End If ' Go to base type, unless that would case infinite recursion or the options or the binder ' disallows it. If (options And LookupOptions.NoBaseClassLookup) <> 0 OrElse binder.IgnoreBaseClassesInLookup Then currentType = Nothing Else currentType = currentType.GetDirectBaseTypeWithDefinitionUseSiteDiagnostics(binder.BasesBeingResolved, useSiteInfo) End If If currentType Is Nothing Then Exit Do End If Loop ClearLookupResultIfNotMethods(methodsOnly, result) LookupForExtensionMethodsIfNeedTo(result, container, name, arity, options, binder, tempResult, useSiteInfo) End Sub Public Delegate Sub WinRTLookupDelegate(iface As NamedTypeSymbol, binder As Binder, result As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) ''' <summary> ''' This function generalizes the idea of producing a set of non-conflicting ''' WinRT members of a given type based on the results of some arbitrary lookup ''' closure (which produces a LookupResult signifying success as IsGood). ''' ''' A non-conflicting WinRT member lookup looks for all members of projected ''' WinRT interfaces which are implemented by a given type, discarding any ''' which have equal signatures. ''' ''' If <paramref name="lookupMembersNotDefaultProperties" /> is true then ''' this function lookups up members with the given <paramref name="name" />, ''' <paramref name="arity" />, and <paramref name="options" />. Otherwise, it looks for default properties. ''' </summary> Private Shared Sub FindWinRTMembers(result As LookupResult, type As NamedTypeSymbol, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), lookupMembersNotDefaultProperties As Boolean, Optional name As String = Nothing, Optional arity As Integer = -1, Optional options As LookupOptions = Nothing) ' If we have no conflict with existing members, we also have to check ' if we have a conflict with other interface members. An example would be ' a type which implements both IIterable (IEnumerable) and IMap ' (IDictionary).There are two different GetEnumerator methods from each ' interface. Thus, we don't know which method to choose. The solution? ' Don't add any GetEnumerator method. Dim comparer = MemberSignatureComparer.WinRTComparer Dim allMembers = New HashSet(Of Symbol)(comparer) Dim conflictingMembers = New HashSet(Of Symbol)(comparer) ' Add all viable members from type lookup If result.IsGood Then For Each sym In result.Symbols ' Fields can't be present in the HashSet because they can't be compared ' with a MemberSignatureComparer ' TODO: Add field support in the C# and VB member comparers and then ' delete this check If sym.Kind <> SymbolKind.Field Then allMembers.Add(sym) End If Next End If Dim tmp = LookupResult.GetInstance() ' Dev11 searches all declared and undeclared base interfaces For Each iface In type.AllInterfacesWithDefinitionUseSiteDiagnostics(useSiteInfo) If IsWinRTProjectedInterface(iface, binder.Compilation) Then If lookupMembersNotDefaultProperties Then Debug.Assert(name IsNot Nothing) LookupWithoutInheritance(tmp, iface, name, arity, options, iface, binder, useSiteInfo) Else LookupDefaultPropertyInSingleType(tmp, iface, iface, binder, tempResult, useSiteInfo) End If ' only add viable members If tmp.IsGood Then For Each sym In tmp.Symbols If Not allMembers.Add(sym) Then conflictingMembers.Add(sym) End If Next End If tmp.Clear() End If Next tmp.Free() If result.IsGood Then For Each sym In result.Symbols If sym.Kind <> SymbolKind.Field Then allMembers.Remove(sym) conflictingMembers.Remove(sym) End If Next End If For Each sym In allMembers If Not conflictingMembers.Contains(sym) Then ' since we only added viable members, every lookupresult should be viable result.MergeOverloadedOrPrioritized( New SingleLookupResult(LookupResultKind.Good, sym, Nothing), checkIfCurrentHasOverloads:=False) End If Next End Sub Private Shared Function IsWinRTProjectedInterface(iFace As NamedTypeSymbol, compilation As VisualBasicCompilation) As Boolean Dim idictSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IDictionary_KV) Dim iroDictSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IReadOnlyDictionary_KV) Dim iListSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_IList) Dim iCollectionSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_ICollection) Dim inccSymbol = compilation.GetWellKnownType(WellKnownType.System_Collections_Specialized_INotifyCollectionChanged) Dim inpcSymbol = compilation.GetWellKnownType(WellKnownType.System_ComponentModel_INotifyPropertyChanged) Dim iFaceOriginal = iFace.OriginalDefinition Dim iFaceSpecial = iFaceOriginal.SpecialType ' Types match the list given in dev11 IMPORTER::GetWindowsRuntimeInterfacesToFake Return iFaceSpecial = SpecialType.System_Collections_Generic_IEnumerable_T OrElse iFaceSpecial = SpecialType.System_Collections_Generic_IList_T OrElse iFaceSpecial = SpecialType.System_Collections_Generic_ICollection_T OrElse TypeSymbol.Equals(iFaceOriginal, idictSymbol, TypeCompareKind.ConsiderEverything) OrElse iFaceSpecial = SpecialType.System_Collections_Generic_IReadOnlyList_T OrElse iFaceSpecial = SpecialType.System_Collections_Generic_IReadOnlyCollection_T OrElse TypeSymbol.Equals(iFaceOriginal, iroDictSymbol, TypeCompareKind.ConsiderEverything) OrElse iFaceSpecial = SpecialType.System_Collections_IEnumerable OrElse TypeSymbol.Equals(iFaceOriginal, iListSymbol, TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(iFaceOriginal, iCollectionSymbol, TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(iFaceOriginal, inccSymbol, TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(iFaceOriginal, inpcSymbol, TypeCompareKind.ConsiderEverything) End Function ''' <summary> ''' Lookup a member name in a submission chain. ''' </summary> ''' <remarks> ''' We start with the current submission class and walk the submission chain back to the first submission. ''' The search has two phases ''' 1) We are looking for any symbol matching the given name, arity, and options. If we don't find any the search is over. ''' If we find an overloadable symbol(s) (a method or a property) we start looking for overloads of this kind ''' (lookingForOverloadsOfKind) of symbol in phase 2. ''' 2) If a visited submission contains a matching member of a kind different from lookingForOverloadsOfKind we stop ''' looking further. Otherwise, if we find viable overload(s) we add them into the result. Overloads modifier is ignored. ''' </remarks> Private Shared Sub LookupInSubmissions(result As LookupResult, submissionClass As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(result.IsClear) Dim submissionSymbols = LookupResult.GetInstance() Dim nonViable = LookupResult.GetInstance() Dim lookingForOverloadsOfKind As SymbolKind? = Nothing Dim submission = binder.Compilation Do submissionSymbols.Clear() If submission.ScriptClass IsNot Nothing Then LookupWithoutInheritance(submissionSymbols, submission.ScriptClass, name, arity, options, submissionClass, binder, useSiteInfo) End If ' TODO (tomat): import aliases If lookingForOverloadsOfKind Is Nothing Then If Not submissionSymbols.IsGoodOrAmbiguous Then ' skip non-viable members, but remember them in case no viable members are found in previous submissions: nonViable.MergePrioritized(submissionSymbols) submission = submission.PreviousSubmission Continue Do End If ' always overload (ignore Overloads modifier): result.MergeOverloadedOrPrioritized(submissionSymbols, checkIfCurrentHasOverloads:=False) Dim first = submissionSymbols.Symbols.First If Not first.IsOverloadable Then Exit Do End If ' we are now looking for any kind of member regardless of the original binding restrictions: options = options And Not LookupOptions.NamespacesOrTypesOnly lookingForOverloadsOfKind = first.Kind Else ' found a member we are not looking for - the overload set is final now If submissionSymbols.HasSymbol AndAlso submissionSymbols.Symbols.First.Kind <> lookingForOverloadsOfKind.Value Then Exit Do End If ' found a viable overload If submissionSymbols.IsGoodOrAmbiguous Then ' merge overloads Debug.Assert(result.Symbols.All(Function(s) s.IsOverloadable)) ' always overload (ignore Overloads modifier): result.MergeOverloadedOrPrioritized(submissionSymbols, checkIfCurrentHasOverloads:=False) End If End If submission = submission.PreviousSubmission Loop Until submission Is Nothing If Not result.HasSymbol Then result.SetFrom(nonViable) End If ' TODO (tomat): extension methods submissionSymbols.Free() nonViable.Free() End Sub Public Shared Sub LookupDefaultProperty(result As LookupResult, container As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Select Case container.TypeKind Case TypeKind.Class, TypeKind.Module, TypeKind.Structure Dim tempResult = LookupResult.GetInstance() LookupDefaultPropertyInClass(result, DirectCast(container, NamedTypeSymbol), binder, tempResult, useSiteInfo) tempResult.Free() Case TypeKind.Interface Dim tempResult = LookupResult.GetInstance() LookupDefaultPropertyInInterface(result, DirectCast(container, NamedTypeSymbol), binder, tempResult, useSiteInfo) tempResult.Free() Case TypeKind.TypeParameter Dim tempResult = LookupResult.GetInstance() LookupDefaultPropertyInTypeParameter(result, DirectCast(container, TypeParameterSymbol), binder, tempResult, useSiteInfo) tempResult.Free() End Select End Sub Private Shared Sub LookupDefaultPropertyInClass( result As LookupResult, type As NamedTypeSymbol, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(type.IsClassType OrElse type.IsModuleType OrElse type.IsStructureType OrElse type.IsDelegateType) Dim accessThroughType As NamedTypeSymbol = type While type IsNot Nothing If LookupDefaultPropertyInSingleType(result, type, accessThroughType, binder, tempResult, useSiteInfo) Then Return End If ' If this is a WinRT type, we should also look for default properties in the ' implemented projected interfaces If type.ShouldAddWinRTMembers Then FindWinRTMembers(result, type, binder, tempResult, useSiteInfo, lookupMembersNotDefaultProperties:=False) If result.IsGood Then Return End If End If type = type.BaseTypeWithDefinitionUseSiteDiagnostics(useSiteInfo) End While End Sub ' See Semantics::LookupDefaultPropertyInInterface. Private Shared Sub LookupDefaultPropertyInInterface( result As LookupResult, [interface] As NamedTypeSymbol, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert([interface].IsInterfaceType) If LookupDefaultPropertyInSingleType(result, [interface], [interface], binder, tempResult, useSiteInfo) Then Return End If For Each baseInterface In [interface].InterfacesNoUseSiteDiagnostics baseInterface.OriginalDefinition.AddUseSiteInfo(useSiteInfo) LookupDefaultPropertyInBaseInterface(result, baseInterface, binder, tempResult, useSiteInfo) If result.HasDiagnostic Then Return End If Next End Sub Private Shared Sub LookupDefaultPropertyInTypeParameter( result As LookupResult, typeParameter As TypeParameterSymbol, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) ' Look up in class constraint. Dim constraintClass = typeParameter.GetClassConstraint(useSiteInfo) If constraintClass IsNot Nothing Then LookupDefaultPropertyInClass(result, constraintClass, binder, tempResult, useSiteInfo) If Not result.IsClear Then Return End If End If ' Look up in interface constraints. Dim lookIn As Queue(Of InterfaceInfo) = Nothing Dim processed As HashSet(Of InterfaceInfo) = Nothing AddInterfaceConstraints(typeParameter, lookIn, processed, useSiteInfo) If lookIn IsNot Nothing Then For Each baseInterface In lookIn LookupDefaultPropertyInBaseInterface(result, baseInterface.InterfaceType, binder, tempResult, useSiteInfo) If result.HasDiagnostic Then Return End If Next End If End Sub ' See Semantics::LookupDefaultPropertyInBaseInterface. Private Shared Sub LookupDefaultPropertyInBaseInterface( result As LookupResult, type As NamedTypeSymbol, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) If type.IsErrorType() Then Return End If Debug.Assert(type.IsInterfaceType) Debug.Assert(Not result.HasDiagnostic) Dim tmpResult = LookupResult.GetInstance() Try LookupDefaultPropertyInInterface(tmpResult, type, binder, tempResult, useSiteInfo) If Not tmpResult.HasSymbol Then Return End If If tmpResult.HasDiagnostic OrElse Not result.HasSymbol Then result.SetFrom(tmpResult) Return End If ' At least one member was found on another interface. ' Report an ambiguity error if the two interfaces are distinct. Dim symbolA = result.Symbols(0) Dim symbolB = tmpResult.Symbols(0) If symbolA.ContainingSymbol <> symbolB.ContainingSymbol Then result.MergeAmbiguous(tmpResult, AddressOf GenerateAmbiguousDefaultPropertyDiagnostic) End If Finally tmpResult.Free() End Try End Sub ' Return True if a default property is defined on the type. Private Shared Function LookupDefaultPropertyInSingleType( result As LookupResult, type As NamedTypeSymbol, accessThroughType As TypeSymbol, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) As Boolean Dim defaultPropertyName = type.DefaultPropertyName If String.IsNullOrEmpty(defaultPropertyName) Then Return False End If Select Case type.TypeKind Case TypeKind.Class, TypeKind.Module, TypeKind.Structure LookupInClass( result, type, defaultPropertyName, arity:=0, options:=LookupOptions.Default, accessThroughType:=accessThroughType, binder:=binder, tempResult:=tempResult, useSiteInfo:=useSiteInfo) Case TypeKind.Interface Debug.Assert(accessThroughType Is type) LookupInInterface( result, type, defaultPropertyName, arity:=0, options:=LookupOptions.Default, binder:=binder, tempResult:=tempResult, useSiteInfo:=useSiteInfo) Case TypeKind.TypeParameter Throw ExceptionUtilities.UnexpectedValue(type.TypeKind) End Select Return result.HasSymbol End Function Private Shared Function GenerateAmbiguousDefaultPropertyDiagnostic(symbols As ImmutableArray(Of Symbol)) As AmbiguousSymbolDiagnostic Debug.Assert(symbols.Length > 1) Dim symbolA = symbols(0) Dim containingSymbolA = symbolA.ContainingSymbol For i = 1 To symbols.Length - 1 Dim symbolB = symbols(i) Dim containingSymbolB = symbolB.ContainingSymbol If containingSymbolA <> containingSymbolB Then ' "Default property access is ambiguous between the inherited interface members '{0}' of interface '{1}' and '{2}' of interface '{3}'." Return New AmbiguousSymbolDiagnostic(ERRID.ERR_DefaultPropertyAmbiguousAcrossInterfaces4, symbols, symbolA, containingSymbolA, symbolB, containingSymbolB) End If Next ' Expected ambiguous symbols Throw ExceptionUtilities.Unreachable End Function Private Shared Sub LookupForExtensionMethodsIfNeedTo( result As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) If result.IsGood AndAlso ((options And LookupOptions.EagerlyLookupExtensionMethods) = 0 OrElse result.Symbols(0).Kind <> SymbolKind.Method) Then Return End If tempResult.Clear() LookupForExtensionMethods(tempResult, container, name, arity, options, binder, useSiteInfo) MergeInternalXmlHelperValueIfNecessary(tempResult, container, name, arity, options, binder, useSiteInfo) result.MergeOverloadedOrPrioritized(tempResult, checkIfCurrentHasOverloads:=False) End Sub Private Shared Function ShouldLookupExtensionMethods(options As LookupOptions, container As TypeSymbol) As Boolean Return options.ShouldLookupExtensionMethods AndAlso Not container.IsObjectType() AndAlso Not container.IsShared AndAlso Not container.IsModuleType() End Function Public Shared Sub LookupForExtensionMethods( lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(lookupResult.IsClear) If Not ShouldLookupExtensionMethods(options, container) Then lookupResult.SetFrom(SingleLookupResult.Empty) Return End If ' Proceed up the chain of binders, collecting extension methods Dim originalBinder = binder Dim currentBinder = binder Dim methods = ArrayBuilder(Of MethodSymbol).GetInstance() Dim proximity As Integer = 0 ' We don't want to process the same methods more than once, but the same extension method ' might be in scope in several different binders. For example, within a type, within ' imported the same type, within imported namespace containing the type. ' So, taking into consideration the fact that CollectProbableExtensionMethodsInSingleBinder ' groups methods from the same containing type together, we will keep track of the types and ' will process all the methods from the same containing type at once. Dim seenContainingTypes As New HashSet(Of NamedTypeSymbol)() Do methods.Clear() currentBinder.CollectProbableExtensionMethodsInSingleBinder(name, methods, originalBinder) Dim i As Integer = 0 Dim count As Integer = methods.Count While i < count Dim containingType As NamedTypeSymbol = methods(i).ContainingType If seenContainingTypes.Add(containingType) AndAlso ((options And LookupOptions.IgnoreAccessibility) <> 0 OrElse AccessCheck.IsSymbolAccessible(containingType, binder.Compilation.Assembly, useSiteInfo)) Then ' Process all methods from the same type together. Do ' Try to reduce this method and merge with the current result Dim reduced As MethodSymbol = methods(i).ReduceExtensionMethod(container, proximity, useSiteInfo) If reduced IsNot Nothing Then lookupResult.MergeOverloadedOrPrioritizedExtensionMethods(binder.CheckViability(reduced, arity, options, reduced.ContainingType, useSiteInfo)) End If i += 1 Loop While i < count AndAlso containingType Is methods(i).ContainingSymbol Else ' We already processed extension methods from this container before or the whole container is not accessible, ' skip the whole group of methods from this containing type. Do i += 1 Loop While i < count AndAlso containingType Is methods(i).ContainingSymbol End If End While ' Continue to containing binders. proximity += 1 currentBinder = currentBinder.m_containingBinder Loop While currentBinder IsNot Nothing methods.Free() End Sub ''' <summary> ''' Include the InternalXmlHelper.Value extension property in the LookupResult ''' if the container implements IEnumerable(Of XElement), the name is "Value", ''' and the arity is 0. ''' </summary> Private Shared Sub MergeInternalXmlHelperValueIfNecessary( lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) If (arity <> 0) OrElse Not IdentifierComparison.Equals(name, StringConstants.ValueProperty) Then Return End If Dim compilation = binder.Compilation If (options And LookupOptions.NamespacesOrTypesOnly) <> 0 OrElse Not container.IsOrImplementsIEnumerableOfXElement(compilation, useSiteInfo) Then Return End If Dim symbol = binder.GetInternalXmlHelperValueExtensionProperty() Dim singleResult As SingleLookupResult If symbol Is Nothing Then ' Match the native compiler which reports ERR_XmlFeaturesNotAvailable in this case. Dim useSiteError = ErrorFactory.ErrorInfo(ERRID.ERR_XmlFeaturesNotAvailable) singleResult = New SingleLookupResult(LookupResultKind.NotReferencable, binder.GetErrorSymbol(name, useSiteError), useSiteError) Else Dim reduced = New ReducedExtensionPropertySymbol(DirectCast(symbol, PropertySymbol)) singleResult = binder.CheckViability(reduced, arity, options, reduced.ContainingType, useSiteInfo) End If lookupResult.MergePrioritized(singleResult) End Sub Private Shared Sub AddLookupSymbolsInfoOfExtensionMethods(nameSet As LookupSymbolsInfo, container As TypeSymbol, newInfo As LookupSymbolsInfo, binder As Binder) Dim lookup = LookupResult.GetInstance() For Each name In newInfo.Names lookup.Clear() LookupForExtensionMethods(lookup, container, name, 0, LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreAccessibility, binder, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If lookup.IsGood Then For Each method As MethodSymbol In lookup.Symbols nameSet.AddSymbol(method, method.Name, method.Arity) Next End If Next lookup.Free() End Sub Public Shared Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo, container As TypeSymbol, options As LookupOptions, binder As Binder) If Not ShouldLookupExtensionMethods(options, container) Then Return End If ' We will not reduce extension methods for the purpose of this operation, ' they will still be shared methods. options = options And (Not Global.Microsoft.CodeAnalysis.VisualBasic.LookupOptions.MustBeInstance) ' Proceed up the chain of binders, collecting names of extension methods Dim currentBinder As Binder = binder Dim newInfo = LookupSymbolsInfo.GetInstance() Do currentBinder.AddExtensionMethodLookupSymbolsInfoInSingleBinder(newInfo, options, binder) ' Continue to containing binders. currentBinder = currentBinder.m_containingBinder Loop While currentBinder IsNot Nothing AddLookupSymbolsInfoOfExtensionMethods(nameSet, container, newInfo, binder) newInfo.Free() ' Include "Value" for InternalXmlHelper.Value if necessary. Dim compilation = binder.Compilation Dim useSiteInfo = CompoundUseSiteInfo(Of AssemblySymbol).DiscardedDependencies If container.IsOrImplementsIEnumerableOfXElement(compilation, useSiteInfo) AndAlso useSiteInfo.Diagnostics.IsNullOrEmpty Then nameSet.AddSymbol(Nothing, StringConstants.ValueProperty, 0) End If End Sub ''' <summary> ''' Checks if two interfaces have a base-derived relationship ''' </summary> Private Shared Function IsDerivedInterface( base As NamedTypeSymbol, derived As NamedTypeSymbol, basesBeingResolved As BasesBeingResolved, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) As Boolean Debug.Assert(base.IsInterface) Debug.Assert(derived.IsInterface) If TypeSymbol.Equals(derived.OriginalDefinition, base.OriginalDefinition, TypeCompareKind.ConsiderEverything) Then Return False End If ' if we are not resolving bases we can just go through AllInterfaces list If basesBeingResolved.InheritsBeingResolvedOpt Is Nothing Then For Each i In derived.AllInterfacesWithDefinitionUseSiteDiagnostics(useSiteInfo) If TypeSymbol.Equals(i, base, TypeCompareKind.ConsiderEverything) Then Return True End If Next Return False End If ' we are resolving bases so should use a private helper that relies only on Declared interfaces Return IsDerivedInterface(base, derived, basesBeingResolved, New HashSet(Of Symbol), useSiteInfo) End Function Private Shared Function IsDerivedInterface( base As NamedTypeSymbol, derived As NamedTypeSymbol, basesBeingResolved As BasesBeingResolved, verified As HashSet(Of Symbol), <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) As Boolean Debug.Assert(Not TypeSymbol.Equals(base, derived, TypeCompareKind.ConsiderEverything), "should already be verified for equality") Debug.Assert(base.IsInterface) Debug.Assert(derived.IsInterface) verified.Add(derived) ' not afraid of cycles here as we will not verify same symbol twice Dim interfaces = derived.GetDeclaredInterfacesWithDefinitionUseSiteDiagnostics(basesBeingResolved, useSiteInfo) If Not interfaces.IsDefaultOrEmpty Then For Each i In interfaces If TypeSymbol.Equals(i, base, TypeCompareKind.ConsiderEverything) Then Return True End If If verified.Contains(i) Then ' seen this already Continue For End If If IsDerivedInterface( base, i, basesBeingResolved, verified, useSiteInfo) Then Return True End If Next End If Return False End Function Private Structure InterfaceInfo Implements IEquatable(Of InterfaceInfo) Public ReadOnly InterfaceType As NamedTypeSymbol Public ReadOnly InComInterfaceContext As Boolean Public ReadOnly DescendantDefinitions As ImmutableHashSet(Of NamedTypeSymbol) Public Sub New(interfaceType As NamedTypeSymbol, inComInterfaceContext As Boolean, Optional descendantDefinitions As ImmutableHashSet(Of NamedTypeSymbol) = Nothing) Me.InterfaceType = interfaceType Me.InComInterfaceContext = inComInterfaceContext Me.DescendantDefinitions = descendantDefinitions End Sub Public Overrides Function GetHashCode() As Integer Return Hash.Combine(Me.InterfaceType.GetHashCode(), Me.InComInterfaceContext.GetHashCode()) End Function Public Overloads Overrides Function Equals(obj As Object) As Boolean Return TypeOf obj Is InterfaceInfo AndAlso Equals(DirectCast(obj, InterfaceInfo)) End Function Public Overloads Function Equals(other As InterfaceInfo) As Boolean Implements IEquatable(Of InterfaceInfo).Equals Return Me.InterfaceType.Equals(other.InterfaceType) AndAlso Me.InComInterfaceContext = other.InComInterfaceContext End Function End Structure Private Shared Sub LookupInInterface(lookupResult As LookupResult, container As NamedTypeSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(lookupResult.IsClear) Dim methodsOnly As Boolean = CheckAndClearMethodsOnlyOption(options) ' look in these types. Start with container, add more accordingly. Dim info As New InterfaceInfo(container, False) Dim lookIn As New Queue(Of InterfaceInfo) lookIn.Enqueue(info) Dim processed As New HashSet(Of InterfaceInfo) processed.Add(info) LookupInInterfaces(lookupResult, container, lookIn, processed, name, arity, options, binder, methodsOnly, useSiteInfo) ' If no viable or ambiguous results, look in Object. If Not lookupResult.IsGoodOrAmbiguous AndAlso (options And LookupOptions.NoSystemObjectLookupForInterfaces) = 0 Then Dim currentResult = lookupResult.GetInstance() Dim obj As NamedTypeSymbol = binder.SourceModule.ContainingAssembly.GetSpecialType(SpecialType.System_Object) LookupInClass(currentResult, obj, name, arity, options Or LookupOptions.IgnoreExtensionMethods, obj, binder, tempResult, useSiteInfo) If currentResult.IsGood Then lookupResult.SetFrom(currentResult) End If currentResult.Free() End If ClearLookupResultIfNotMethods(methodsOnly, lookupResult) LookupForExtensionMethodsIfNeedTo(lookupResult, container, name, arity, options, binder, tempResult, useSiteInfo) Return End Sub Private Shared Sub LookupInInterfaces(lookupResult As LookupResult, container As TypeSymbol, lookIn As Queue(Of InterfaceInfo), processed As HashSet(Of InterfaceInfo), name As String, arity As Integer, options As LookupOptions, binder As Binder, methodsOnly As Boolean, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(lookupResult.IsClear) Dim basesBeingResolved As BasesBeingResolved = binder.BasesBeingResolved() Dim isEventsOnlySpecified As Boolean = (options And LookupOptions.EventsOnly) <> 0 Dim currentResult = lookupResult.GetInstance() Do Dim info As InterfaceInfo = lookIn.Dequeue() Debug.Assert(processed.Contains(info)) Debug.Assert(currentResult.IsClear) LookupWithoutInheritance(currentResult, info.InterfaceType, name, arity, options, container, binder, useSiteInfo) ' if result does not shadow we will have bases to visit If Not (currentResult.StopFurtherLookup AndAlso AnyShadows(currentResult)) Then If (options And LookupOptions.NoBaseClassLookup) = 0 AndAlso Not binder.IgnoreBaseClassesInLookup Then AddBaseInterfacesToTheSearch(binder, info, lookIn, processed, useSiteInfo) End If End If Dim leaveEventsOnly As Boolean? = Nothing If info.InComInterfaceContext Then leaveEventsOnly = isEventsOnlySpecified End If If lookupResult.IsGood AndAlso currentResult.IsGood Then ' We have _another_ viable result while lookupResult is already viable. Use special interface merging rules. MergeInterfaceLookupResults(lookupResult, currentResult, basesBeingResolved, leaveEventsOnly, useSiteInfo) Else If currentResult.IsGood AndAlso leaveEventsOnly.HasValue Then FilterSymbolsInLookupResult(currentResult, SymbolKind.Event, leaveInsteadOfRemoving:=leaveEventsOnly.Value) End If lookupResult.MergePrioritized(currentResult) End If currentResult.Clear() Loop While lookIn.Count <> 0 currentResult.Free() If methodsOnly AndAlso lookupResult.IsGood Then ' We need to filter out non-method symbols from 'currentResult' ' before merging with 'lookupResult' FilterSymbolsInLookupResult(lookupResult, SymbolKind.Method, leaveInsteadOfRemoving:=True) End If ' it may look like a Good result, but it may have ambiguities inside ' so we need to check that to be sure. If lookupResult.IsGood Then Dim ambiguityDiagnostics As AmbiguousSymbolDiagnostic = Nothing Dim symbols As ArrayBuilder(Of Symbol) = lookupResult.Symbols For i As Integer = 0 To symbols.Count - 2 Dim interface1 = DirectCast(symbols(i).ContainingType, NamedTypeSymbol) For j As Integer = i + 1 To symbols.Count - 1 If Not lookupResult.CanOverload(symbols(i), symbols(j)) Then ' Symbols cannot overload each other. ' If they were from the same interface, LookupWithoutInheritance would make the result ambiguous. ' If they were from interfaces related through inheritance, one of them would shadow another, ' MergeInterfaceLookupResults handles that. ' Therefore, this symbols are from unrelated interfaces. ambiguityDiagnostics = New AmbiguousSymbolDiagnostic( ERRID.ERR_AmbiguousAcrossInterfaces3, symbols.ToImmutable, name, CustomSymbolDisplayFormatter.DefaultErrorFormat(symbols(i).ContainingType), CustomSymbolDisplayFormatter.DefaultErrorFormat(symbols(j).ContainingType)) GoTo ExitForFor End If Next Next ExitForFor: If ambiguityDiagnostics IsNot Nothing Then lookupResult.SetFrom(New SingleLookupResult(LookupResultKind.Ambiguous, symbols.First, ambiguityDiagnostics)) End If End If End Sub Private Shared Sub FilterSymbolsInLookupResult(result As LookupResult, kind As SymbolKind, leaveInsteadOfRemoving As Boolean) Debug.Assert(result.IsGood) Dim resultSymbols As ArrayBuilder(Of Symbol) = result.Symbols Debug.Assert(resultSymbols.Count > 0) Dim i As Integer = 0 Dim j As Integer = 0 While j < resultSymbols.Count Dim symbol As Symbol = resultSymbols(j) If (symbol.Kind = kind) = leaveInsteadOfRemoving Then resultSymbols(i) = resultSymbols(j) i += 1 End If j += 1 End While resultSymbols.Clip(i) If i = 0 Then result.Clear() End If End Sub Private Shared Sub LookupInTypeParameter(lookupResult As LookupResult, typeParameter As TypeParameterSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Dim methodsOnly = CheckAndClearMethodsOnlyOption(options) LookupInTypeParameterNoExtensionMethods(lookupResult, typeParameter, name, arity, options, binder, tempResult, useSiteInfo) ClearLookupResultIfNotMethods(methodsOnly, lookupResult) LookupForExtensionMethodsIfNeedTo(lookupResult, typeParameter, name, arity, options, binder, tempResult, useSiteInfo) End Sub Private Shared Sub LookupInTypeParameterNoExtensionMethods(result As LookupResult, typeParameter As TypeParameterSymbol, name As String, arity As Integer, options As LookupOptions, binder As Binder, tempResult As LookupResult, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert((options And LookupOptions.MethodsOnly) = 0) options = options Or LookupOptions.IgnoreExtensionMethods ' §4.9.2: "the class constraint hides members in interface constraints, which ' hide members in System.ValueType (if Structure constraint is specified), ' which hides members in Object." ' Look up in class constraint. Dim constraintClass = typeParameter.GetClassConstraint(useSiteInfo) If constraintClass IsNot Nothing Then LookupInClass(result, constraintClass, name, arity, options, constraintClass, binder, tempResult, useSiteInfo) If result.StopFurtherLookup Then Return End If End If ' Look up in interface constraints. Dim lookIn As Queue(Of InterfaceInfo) = Nothing Dim processed As HashSet(Of InterfaceInfo) = Nothing AddInterfaceConstraints(typeParameter, lookIn, processed, useSiteInfo) If lookIn IsNot Nothing Then ' §4.9.2: "If a member with the same name appears in more than one interface ' constraint the member is unavailable (as in multiple interface inheritance)" Dim interfaceResult = LookupResult.GetInstance() Debug.Assert((options And LookupOptions.MethodsOnly) = 0) LookupInInterfaces(interfaceResult, typeParameter, lookIn, processed, name, arity, options, binder, False, useSiteInfo) result.MergePrioritized(interfaceResult) interfaceResult.Free() If Not result.IsClear Then Return End If End If ' Look up in System.ValueType or System.Object. If constraintClass Is Nothing Then Debug.Assert(result.IsClear) Dim baseType = GetTypeParameterBaseType(typeParameter) LookupInClass(result, baseType, name, arity, options, baseType, binder, tempResult, useSiteInfo) End If End Sub Private Shared Function CheckAndClearMethodsOnlyOption(ByRef options As LookupOptions) As Boolean If (options And LookupOptions.MethodsOnly) <> 0 Then options = CType(options And (Not LookupOptions.MethodsOnly), LookupOptions) Return True End If Return False End Function Private Shared Sub ClearLookupResultIfNotMethods(methodsOnly As Boolean, lookupResult As LookupResult) If methodsOnly AndAlso lookupResult.HasSymbol AndAlso lookupResult.Symbols(0).Kind <> SymbolKind.Method Then lookupResult.Clear() End If End Sub Private Shared Sub AddInterfaceConstraints(typeParameter As TypeParameterSymbol, ByRef allInterfaces As Queue(Of InterfaceInfo), ByRef processedInterfaces As HashSet(Of InterfaceInfo), <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) For Each constraintType In typeParameter.ConstraintTypesWithDefinitionUseSiteDiagnostics(useSiteInfo) Select Case constraintType.TypeKind Case TypeKind.Interface Dim newInfo As New InterfaceInfo(DirectCast(constraintType, NamedTypeSymbol), False) If processedInterfaces Is Nothing OrElse Not processedInterfaces.Contains(newInfo) Then If processedInterfaces Is Nothing Then allInterfaces = New Queue(Of InterfaceInfo) processedInterfaces = New HashSet(Of InterfaceInfo) End If allInterfaces.Enqueue(newInfo) processedInterfaces.Add(newInfo) End If Case TypeKind.TypeParameter AddInterfaceConstraints(DirectCast(constraintType, TypeParameterSymbol), allInterfaces, processedInterfaces, useSiteInfo) End Select Next End Sub ''' <summary> ''' Merges two lookup results while eliminating symbols that are shadowed. ''' Note that the final result may contain unrelated and possibly conflicting symbols as ''' this helper is not intended to catch ambiguities. ''' </summary> ''' <param name="leaveEventsOnly"> ''' If is not Nothing and False filters out all Event symbols, and if is not Nothing ''' and True filters out all non-Event symbols, nos not have any effect otherwise. ''' Is used for special handling of Events inside COM interfaces. ''' </param> Private Shared Sub MergeInterfaceLookupResults( knownResult As LookupResult, newResult As LookupResult, BasesBeingResolved As BasesBeingResolved, leaveEventsOnly As Boolean?, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(knownResult.Kind = newResult.Kind) Dim knownSymbols As ArrayBuilder(Of Symbol) = knownResult.Symbols Dim newSymbols As ArrayBuilder(Of Symbol) = newResult.Symbols Dim newSymbolContainer = newSymbols.First().ContainingType For i As Integer = 0 To knownSymbols.Count - 1 Dim knownSymbol = knownSymbols(i) ' Nothing means that the symbol has been eliminated via shadowing If knownSymbol Is Nothing Then Continue For End If Dim knownSymbolContainer = knownSymbol.ContainingType For j As Integer = 0 To newSymbols.Count - 1 Dim newSymbol As Symbol = newSymbols(j) ' Nothing means that the symbol has been eliminated via shadowing If newSymbol Is Nothing Then Continue For End If ' Special-case events in case we are inside COM interface If leaveEventsOnly.HasValue AndAlso (newSymbol.Kind = SymbolKind.Event) <> leaveEventsOnly.Value Then newSymbols(j) = Nothing Continue For End If If knownSymbol = newSymbol Then ' this is the same result as we already have, remove from the new set newSymbols(j) = Nothing Continue For End If ' container of the first new symbol should be container of all others Debug.Assert(TypeSymbol.Equals(newSymbolContainer, newSymbol.ContainingType, TypeCompareKind.ConsiderEverything)) ' Are the known and new symbols of the right kinds to overload? Dim cantOverloadEachOther = Not LookupResult.CanOverload(knownSymbol, newSymbol) If IsDerivedInterface(base:=newSymbolContainer, derived:=knownSymbolContainer, basesBeingResolved:=BasesBeingResolved, useSiteInfo:=useSiteInfo) Then ' if currently known is more derived and shadows the new one ' it shadows all the new ones and we are done If IsShadows(knownSymbol) OrElse cantOverloadEachOther Then ' no need to continue with merge. new symbols are all shadowed ' and they cannot shadow anything in the old set Debug.Assert(Not knownSymbols.Any(Function(s) s Is Nothing)) newResult.Clear() Return End If ElseIf IsDerivedInterface(base:=knownSymbolContainer, derived:=newSymbolContainer, basesBeingResolved:=BasesBeingResolved, useSiteInfo:=useSiteInfo) Then ' if new is more derived and shadows ' the current one should be dropped ' NOTE that we continue iterating as more known symbols may be "shadowed out" by the current. If IsShadows(newSymbol) OrElse cantOverloadEachOther Then knownSymbols(i) = Nothing ' all following known symbols in the same container are shadowed by the new one ' we can do a quick check and remove them here For k = i + 1 To knownSymbols.Count - 1 Dim otherKnown As Symbol = knownSymbols(k) If otherKnown IsNot Nothing AndAlso TypeSymbol.Equals(otherKnown.ContainingType, knownSymbolContainer, TypeCompareKind.ConsiderEverything) Then knownSymbols(k) = Nothing End If Next End If End If ' we can get here if results are completely unrelated. ' However we do not know if they are conflicting as either one could be "shadowed out" in later iterations. ' for now we let both known and new stay Next Next CompactAndAppend(knownSymbols, newSymbols) newResult.Clear() End Sub ''' <summary> ''' first.Where(t IsNot Nothing).Concat(second.Where(t IsNot Nothing)) ''' </summary> Private Shared Sub CompactAndAppend(first As ArrayBuilder(Of Symbol), second As ArrayBuilder(Of Symbol)) Dim i As Integer = 0 ' skip non nulls While i < first.Count If first(i) Is Nothing Then Exit While End If i += 1 End While ' compact the rest Dim j As Integer = i + 1 While j < first.Count Dim item As Symbol = first(j) If item IsNot Nothing Then first(i) = item i += 1 End If j += 1 End While ' clip to compacted size first.Clip(i) ' append non nulls from second i = 0 While i < second.Count Dim items As Symbol = second(i) If items IsNot Nothing Then first.Add(items) End If i += 1 End While End Sub ''' <summary> ''' ''' </summary> Private Shared Sub AddBaseInterfacesToTheSearch(binder As Binder, currentInfo As InterfaceInfo, lookIn As Queue(Of InterfaceInfo), processed As HashSet(Of InterfaceInfo), <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Dim interfaces As ImmutableArray(Of NamedTypeSymbol) = currentInfo.InterfaceType.GetDirectBaseInterfacesNoUseSiteDiagnostics(binder.BasesBeingResolved) If Not interfaces.IsDefaultOrEmpty Then Dim inComInterfaceContext As Boolean = currentInfo.InComInterfaceContext OrElse currentInfo.InterfaceType.CoClassType IsNot Nothing Dim descendants As ImmutableHashSet(Of NamedTypeSymbol) If binder.BasesBeingResolved.InheritsBeingResolvedOpt Is Nothing Then descendants = Nothing Else ' We need to watch out for cycles in inheritance chain since they are not broken while bases are being resolved. If currentInfo.DescendantDefinitions Is Nothing Then descendants = ImmutableHashSet.Create(currentInfo.InterfaceType.OriginalDefinition) Else descendants = currentInfo.DescendantDefinitions.Add(currentInfo.InterfaceType.OriginalDefinition) End If End If For Each i In interfaces If descendants IsNot Nothing AndAlso descendants.Contains(i.OriginalDefinition) Then ' About to get in an inheritance cycle Continue For End If i.OriginalDefinition.AddUseSiteInfo(useSiteInfo) Dim newInfo As New InterfaceInfo(i, inComInterfaceContext, descendants) If processed.Add(newInfo) Then lookIn.Enqueue(newInfo) End If Next End If End Sub ''' <summary> ''' if any symbol in the list Shadows. This implies that name is not visible through the base. ''' </summary> Private Shared Function AnyShadows(result As LookupResult) As Boolean For Each sym As Symbol In result.Symbols If sym.IsShadows Then Return True End If Next Return False End Function ' Find all names in a non-interface type, consider inheritance. Private Shared Sub AddLookupSymbolsInfoInClass(nameSet As LookupSymbolsInfo, container As TypeSymbol, options As LookupOptions, binder As Binder) ' We need a check for SpecialType.System_Void as its base type is ' ValueType but we don't wish to return any members for void type If container IsNot Nothing And container.SpecialType = SpecialType.System_Void Then Return End If ' Lookup proceeds up the base class chain. Dim currentType = container Do AddLookupSymbolsInfoWithoutInheritance(nameSet, currentType, options, container, binder) ' If the type is from a winmd file and implements any of the special WinRT collection ' projections, then we may need to add projected interface members Dim namedType = TryCast(currentType, NamedTypeSymbol) If namedType IsNot Nothing AndAlso namedType.ShouldAddWinRTMembers Then AddWinRTMembersLookupSymbolsInfo(nameSet, namedType, options, container, binder) End If ' Go to base type, unless that would case infinite recursion or the options or the binder ' disallows it. If (options And LookupOptions.NoBaseClassLookup) <> 0 OrElse binder.IgnoreBaseClassesInLookup Then currentType = Nothing Else currentType = currentType.GetDirectBaseTypeNoUseSiteDiagnostics(binder.BasesBeingResolved) End If Loop While currentType IsNot Nothing ' Search for extension methods. AddExtensionMethodLookupSymbolsInfo(nameSet, container, options, binder) ' Special case: if we're in a constructor of a class or structure, then we can call constructors on ourself or our immediate base ' (via Me.New or MyClass.New or MyBase.New). We don't have enough info to check the constraints that the constructor must be ' the specific tokens Me, MyClass, or MyBase, or that its the first statement in the constructor, so services must do ' that check if it wants to show that. ' Roslyn Bug 9701. Dim containingMethod = TryCast(binder.ContainingMember, MethodSymbol) If containingMethod IsNot Nothing AndAlso containingMethod.MethodKind = MethodKind.Constructor AndAlso (container.TypeKind = TypeKind.Class OrElse container.TypeKind = TypeKind.Structure) AndAlso (TypeSymbol.Equals(containingMethod.ContainingType, container, TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(containingMethod.ContainingType.BaseTypeNoUseSiteDiagnostics, container, TypeCompareKind.ConsiderEverything)) Then nameSet.AddSymbol(Nothing, WellKnownMemberNames.InstanceConstructorName, 0) End If End Sub Private Shared Sub AddLookupSymbolsInfoInSubmissions(nameSet As LookupSymbolsInfo, submissionClass As TypeSymbol, options As LookupOptions, binder As Binder) Dim submission = binder.Compilation Do ' TODO (tomat): import aliases If submission.ScriptClass IsNot Nothing Then AddLookupSymbolsInfoWithoutInheritance(nameSet, submission.ScriptClass, options, submissionClass, binder) End If submission = submission.PreviousSubmission Loop Until submission Is Nothing ' TODO (tomat): extension methods End Sub ' Find all names in an interface type, consider inheritance. Private Shared Sub AddLookupSymbolsInfoInInterface(nameSet As LookupSymbolsInfo, container As NamedTypeSymbol, options As LookupOptions, binder As Binder) Dim info As New InterfaceInfo(container, False) Dim lookIn As New Queue(Of InterfaceInfo) lookIn.Enqueue(info) Dim processed As New HashSet(Of InterfaceInfo) processed.Add(info) AddLookupSymbolsInfoInInterfaces(nameSet, container, lookIn, processed, options, binder) ' Look in Object. AddLookupSymbolsInfoInClass(nameSet, binder.SourceModule.ContainingAssembly.GetSpecialType(SpecialType.System_Object), options Or LookupOptions.IgnoreExtensionMethods, binder) ' Search for extension methods. AddExtensionMethodLookupSymbolsInfo(nameSet, container, options, binder) End Sub Private Shared Sub AddLookupSymbolsInfoInInterfaces(nameSet As LookupSymbolsInfo, container As TypeSymbol, lookIn As Queue(Of InterfaceInfo), processed As HashSet(Of InterfaceInfo), options As LookupOptions, binder As Binder) Dim useSiteInfo = CompoundUseSiteInfo(Of AssemblySymbol).Discarded Do Dim currentType As InterfaceInfo = lookIn.Dequeue AddLookupSymbolsInfoWithoutInheritance(nameSet, currentType.InterfaceType, options, container, binder) ' Go to base type, unless that would case infinite recursion or the options or the binder ' disallows it. If (options And LookupOptions.NoBaseClassLookup) = 0 AndAlso Not binder.IgnoreBaseClassesInLookup Then AddBaseInterfacesToTheSearch(binder, currentType, lookIn, processed, useSiteInfo) End If Loop While lookIn.Count <> 0 End Sub Private Shared Sub AddLookupSymbolsInfoInTypeParameter(nameSet As LookupSymbolsInfo, typeParameter As TypeParameterSymbol, options As LookupOptions, binder As Binder) If typeParameter.TypeParameterKind = TypeParameterKind.Cref Then Return End If AddLookupSymbolsInfoInTypeParameterNoExtensionMethods(nameSet, typeParameter, options, binder) ' Search for extension methods. AddExtensionMethodLookupSymbolsInfo(nameSet, typeParameter, options, binder) End Sub Private Shared Sub AddLookupSymbolsInfoInTypeParameterNoExtensionMethods(nameSet As LookupSymbolsInfo, typeParameter As TypeParameterSymbol, options As LookupOptions, binder As Binder) options = options Or LookupOptions.IgnoreExtensionMethods ' Look up in class constraint. Dim constraintClass = typeParameter.GetClassConstraint(CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If constraintClass IsNot Nothing Then AddLookupSymbolsInfoInClass(nameSet, constraintClass, options, binder) End If ' Look up in interface constraints. Dim lookIn As Queue(Of InterfaceInfo) = Nothing Dim processed As HashSet(Of InterfaceInfo) = Nothing AddInterfaceConstraints(typeParameter, lookIn, processed, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If lookIn IsNot Nothing Then AddLookupSymbolsInfoInInterfaces(nameSet, typeParameter, lookIn, processed, options, binder) End If ' Look up in System.ValueType or System.Object. If constraintClass Is Nothing Then Dim baseType = GetTypeParameterBaseType(typeParameter) AddLookupSymbolsInfoInClass(nameSet, baseType, options, binder) End If End Sub ''' <summary> ''' Lookup a member name in a type without considering inheritance, returning a LookupResult that ''' summarizes the results of the lookup. See LookupResult structure for a detailed ''' discussing of the meaning of the results. ''' </summary> Private Shared Sub LookupWithoutInheritance(lookupResult As LookupResult, container As TypeSymbol, name As String, arity As Integer, options As LookupOptions, accessThroughType As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Dim members As ImmutableArray(Of Symbol) = ImmutableArray(Of Symbol).Empty If (options And (LookupOptions.NamespacesOrTypesOnly Or LookupOptions.LabelsOnly)) = LookupOptions.NamespacesOrTypesOnly Then ' Only named types have members that are types. Go through all the types in this type and ' validate them. If there's multiple, give an error. If TypeOf container Is NamedTypeSymbol Then members = ImmutableArray(Of Symbol).CastUp(container.GetTypeMembers(name)) End If ElseIf (options And LookupOptions.LabelsOnly) = 0 Then members = container.GetMembers(name) End If Debug.Assert(lookupResult.IsClear) ' Go through each member of the type, and combine them into a single result. Overloadable members ' are combined together, while other duplicates cause an ambiguity error. If Not members.IsDefaultOrEmpty Then Dim imported As Boolean = container.ContainingModule IsNot binder.SourceModule For Each sym In members lookupResult.MergeMembersOfTheSameType(binder.CheckViability(sym, arity, options, accessThroughType, useSiteInfo), imported) Next End If End Sub ' Find all names in a type, without considering inheritance. Private Shared Sub AddLookupSymbolsInfoWithoutInheritance(nameSet As LookupSymbolsInfo, container As TypeSymbol, options As LookupOptions, accessThroughType As TypeSymbol, binder As Binder) ' UNDONE: validate symbols with something that looks like ValidateSymbol. If (options And (LookupOptions.NamespacesOrTypesOnly Or LookupOptions.LabelsOnly)) = LookupOptions.NamespacesOrTypesOnly Then ' Only named types have members that are types. Go through all the types in this type and ' validate them. If TypeOf container Is NamedTypeSymbol Then For Each sym In container.GetTypeMembersUnordered() If binder.CanAddLookupSymbolInfo(sym, options, nameSet, accessThroughType) Then nameSet.AddSymbol(sym, sym.Name, sym.Arity) End If Next End If ElseIf (options And LookupOptions.LabelsOnly) = 0 Then ' Go through each member of the type. For Each sym In container.GetMembersUnordered() If binder.CanAddLookupSymbolInfo(sym, options, nameSet, accessThroughType) Then nameSet.AddSymbol(sym, sym.Name, sym.GetArity()) End If Next End If End Sub Private Shared Sub AddWinRTMembersLookupSymbolsInfo( nameSet As LookupSymbolsInfo, type As NamedTypeSymbol, options As LookupOptions, accessThroughType As TypeSymbol, binder As Binder ) ' Dev11 searches all declared and undeclared base interfaces For Each iface In type.AllInterfacesNoUseSiteDiagnostics If IsWinRTProjectedInterface(iface, binder.Compilation) Then AddLookupSymbolsInfoWithoutInheritance(nameSet, iface, options, accessThroughType, binder) End If Next End Sub Private Shared Function GetTypeParameterBaseType(typeParameter As TypeParameterSymbol) As NamedTypeSymbol ' The default base type should only be used if there is no explicit class constraint. Debug.Assert(typeParameter.GetClassConstraint(CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Is Nothing) Return typeParameter.ContainingAssembly.GetSpecialType(If(typeParameter.HasValueTypeConstraint, SpecialType.System_ValueType, SpecialType.System_Object)) 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/Compilers/Core/Portable/Symbols/IFieldSymbolInternal.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.Symbols { internal interface IFieldSymbolInternal : ISymbolInternal { /// <summary> /// Returns true if this field was declared as "volatile". /// </summary> bool IsVolatile { get; } } }
// 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.Symbols { internal interface IFieldSymbolInternal : ISymbolInternal { /// <summary> /// Returns true if this field was declared as "volatile". /// </summary> bool IsVolatile { get; } } }
-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/Diagnostics/Configuration/ConfigureSeverity/CSharpCodeStyleOptionBasedSeverityConfigurationTests.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.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity; using Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureSeverity { public abstract partial class CSharpCodeStyleOptionBasedSeverityConfigurationTests : AbstractSuppressionDiagnosticTest { protected internal override string GetLanguage() => LanguageNames.CSharp; protected override ParseOptions GetScriptOptions() => Options.Script; internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider()); } public class ErrorConfigurationTests : CSharpCodeStyleOptionBasedSeverityConfigurationTests { protected override int CodeActionIndex => 4; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""> </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # IDE0059: Unnecessary assignment of a value dotnet_diagnostic.IDE0059.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_ExistingRule_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = discard_variable:warning dotnet_diagnostic.IDE0059.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = discard_variable:error dotnet_diagnostic.IDE0059.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_ExistingRuleDotNetHeader_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = discard_variable:warning dotnet_diagnostic.IDE0059.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = discard_variable:error dotnet_diagnostic.IDE0059.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_ChooseBestHeader_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = false:silent [*.{vb,cs}] dotnet_style_qualification_for_field = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = false:silent # IDE0059: Unnecessary assignment of a value dotnet_diagnostic.IDE0059.severity = error [*.{vb,cs}] dotnet_style_qualification_for_field = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_ChooseBestHeaderReversed_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_qualification_for_field = false:silent [*.cs] csharp_style_expression_bodied_methods = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_qualification_for_field = false:silent [*.cs] csharp_style_expression_bodied_methods = false:silent # IDE0059: Unnecessary assignment of a value dotnet_diagnostic.IDE0059.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } } }
// 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.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity; using Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureSeverity { public abstract partial class CSharpCodeStyleOptionBasedSeverityConfigurationTests : AbstractSuppressionDiagnosticTest { protected internal override string GetLanguage() => LanguageNames.CSharp; protected override ParseOptions GetScriptOptions() => Options.Script; internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider()); } public class ErrorConfigurationTests : CSharpCodeStyleOptionBasedSeverityConfigurationTests { protected override int CodeActionIndex => 4; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""> </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # IDE0059: Unnecessary assignment of a value dotnet_diagnostic.IDE0059.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_ExistingRule_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = discard_variable:warning dotnet_diagnostic.IDE0059.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = discard_variable:error dotnet_diagnostic.IDE0059.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_ExistingRuleDotNetHeader_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = discard_variable:warning dotnet_diagnostic.IDE0059.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = discard_variable:error dotnet_diagnostic.IDE0059.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_ChooseBestHeader_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = false:silent [*.{vb,cs}] dotnet_style_qualification_for_field = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = false:silent # IDE0059: Unnecessary assignment of a value dotnet_diagnostic.IDE0059.severity = error [*.{vb,cs}] dotnet_style_qualification_for_field = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_ChooseBestHeaderReversed_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_qualification_for_field = false:silent [*.cs] csharp_style_expression_bodied_methods = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> public class Class1 { public int Test() { var o = 1; // csharp_style_unused_value_assignment_preference = discard_variable var [|unused|] = o; return 1; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_qualification_for_field = false:silent [*.cs] csharp_style_expression_bodied_methods = false:silent # IDE0059: Unnecessary assignment of a value dotnet_diagnostic.IDE0059.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } } }
-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/Services/SyntaxFacts/ISyntaxFactsExtensions.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.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal static class ISyntaxFactsExtensions { public static bool IsLegalIdentifier(this ISyntaxFacts syntaxFacts, string name) { if (name.Length == 0) { return false; } if (!syntaxFacts.IsIdentifierStartCharacter(name[0])) { return false; } for (var i = 1; i < name.Length; i++) { if (!syntaxFacts.IsIdentifierPartCharacter(name[i])) { return false; } } return true; } public static bool IsReservedOrContextualKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token) => syntaxFacts.IsReservedKeyword(token) || syntaxFacts.IsContextualKeyword(token); public static bool IsWord(this ISyntaxFacts syntaxFacts, SyntaxToken token) { return syntaxFacts.IsIdentifier(token) || syntaxFacts.IsReservedOrContextualKeyword(token) || syntaxFacts.IsPreprocessorKeyword(token); } public static bool IsAnyMemberAccessExpression( this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) { return syntaxFacts.IsSimpleMemberAccessExpression(node) || syntaxFacts.IsPointerMemberAccessExpression(node); } public static bool IsRegularOrDocumentationComment(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => syntaxFacts.IsRegularComment(trivia) || syntaxFacts.IsDocumentationComment(trivia); public static ImmutableArray<SyntaxTrivia> GetTriviaAfterLeadingBlankLines( this ISyntaxFacts syntaxFacts, SyntaxNode node) { var leadingBlankLines = syntaxFacts.GetLeadingBlankLines(node); return node.GetLeadingTrivia().Skip(leadingBlankLines.Length).ToImmutableArray(); } public static void GetPartsOfAssignmentStatement( this ISyntaxFacts syntaxFacts, SyntaxNode statement, out SyntaxNode left, out SyntaxNode right) { syntaxFacts.GetPartsOfAssignmentStatement(statement, out left, out _, out right); } public static SyntaxNode GetExpressionOfInvocationExpression( this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfInvocationExpression(node, out var expression, out _); return expression; } public static SyntaxNode Unparenthesize( this ISyntaxFacts syntaxFacts, SyntaxNode node) { SyntaxToken openParenToken; SyntaxNode operand; SyntaxToken closeParenToken; if (syntaxFacts.IsParenthesizedPattern(node)) { syntaxFacts.GetPartsOfParenthesizedPattern(node, out openParenToken, out operand, out closeParenToken); } else { syntaxFacts.GetPartsOfParenthesizedExpression(node, out openParenToken, out operand, out closeParenToken); } var leadingTrivia = openParenToken.LeadingTrivia .Concat(openParenToken.TrailingTrivia) .Where(t => !syntaxFacts.IsElastic(t)) .Concat(operand.GetLeadingTrivia()); var trailingTrivia = operand.GetTrailingTrivia() .Concat(closeParenToken.LeadingTrivia) .Where(t => !syntaxFacts.IsElastic(t)) .Concat(closeParenToken.TrailingTrivia); var resultNode = operand .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(trailingTrivia); // If there's no trivia between the original node and the tokens around it, then add // elastic markers so the formatting engine will spaces if necessary to keep things // parseable. if (resultNode.GetLeadingTrivia().Count == 0) { var previousToken = node.GetFirstToken().GetPreviousToken(); if (previousToken.TrailingTrivia.Count == 0 && syntaxFacts.IsWordOrNumber(previousToken) && syntaxFacts.IsWordOrNumber(resultNode.GetFirstToken())) { resultNode = resultNode.WithPrependedLeadingTrivia(syntaxFacts.ElasticMarker); } } if (resultNode.GetTrailingTrivia().Count == 0) { var nextToken = node.GetLastToken().GetNextToken(); if (nextToken.LeadingTrivia.Count == 0 && syntaxFacts.IsWordOrNumber(nextToken) && syntaxFacts.IsWordOrNumber(resultNode.GetLastToken())) { resultNode = resultNode.WithAppendedTrailingTrivia(syntaxFacts.ElasticMarker); } } return resultNode; } private static bool IsWordOrNumber(this ISyntaxFacts syntaxFacts, SyntaxToken token) => syntaxFacts.IsWord(token) || syntaxFacts.IsNumericLiteral(token); public static bool SpansPreprocessorDirective(this ISyntaxFacts service, SyntaxNode node) => service.SpansPreprocessorDirective(SpecializedCollections.SingletonEnumerable(node)); public static bool SpansPreprocessorDirective(this ISyntaxFacts service, params SyntaxNode[] nodes) => service.SpansPreprocessorDirective(nodes); public static bool IsWhitespaceOrEndOfLineTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => syntaxFacts.IsWhitespaceTrivia(trivia) || syntaxFacts.IsEndOfLineTrivia(trivia); public static void GetPartsOfBinaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode left, out SyntaxNode right) => syntaxFacts.GetPartsOfBinaryExpression(node, out left, out _, out right); public static SyntaxNode GetPatternOfParenthesizedPattern(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfParenthesizedPattern(node, out _, out var pattern, out _); return pattern; } public static SyntaxNode GetExpressionOfParenthesizedExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfParenthesizedExpression(node, out _, out var expression, out _); return expression; } public static SyntaxToken GetOperatorTokenOfBinaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfBinaryExpression(node, out _, out var token, out _); return token; } public static bool IsAnonymousOrLocalFunction(this ISyntaxFacts syntaxFacts, SyntaxNode node) => syntaxFacts.IsAnonymousFunction(node) || syntaxFacts.IsLocalFunctionStatement(node); public static SyntaxNode? GetExpressionOfElementAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfElementAccessExpression(node, out var expression, out _); return expression; } public static SyntaxNode? GetArgumentListOfElementAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfElementAccessExpression(node, out _, out var argumentList); return argumentList; } public static SyntaxNode GetExpressionOfConditionalAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfConditionalAccessExpression(node, out var expression, out _); return expression; } public static SyntaxToken GetOperatorTokenOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfMemberAccessExpression(node, out _, out var operatorToken, out _); return operatorToken; } public static void GetPartsOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode expression, out SyntaxNode name) => syntaxFacts.GetPartsOfMemberAccessExpression(node, out expression, out _, out name); public static void GetPartsOfConditionalAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode expression, out SyntaxNode whenNotNull) => syntaxFacts.GetPartsOfConditionalAccessExpression(node, out expression, out _, out whenNotNull); public static TextSpan GetSpanWithoutAttributes(this ISyntaxFacts syntaxFacts, SyntaxNode root, SyntaxNode node) { // Span without AttributeLists // - No AttributeLists -> original .Span // - Some AttributeLists -> (first non-trivia/comment Token.Span.Begin, original.Span.End) // - We need to be mindful about comments due to: // // [Test1] // //Comment1 // [||]object Property1 { get; set; } // the comment node being part of the next token's (`object`) leading trivia and not the AttributeList's node. // - In case only attribute is written we need to be careful to not to use next (unrelated) token as beginning current the node. var attributeList = syntaxFacts.GetAttributeLists(node); if (attributeList.Any()) { var endOfAttributeLists = attributeList.Last().Span.End; var afterAttributesToken = root.FindTokenOnRightOfPosition(endOfAttributeLists); var endOfNode = node.Span.End; var startOfNodeWithoutAttributes = Math.Min(afterAttributesToken.Span.Start, endOfNode); return TextSpan.FromBounds(startOfNodeWithoutAttributes, endOfNode); } return node.Span; } /// <summary> /// Checks if the position is on the header of a type (from the start of the type up through it's name). /// </summary> public static bool IsOnTypeHeader(this ISyntaxFacts syntaxFacts, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) => syntaxFacts.IsOnTypeHeader(root, position, fullHeader: false, out typeDeclaration); /// <summary> /// Gets the statement container node for the statement <paramref name="node"/>. /// </summary> /// <param name="syntaxFacts">The <see cref="ISyntaxFacts"/> implementation.</param> /// <param name="node">The statement.</param> /// <returns>The statement container for <paramref name="node"/>.</returns> public static SyntaxNode? GetStatementContainer(this ISyntaxFacts syntaxFacts, SyntaxNode node) { for (var current = node; current is object; current = current.Parent) { if (syntaxFacts.IsStatementContainer(current.Parent)) { return current.Parent; } } return null; } /// <summary> /// Similar to <see cref="ISyntaxFacts.GetStandaloneExpression(SyntaxNode)"/>, this gets the containing /// expression that is actually a language expression and not just typed as an ExpressionSyntax for convenience. /// However, this goes beyond that that method in that if this expression is the RHS of a conditional access /// (i.e. <c>a?.b()</c>) it will also return the root of the conditional access expression tree. /// <para/> The intuition here is that this will give the topmost expression node that could realistically be /// replaced with any other expression. For example, with <c>a?.b()</c> technically <c>.b()</c> is an /// expression. But that cannot be replaced with something like <c>(1 + 1)</c> (as <c>a?.(1 + 1)</c> is not /// legal). However, in <c>a?.b()</c>, then <c>a</c> itself could be replaced with <c>(1 + 1)?.b()</c> to form /// a legal expression. /// </summary> public static SyntaxNode GetRootStandaloneExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { // First, make sure we're on a construct the language things is a standalone expression. var standalone = syntaxFacts.GetStandaloneExpression(node); // Then, if this is the RHS of a `?`, walk up to the top of that tree to get the final standalone expression. return syntaxFacts.GetRootConditionalAccessExpression(standalone) ?? standalone; } #region ISyntaxKinds forwarding methods #region trivia public static bool IsEndOfLineTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => trivia.RawKind == syntaxFacts.SyntaxKinds.EndOfLineTrivia; public static bool IsWhitespaceTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => trivia.RawKind == syntaxFacts.SyntaxKinds.WhitespaceTrivia; public static bool IsSkippedTokensTrivia(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.SkippedTokensTrivia; #endregion #region keywords public static bool IsAwaitKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.AwaitKeyword; public static bool IsGlobalNamespaceKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.GlobalKeyword; #endregion #region literal tokens public static bool IsCharacterLiteral(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.CharacterLiteralToken; public static bool IsStringLiteral(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.StringLiteralToken; #endregion #region tokens public static bool IsIdentifier(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.IdentifierToken; public static bool IsHashToken(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.HashToken; public static bool IsInterpolatedStringTextToken(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringTextToken; #endregion #region names public static bool IsGenericName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.GenericName; public static bool IsIdentifierName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.IdentifierName; public static bool IsQualifiedName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.QualifiedName; #endregion #region types public static bool IsTupleType(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TupleType; #endregion #region literal expressions public static bool IsCharacterLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.CharacterLiteralExpression; public static bool IsDefaultLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.DefaultLiteralExpression; public static bool IsFalseLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.FalseLiteralExpression; public static bool IsNullLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.NullLiteralExpression; public static bool IsStringLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.StringLiteralExpression; public static bool IsTrueLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TrueLiteralExpression; #endregion #region expressions public static bool IsAwaitExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.AwaitExpression; public static bool IsImplicitObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => syntaxFacts.IsImplicitObjectCreation(node); public static bool IsBaseExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.BaseExpression; public static bool IsConditionalAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ConditionalAccessExpression; public static bool IsInterpolatedStringExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringExpression; public static bool IsInterpolation(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.Interpolation; public static bool IsInterpolatedStringText(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringText; public static bool IsInvocationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.InvocationExpression; public static bool IsLogicalAndExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LogicalAndExpression; public static bool IsLogicalOrExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LogicalOrExpression; public static bool IsLogicalNotExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LogicalNotExpression; public static bool IsObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ObjectCreationExpression; public static bool IsParenthesizedExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ParenthesizedExpression; public static bool IsQueryExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.QueryExpression; public static bool IsSimpleMemberAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.SimpleMemberAccessExpression; public static bool IsThisExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ThisExpression; public static bool IsTupleExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TupleExpression; public static bool ContainsGlobalStatement(this ISyntaxFacts syntaxFacts, SyntaxNode node) => node.ChildNodes().Any(c => c.RawKind == syntaxFacts.SyntaxKinds.GlobalStatement); #endregion #region statements public static bool IsExpressionStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ExpressionStatement; public static bool IsForEachStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ForEachStatement; public static bool IsLocalDeclarationStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LocalDeclarationStatement; public static bool IsLockStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LockStatement; public static bool IsReturnStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode node) => node?.RawKind == syntaxFacts.SyntaxKinds.ReturnStatement; public static bool IsUsingStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.UsingStatement; #endregion #region members/declarations public static bool IsAttribute(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.Attribute; public static bool IsGlobalAttribute(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => syntaxFacts.IsGlobalAssemblyAttribute(node) || syntaxFacts.IsGlobalModuleAttribute(node); public static bool IsParameter(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.Parameter; public static bool IsTypeConstraint(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TypeConstraint; public static bool IsVariableDeclarator(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.VariableDeclarator; public static bool IsFieldDeclaration(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.FieldDeclaration; public static bool IsTypeArgumentList(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TypeArgumentList; #endregion #region clauses public static bool IsEqualsValueClause(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.EqualsValueClause; #endregion #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.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal static class ISyntaxFactsExtensions { public static bool IsLegalIdentifier(this ISyntaxFacts syntaxFacts, string name) { if (name.Length == 0) { return false; } if (!syntaxFacts.IsIdentifierStartCharacter(name[0])) { return false; } for (var i = 1; i < name.Length; i++) { if (!syntaxFacts.IsIdentifierPartCharacter(name[i])) { return false; } } return true; } public static bool IsReservedOrContextualKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token) => syntaxFacts.IsReservedKeyword(token) || syntaxFacts.IsContextualKeyword(token); public static bool IsWord(this ISyntaxFacts syntaxFacts, SyntaxToken token) { return syntaxFacts.IsIdentifier(token) || syntaxFacts.IsReservedOrContextualKeyword(token) || syntaxFacts.IsPreprocessorKeyword(token); } public static bool IsAnyMemberAccessExpression( this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) { return syntaxFacts.IsSimpleMemberAccessExpression(node) || syntaxFacts.IsPointerMemberAccessExpression(node); } public static bool IsRegularOrDocumentationComment(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => syntaxFacts.IsRegularComment(trivia) || syntaxFacts.IsDocumentationComment(trivia); public static ImmutableArray<SyntaxTrivia> GetTriviaAfterLeadingBlankLines( this ISyntaxFacts syntaxFacts, SyntaxNode node) { var leadingBlankLines = syntaxFacts.GetLeadingBlankLines(node); return node.GetLeadingTrivia().Skip(leadingBlankLines.Length).ToImmutableArray(); } public static void GetPartsOfAssignmentStatement( this ISyntaxFacts syntaxFacts, SyntaxNode statement, out SyntaxNode left, out SyntaxNode right) { syntaxFacts.GetPartsOfAssignmentStatement(statement, out left, out _, out right); } public static SyntaxNode GetExpressionOfInvocationExpression( this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfInvocationExpression(node, out var expression, out _); return expression; } public static SyntaxNode Unparenthesize( this ISyntaxFacts syntaxFacts, SyntaxNode node) { SyntaxToken openParenToken; SyntaxNode operand; SyntaxToken closeParenToken; if (syntaxFacts.IsParenthesizedPattern(node)) { syntaxFacts.GetPartsOfParenthesizedPattern(node, out openParenToken, out operand, out closeParenToken); } else { syntaxFacts.GetPartsOfParenthesizedExpression(node, out openParenToken, out operand, out closeParenToken); } var leadingTrivia = openParenToken.LeadingTrivia .Concat(openParenToken.TrailingTrivia) .Where(t => !syntaxFacts.IsElastic(t)) .Concat(operand.GetLeadingTrivia()); var trailingTrivia = operand.GetTrailingTrivia() .Concat(closeParenToken.LeadingTrivia) .Where(t => !syntaxFacts.IsElastic(t)) .Concat(closeParenToken.TrailingTrivia); var resultNode = operand .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(trailingTrivia); // If there's no trivia between the original node and the tokens around it, then add // elastic markers so the formatting engine will spaces if necessary to keep things // parseable. if (resultNode.GetLeadingTrivia().Count == 0) { var previousToken = node.GetFirstToken().GetPreviousToken(); if (previousToken.TrailingTrivia.Count == 0 && syntaxFacts.IsWordOrNumber(previousToken) && syntaxFacts.IsWordOrNumber(resultNode.GetFirstToken())) { resultNode = resultNode.WithPrependedLeadingTrivia(syntaxFacts.ElasticMarker); } } if (resultNode.GetTrailingTrivia().Count == 0) { var nextToken = node.GetLastToken().GetNextToken(); if (nextToken.LeadingTrivia.Count == 0 && syntaxFacts.IsWordOrNumber(nextToken) && syntaxFacts.IsWordOrNumber(resultNode.GetLastToken())) { resultNode = resultNode.WithAppendedTrailingTrivia(syntaxFacts.ElasticMarker); } } return resultNode; } private static bool IsWordOrNumber(this ISyntaxFacts syntaxFacts, SyntaxToken token) => syntaxFacts.IsWord(token) || syntaxFacts.IsNumericLiteral(token); public static bool SpansPreprocessorDirective(this ISyntaxFacts service, SyntaxNode node) => service.SpansPreprocessorDirective(SpecializedCollections.SingletonEnumerable(node)); public static bool SpansPreprocessorDirective(this ISyntaxFacts service, params SyntaxNode[] nodes) => service.SpansPreprocessorDirective(nodes); public static bool IsWhitespaceOrEndOfLineTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => syntaxFacts.IsWhitespaceTrivia(trivia) || syntaxFacts.IsEndOfLineTrivia(trivia); public static void GetPartsOfBinaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode left, out SyntaxNode right) => syntaxFacts.GetPartsOfBinaryExpression(node, out left, out _, out right); public static SyntaxNode GetPatternOfParenthesizedPattern(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfParenthesizedPattern(node, out _, out var pattern, out _); return pattern; } public static SyntaxNode GetExpressionOfParenthesizedExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfParenthesizedExpression(node, out _, out var expression, out _); return expression; } public static SyntaxToken GetOperatorTokenOfBinaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfBinaryExpression(node, out _, out var token, out _); return token; } public static bool IsAnonymousOrLocalFunction(this ISyntaxFacts syntaxFacts, SyntaxNode node) => syntaxFacts.IsAnonymousFunction(node) || syntaxFacts.IsLocalFunctionStatement(node); public static SyntaxNode? GetExpressionOfElementAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfElementAccessExpression(node, out var expression, out _); return expression; } public static SyntaxNode? GetArgumentListOfElementAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfElementAccessExpression(node, out _, out var argumentList); return argumentList; } public static SyntaxNode GetExpressionOfConditionalAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfConditionalAccessExpression(node, out var expression, out _); return expression; } public static SyntaxToken GetOperatorTokenOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { syntaxFacts.GetPartsOfMemberAccessExpression(node, out _, out var operatorToken, out _); return operatorToken; } public static void GetPartsOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode expression, out SyntaxNode name) => syntaxFacts.GetPartsOfMemberAccessExpression(node, out expression, out _, out name); public static void GetPartsOfConditionalAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode expression, out SyntaxNode whenNotNull) => syntaxFacts.GetPartsOfConditionalAccessExpression(node, out expression, out _, out whenNotNull); public static TextSpan GetSpanWithoutAttributes(this ISyntaxFacts syntaxFacts, SyntaxNode root, SyntaxNode node) { // Span without AttributeLists // - No AttributeLists -> original .Span // - Some AttributeLists -> (first non-trivia/comment Token.Span.Begin, original.Span.End) // - We need to be mindful about comments due to: // // [Test1] // //Comment1 // [||]object Property1 { get; set; } // the comment node being part of the next token's (`object`) leading trivia and not the AttributeList's node. // - In case only attribute is written we need to be careful to not to use next (unrelated) token as beginning current the node. var attributeList = syntaxFacts.GetAttributeLists(node); if (attributeList.Any()) { var endOfAttributeLists = attributeList.Last().Span.End; var afterAttributesToken = root.FindTokenOnRightOfPosition(endOfAttributeLists); var endOfNode = node.Span.End; var startOfNodeWithoutAttributes = Math.Min(afterAttributesToken.Span.Start, endOfNode); return TextSpan.FromBounds(startOfNodeWithoutAttributes, endOfNode); } return node.Span; } /// <summary> /// Checks if the position is on the header of a type (from the start of the type up through it's name). /// </summary> public static bool IsOnTypeHeader(this ISyntaxFacts syntaxFacts, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) => syntaxFacts.IsOnTypeHeader(root, position, fullHeader: false, out typeDeclaration); /// <summary> /// Gets the statement container node for the statement <paramref name="node"/>. /// </summary> /// <param name="syntaxFacts">The <see cref="ISyntaxFacts"/> implementation.</param> /// <param name="node">The statement.</param> /// <returns>The statement container for <paramref name="node"/>.</returns> public static SyntaxNode? GetStatementContainer(this ISyntaxFacts syntaxFacts, SyntaxNode node) { for (var current = node; current is object; current = current.Parent) { if (syntaxFacts.IsStatementContainer(current.Parent)) { return current.Parent; } } return null; } /// <summary> /// Similar to <see cref="ISyntaxFacts.GetStandaloneExpression(SyntaxNode)"/>, this gets the containing /// expression that is actually a language expression and not just typed as an ExpressionSyntax for convenience. /// However, this goes beyond that that method in that if this expression is the RHS of a conditional access /// (i.e. <c>a?.b()</c>) it will also return the root of the conditional access expression tree. /// <para/> The intuition here is that this will give the topmost expression node that could realistically be /// replaced with any other expression. For example, with <c>a?.b()</c> technically <c>.b()</c> is an /// expression. But that cannot be replaced with something like <c>(1 + 1)</c> (as <c>a?.(1 + 1)</c> is not /// legal). However, in <c>a?.b()</c>, then <c>a</c> itself could be replaced with <c>(1 + 1)?.b()</c> to form /// a legal expression. /// </summary> public static SyntaxNode GetRootStandaloneExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node) { // First, make sure we're on a construct the language things is a standalone expression. var standalone = syntaxFacts.GetStandaloneExpression(node); // Then, if this is the RHS of a `?`, walk up to the top of that tree to get the final standalone expression. return syntaxFacts.GetRootConditionalAccessExpression(standalone) ?? standalone; } #region ISyntaxKinds forwarding methods #region trivia public static bool IsEndOfLineTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => trivia.RawKind == syntaxFacts.SyntaxKinds.EndOfLineTrivia; public static bool IsWhitespaceTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia) => trivia.RawKind == syntaxFacts.SyntaxKinds.WhitespaceTrivia; public static bool IsSkippedTokensTrivia(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.SkippedTokensTrivia; #endregion #region keywords public static bool IsAwaitKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.AwaitKeyword; public static bool IsGlobalNamespaceKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.GlobalKeyword; #endregion #region literal tokens public static bool IsCharacterLiteral(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.CharacterLiteralToken; public static bool IsStringLiteral(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.StringLiteralToken; #endregion #region tokens public static bool IsIdentifier(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.IdentifierToken; public static bool IsHashToken(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.HashToken; public static bool IsInterpolatedStringTextToken(this ISyntaxFacts syntaxFacts, SyntaxToken token) => token.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringTextToken; #endregion #region names public static bool IsGenericName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.GenericName; public static bool IsIdentifierName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.IdentifierName; public static bool IsQualifiedName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.QualifiedName; #endregion #region types public static bool IsTupleType(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TupleType; #endregion #region literal expressions public static bool IsCharacterLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.CharacterLiteralExpression; public static bool IsDefaultLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.DefaultLiteralExpression; public static bool IsFalseLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.FalseLiteralExpression; public static bool IsNullLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.NullLiteralExpression; public static bool IsStringLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.StringLiteralExpression; public static bool IsTrueLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TrueLiteralExpression; #endregion #region expressions public static bool IsAwaitExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.AwaitExpression; public static bool IsImplicitObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => syntaxFacts.IsImplicitObjectCreation(node); public static bool IsBaseExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.BaseExpression; public static bool IsConditionalAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ConditionalAccessExpression; public static bool IsInterpolatedStringExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringExpression; public static bool IsInterpolation(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.Interpolation; public static bool IsInterpolatedStringText(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringText; public static bool IsInvocationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.InvocationExpression; public static bool IsLogicalAndExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LogicalAndExpression; public static bool IsLogicalOrExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LogicalOrExpression; public static bool IsLogicalNotExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LogicalNotExpression; public static bool IsObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ObjectCreationExpression; public static bool IsParenthesizedExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ParenthesizedExpression; public static bool IsQueryExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.QueryExpression; public static bool IsSimpleMemberAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.SimpleMemberAccessExpression; public static bool IsThisExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ThisExpression; public static bool IsTupleExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TupleExpression; public static bool ContainsGlobalStatement(this ISyntaxFacts syntaxFacts, SyntaxNode node) => node.ChildNodes().Any(c => c.RawKind == syntaxFacts.SyntaxKinds.GlobalStatement); #endregion #region statements public static bool IsExpressionStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ExpressionStatement; public static bool IsForEachStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.ForEachStatement; public static bool IsLocalDeclarationStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LocalDeclarationStatement; public static bool IsLockStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.LockStatement; public static bool IsReturnStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode node) => node?.RawKind == syntaxFacts.SyntaxKinds.ReturnStatement; public static bool IsUsingStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.UsingStatement; #endregion #region members/declarations public static bool IsAttribute(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.Attribute; public static bool IsGlobalAttribute(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => syntaxFacts.IsGlobalAssemblyAttribute(node) || syntaxFacts.IsGlobalModuleAttribute(node); public static bool IsParameter(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.Parameter; public static bool IsTypeConstraint(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TypeConstraint; public static bool IsVariableDeclarator(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.VariableDeclarator; public static bool IsFieldDeclaration(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.FieldDeclaration; public static bool IsTypeArgumentList(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.TypeArgumentList; #endregion #region clauses public static bool IsEqualsValueClause(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node) => node?.RawKind == syntaxFacts.SyntaxKinds.EqualsValueClause; #endregion #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/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/IReadOnlyListExtensions.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; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Utilities { internal static class IReadOnlyListExtensions { public static IReadOnlyList<T> ToReadOnlyList<T>(this IList<T> list) { if (list is IReadOnlyList<T> readOnlyList) { return readOnlyList; } return new ReadOnlyList<T>(list); } public static T Last<T>(this IReadOnlyList<T> list) => list[list.Count - 1]; public static int IndexOf<T>(this IReadOnlyList<T> list, T value, int startIndex = 0) { for (var index = startIndex; index < list.Count; index++) { if (EqualityComparer<T>.Default.Equals(list[index], value)) { return index; } } return -1; } private class ReadOnlyList<T> : IReadOnlyList<T> { private readonly IList<T> _list; public ReadOnlyList(IList<T> list) => _list = list; public T this[int index] => _list[index]; public int Count => _list.Count; public IEnumerator<T> GetEnumerator() => _list.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator(); } } }
// 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; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Utilities { internal static class IReadOnlyListExtensions { public static IReadOnlyList<T> ToReadOnlyList<T>(this IList<T> list) { if (list is IReadOnlyList<T> readOnlyList) { return readOnlyList; } return new ReadOnlyList<T>(list); } public static T Last<T>(this IReadOnlyList<T> list) => list[list.Count - 1]; public static int IndexOf<T>(this IReadOnlyList<T> list, T value, int startIndex = 0) { for (var index = startIndex; index < list.Count; index++) { if (EqualityComparer<T>.Default.Equals(list[index], value)) { return index; } } return -1; } private class ReadOnlyList<T> : IReadOnlyList<T> { private readonly IList<T> _list; public ReadOnlyList(IList<T> list) => _list = list; public T this[int index] => _list[index]; public int Count => _list.Count; public IEnumerator<T> GetEnumerator() => _list.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator(); } } }
-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/MSBuildTest/Resources/SourceFiles/VisualBasic/Resources.resx_
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> </root>
<?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> </root>
-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/ULongKeywordRecommenderTests.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.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ULongKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(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 TestAfterStackAlloc() { await VerifyKeywordAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInMemberContext() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInMemberContext() { await VerifyKeywordAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInMemberContext() { await VerifyKeywordAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEnumBaseTypes() { await VerifyKeywordAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Goo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInImplicitOperator() { await VerifyKeywordAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExplicitOperator() { await VerifyKeywordAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContext() { await VerifyKeywordAsync(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContextNotAfterDot() { await VerifyAbsenceAsync(@" /// <see cref=""System.$$"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCrefTypeParameter() { await VerifyAbsenceAsync(@" using System; /// <see cref=""List{$$}"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task Preselection() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { Helper($$) } static void Helper(ulong x) { } } "); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinType() { await VerifyKeywordAsync(@" class Program { ($$ }"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinMember() { await VerifyKeywordAsync(@" class Program { void Method() { ($$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerType() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))] public async Task TestAfterKeywordIndicatingLocalFunction(string keyword) { await VerifyKeywordAsync(AddInsideMethod($@" {keyword} $$")); } } }
// 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.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ULongKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(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 TestAfterStackAlloc() { await VerifyKeywordAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInMemberContext() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInMemberContext() { await VerifyKeywordAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInMemberContext() { await VerifyKeywordAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEnumBaseTypes() { await VerifyKeywordAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Goo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInImplicitOperator() { await VerifyKeywordAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExplicitOperator() { await VerifyKeywordAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContext() { await VerifyKeywordAsync(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContextNotAfterDot() { await VerifyAbsenceAsync(@" /// <see cref=""System.$$"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCrefTypeParameter() { await VerifyAbsenceAsync(@" using System; /// <see cref=""List{$$}"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task Preselection() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { Helper($$) } static void Helper(ulong x) { } } "); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinType() { await VerifyKeywordAsync(@" class Program { ($$ }"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinMember() { await VerifyKeywordAsync(@" class Program { void Method() { ($$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerType() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))] public async Task TestAfterKeywordIndicatingLocalFunction(string keyword) { await VerifyKeywordAsync(AddInsideMethod($@" {keyword} $$")); } } }
-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/xlf/FeaturesResources.pt-BR.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pt-BR" original="../FeaturesResources.resx"> <body> <trans-unit id="0_directive"> <source>#{0} directive</source> <target state="new">#{0} directive</target> <note /> </trans-unit> <trans-unit id="AM_PM_abbreviated"> <source>AM/PM (abbreviated)</source> <target state="translated">AM/PM (abreviado)</target> <note /> </trans-unit> <trans-unit id="AM_PM_abbreviated_description"> <source>The "t" custom format specifier represents the first character of the AM/PM designator. The appropriate localized designator is retrieved from the DateTimeFormatInfo.AMDesignator or DateTimeFormatInfo.PMDesignator property of the current or specific culture. The AM designator is used for all times from 0:00:00 (midnight) to 11:59:59.999. The PM designator is used for all times from 12:00:00 (noon) to 23:59:59.999. If the "t" format specifier is used without other custom format specifiers, it's interpreted as the "t" standard date and time format specifier.</source> <target state="translated">O especificador de formato personalizado "t" representa o primeiro caractere do designador AM/PM. O designador localizado apropriado é recuperado da propriedade DateTimeFormatInfo.AMDesignator ou DateTimeFormatInfo.PMDesignator da cultura atual ou específica. O designador AM é usado para todos os horários de 0:00:00 (meia-noite) até 11:59:59.999. O designador PM é usado para todos os horários de 12:00:00 (meio-dia) para 23:59:59.999. Se o especificador de formato "t" for usado sem outros especificadores de formato personalizado, ele será interpretado como o especificador de formato padrão de data e hora "t".</target> <note /> </trans-unit> <trans-unit id="AM_PM_full"> <source>AM/PM (full)</source> <target state="translated">AM/PM (completo)</target> <note /> </trans-unit> <trans-unit id="AM_PM_full_description"> <source>The "tt" custom format specifier (plus any number of additional "t" specifiers) represents the entire AM/PM designator. The appropriate localized designator is retrieved from the DateTimeFormatInfo.AMDesignator or DateTimeFormatInfo.PMDesignator property of the current or specific culture. The AM designator is used for all times from 0:00:00 (midnight) to 11:59:59.999. The PM designator is used for all times from 12:00:00 (noon) to 23:59:59.999. Make sure to use the "tt" specifier for languages for which it's necessary to maintain the distinction between AM and PM. An example is Japanese, for which the AM and PM designators differ in the second character instead of the first character.</source> <target state="translated">O especificador de formato personalizado "tt" (mais qualquer número de especificadores "t" adicionais) representa todo o designador AM/PM. O designador localizado apropriado é recuperado da propriedade DateTimeFormatInfo.AMDesignator ou DateTimeFormatInfo.PMDesignator da cultura atual ou específica. O designador AM é usado para todos os horários de 0:00:00 (meia-noite) até 11:59:59.999. O designador PM é usado para todos os horários de 12:00:00 (meio-dia) até 23:59:59.999. Verifique se o especificador "tt" foi usado para idiomas para os quais é necessário manter a distinção entre AM e PM. Um exemplo é o japonês, para o qual os designadores AM e PM diferem no segundo caractere, em vez de no primeiro caractere.</target> <note /> </trans-unit> <trans-unit id="A_subtraction_must_be_the_last_element_in_a_character_class"> <source>A subtraction must be the last element in a character class</source> <target state="translated">Uma subtração deve ser o último elemento em uma classe de caracteres</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: [a-[b]-c]</note> </trans-unit> <trans-unit id="Accessing_captured_variable_0_that_hasn_t_been_accessed_before_in_1_requires_restarting_the_application"> <source>Accessing captured variable '{0}' that hasn't been accessed before in {1} requires restarting the application.</source> <target state="new">Accessing captured variable '{0}' that hasn't been accessed before in {1} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Add_DebuggerDisplay_attribute"> <source>Add 'DebuggerDisplay' attribute</source> <target state="translated">Adicionar atributo 'DebuggerDisplay'</target> <note>{Locked="DebuggerDisplay"} "DebuggerDisplay" is a BCL class and should not be localized.</note> </trans-unit> <trans-unit id="Add_explicit_cast"> <source>Add explicit cast</source> <target state="translated">Adicionar conversão explícita</target> <note /> </trans-unit> <trans-unit id="Add_member_name"> <source>Add member name</source> <target state="translated">Adicionar o nome do membro</target> <note /> </trans-unit> <trans-unit id="Add_null_checks_for_all_parameters"> <source>Add null checks for all parameters</source> <target state="translated">Adicionar verificações nulas para todos os parâmetros</target> <note /> </trans-unit> <trans-unit id="Add_optional_parameter_to_constructor"> <source>Add optional parameter to constructor</source> <target state="translated">Adicionar parâmetro opcional ao construtor</target> <note /> </trans-unit> <trans-unit id="Add_parameter_to_0_and_overrides_implementations"> <source>Add parameter to '{0}' (and overrides/implementations)</source> <target state="translated">Adicionar parâmetro ao '{0}' (e substituições/implementações)</target> <note /> </trans-unit> <trans-unit id="Add_parameter_to_constructor"> <source>Add parameter to constructor</source> <target state="translated">Adicionar parâmetro ao construtor</target> <note /> </trans-unit> <trans-unit id="Add_project_reference_to_0"> <source>Add project reference to '{0}'.</source> <target state="translated">Adicione referência de projeto a "{0}".</target> <note /> </trans-unit> <trans-unit id="Add_reference_to_0"> <source>Add reference to '{0}'.</source> <target state="translated">Adicione referência a "{0}".</target> <note /> </trans-unit> <trans-unit id="Actions_can_not_be_empty"> <source>Actions can not be empty.</source> <target state="translated">Ações não podem ficar vazias.</target> <note /> </trans-unit> <trans-unit id="Add_tuple_element_name_0"> <source>Add tuple element name '{0}'</source> <target state="translated">Adicionar o nome do elemento de tupla '{0}'</target> <note /> </trans-unit> <trans-unit id="Adding_0_around_an_active_statement_requires_restarting_the_application"> <source>Adding {0} around an active statement requires restarting the application.</source> <target state="new">Adding {0} around an active statement requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_into_a_1_requires_restarting_the_application"> <source>Adding {0} into a {1} requires restarting the application.</source> <target state="new">Adding {0} into a {1} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_into_a_class_with_explicit_or_sequential_layout_requires_restarting_the_application"> <source>Adding {0} into a class with explicit or sequential layout requires restarting the application.</source> <target state="new">Adding {0} into a class with explicit or sequential layout requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_into_a_generic_type_requires_restarting_the_application"> <source>Adding {0} into a generic type requires restarting the application.</source> <target state="new">Adding {0} into a generic type requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_into_an_interface_method_requires_restarting_the_application"> <source>Adding {0} into an interface method requires restarting the application.</source> <target state="new">Adding {0} into an interface method requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_into_an_interface_requires_restarting_the_application"> <source>Adding {0} into an interface requires restarting the application.</source> <target state="new">Adding {0} into an interface requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_requires_restarting_the_application"> <source>Adding {0} requires restarting the application.</source> <target state="new">Adding {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_that_accesses_captured_variables_1_and_2_declared_in_different_scopes_requires_restarting_the_application"> <source>Adding {0} that accesses captured variables '{1}' and '{2}' declared in different scopes requires restarting the application.</source> <target state="new">Adding {0} that accesses captured variables '{1}' and '{2}' declared in different scopes requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_with_the_Handles_clause_requires_restarting_the_application"> <source>Adding {0} with the Handles clause requires restarting the application.</source> <target state="new">Adding {0} with the Handles clause requires restarting the application.</target> <note>{Locked="Handles"} "Handles" is VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Adding_a_MustOverride_0_or_overriding_an_inherited_0_requires_restarting_the_application"> <source>Adding a MustOverride {0} or overriding an inherited {0} requires restarting the application.</source> <target state="new">Adding a MustOverride {0} or overriding an inherited {0} requires restarting the application.</target> <note>{Locked="MustOverride"} "MustOverride" is VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Adding_a_constructor_to_a_type_with_a_field_or_property_initializer_that_contains_an_anonymous_function_requires_restarting_the_application"> <source>Adding a constructor to a type with a field or property initializer that contains an anonymous function requires restarting the application.</source> <target state="new">Adding a constructor to a type with a field or property initializer that contains an anonymous function requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_a_generic_0_requires_restarting_the_application"> <source>Adding a generic {0} requires restarting the application.</source> <target state="new">Adding a generic {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_a_method_with_an_explicit_interface_specifier_requires_restarting_the_application"> <source>Adding a method with an explicit interface specifier requires restarting the application.</source> <target state="new">Adding a method with an explicit interface specifier requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_a_new_file_requires_restarting_the_application"> <source>Adding a new file requires restarting the application.</source> <target state="new">Adding a new file requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_a_user_defined_0_requires_restarting_the_application"> <source>Adding a user defined {0} requires restarting the application.</source> <target state="new">Adding a user defined {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application"> <source>Adding an abstract {0} or overriding an inherited {0} requires restarting the application.</source> <target state="new">Adding an abstract {0} or overriding an inherited {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_an_extern_0_requires_restarting_the_application"> <source>Adding an extern {0} requires restarting the application.</source> <target state="new">Adding an extern {0} requires restarting the application.</target> <note>{Locked="extern"} "extern" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Adding_an_imported_method_requires_restarting_the_application"> <source>Adding an imported method requires restarting the application.</source> <target state="new">Adding an imported method requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Align_wrapped_arguments"> <source>Align wrapped arguments</source> <target state="translated">Alinhar argumentos encapsulados</target> <note /> </trans-unit> <trans-unit id="Align_wrapped_parameters"> <source>Align wrapped parameters</source> <target state="translated">Alinhar os parâmetros encapsulados</target> <note /> </trans-unit> <trans-unit id="Alternation_conditions_cannot_be_comments"> <source>Alternation conditions cannot be comments</source> <target state="translated">Condições de alternância não podem ser comentários</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: a|(?#b)</note> </trans-unit> <trans-unit id="Alternation_conditions_do_not_capture_and_cannot_be_named"> <source>Alternation conditions do not capture and cannot be named</source> <target state="translated">Condições de alternância não capturam e não podem ser nomeadas</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?(?'x'))</note> </trans-unit> <trans-unit id="An_update_that_causes_the_return_type_of_implicit_main_to_change_requires_restarting_the_application"> <source>An update that causes the return type of the implicit Main method to change requires restarting the application.</source> <target state="new">An update that causes the return type of the implicit Main method to change requires restarting the application.</target> <note>{Locked="Main"} is C# keywords and should not be localized.</note> </trans-unit> <trans-unit id="Apply_file_header_preferences"> <source>Apply file header preferences</source> <target state="translated">Aplicar as preferências de cabeçalho de arquivo</target> <note /> </trans-unit> <trans-unit id="Apply_object_collection_initialization_preferences"> <source>Apply object/collection initialization preferences</source> <target state="translated">Aplicar as preferências de inicialização de objeto/coleção</target> <note /> </trans-unit> <trans-unit id="Attribute_0_is_missing_Updating_an_async_method_or_an_iterator_requires_restarting_the_application"> <source>Attribute '{0}' is missing. Updating an async method or an iterator requires restarting the application.</source> <target state="new">Attribute '{0}' is missing. Updating an async method or an iterator requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Asynchronously_waits_for_the_task_to_finish"> <source>Asynchronously waits for the task to finish.</source> <target state="new">Asynchronously waits for the task to finish.</target> <note /> </trans-unit> <trans-unit id="Awaited_task_returns_0"> <source>Awaited task returns '{0}'</source> <target state="translated">A tarefa esperada retorna '{0}'</target> <note /> </trans-unit> <trans-unit id="Awaited_task_returns_no_value"> <source>Awaited task returns no value</source> <target state="translated">A tarefa esperada não retorna nenhum valor</target> <note /> </trans-unit> <trans-unit id="Base_classes_contain_inaccessible_unimplemented_members"> <source>Base classes contain inaccessible unimplemented members</source> <target state="translated">As classes base contêm membros não implementados inacessíveis</target> <note /> </trans-unit> <trans-unit id="CannotApplyChangesUnexpectedError"> <source>Cannot apply changes -- unexpected error: '{0}'</source> <target state="translated">Não é possível aplicar as alterações – erro inesperado: '{0}'</target> <note /> </trans-unit> <trans-unit id="Cannot_include_class_0_in_character_range"> <source>Cannot include class \{0} in character range</source> <target state="translated">Não é possível incluir a classe \{0} no intervalo de caracteres</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: [a-\w]. {0} is the invalid class (\w here)</note> </trans-unit> <trans-unit id="Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue"> <source>Capture group numbers must be less than or equal to Int32.MaxValue</source> <target state="translated">Os números do grupo de captura devem ser menores ou iguais a Int32.MaxValue</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: a{2147483648}</note> </trans-unit> <trans-unit id="Capture_number_cannot_be_zero"> <source>Capture number cannot be zero</source> <target state="translated">O número da captura não pode ser zero</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?&lt;0&gt;a)</note> </trans-unit> <trans-unit id="Capturing_variable_0_that_hasn_t_been_captured_before_requires_restarting_the_application"> <source>Capturing variable '{0}' that hasn't been captured before requires restarting the application.</source> <target state="new">Capturing variable '{0}' that hasn't been captured before requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Ceasing_to_access_captured_variable_0_in_1_requires_restarting_the_application"> <source>Ceasing to access captured variable '{0}' in {1} requires restarting the application.</source> <target state="new">Ceasing to access captured variable '{0}' in {1} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Ceasing_to_capture_variable_0_requires_restarting_the_application"> <source>Ceasing to capture variable '{0}' requires restarting the application.</source> <target state="new">Ceasing to capture variable '{0}' requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="ChangeSignature_NewParameterInferValue"> <source>&lt;infer&gt;</source> <target state="translated">&lt;inferir&gt;</target> <note /> </trans-unit> <trans-unit id="ChangeSignature_NewParameterIntroduceTODOVariable"> <source>TODO</source> <target state="new">TODO</target> <note>"TODO" is an indication that there is work still to be done.</note> </trans-unit> <trans-unit id="ChangeSignature_NewParameterOmitValue"> <source>&lt;omit&gt;</source> <target state="translated">&lt;omitir&gt;</target> <note /> </trans-unit> <trans-unit id="Change_namespace_to_0"> <source>Change namespace to '{0}'</source> <target state="translated">Alterar o namespace para '{0}'</target> <note /> </trans-unit> <trans-unit id="Change_to_global_namespace"> <source>Change to global namespace</source> <target state="translated">Alterar para o namespace global</target> <note /> </trans-unit> <trans-unit id="ChangesDisallowedWhileStoppedAtException"> <source>Changes are not allowed while stopped at exception</source> <target state="translated">Não são permitidas alterações durante uma interrupção em exceção</target> <note /> </trans-unit> <trans-unit id="ChangesNotAppliedWhileRunning"> <source>Changes made in project '{0}' will not be applied while the application is running</source> <target state="translated">As alterações feitas no projeto '{0}' não serão aplicadas enquanto o aplicativo estiver em execução</target> <note /> </trans-unit> <trans-unit id="ChangesRequiredSynthesizedType"> <source>One or more changes result in a new type being created by the compiler, which requires restarting the application because it is not supported by the runtime</source> <target state="new">One or more changes result in a new type being created by the compiler, which requires restarting the application because it is not supported by the runtime</target> <note /> </trans-unit> <trans-unit id="Changing_0_from_asynchronous_to_synchronous_requires_restarting_the_application"> <source>Changing {0} from asynchronous to synchronous requires restarting the application.</source> <target state="new">Changing {0} from asynchronous to synchronous requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_0_to_1_requires_restarting_the_application_because_it_changes_the_shape_of_the_state_machine"> <source>Changing '{0}' to '{1}' requires restarting the application because it changes the shape of the state machine.</source> <target state="new">Changing '{0}' to '{1}' requires restarting the application because it changes the shape of the state machine.</target> <note /> </trans-unit> <trans-unit id="Changing_a_field_to_an_event_or_vice_versa_requires_restarting_the_application"> <source>Changing a field to an event or vice versa requires restarting the application.</source> <target state="new">Changing a field to an event or vice versa requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_constraints_of_0_requires_restarting_the_application"> <source>Changing constraints of {0} requires restarting the application.</source> <target state="new">Changing constraints of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_parameter_types_of_0_requires_restarting_the_application"> <source>Changing parameter types of {0} requires restarting the application.</source> <target state="new">Changing parameter types of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_the_declaration_scope_of_a_captured_variable_0_requires_restarting_the_application"> <source>Changing the declaration scope of a captured variable '{0}' requires restarting the application.</source> <target state="new">Changing the declaration scope of a captured variable '{0}' requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_the_parameters_of_0_requires_restarting_the_application"> <source>Changing the parameters of {0} requires restarting the application.</source> <target state="new">Changing the parameters of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_the_return_type_of_0_requires_restarting_the_application"> <source>Changing the return type of {0} requires restarting the application.</source> <target state="new">Changing the return type of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_the_type_of_0_requires_restarting_the_application"> <source>Changing the type of {0} requires restarting the application.</source> <target state="new">Changing the type of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_the_type_of_a_captured_variable_0_previously_of_type_1_requires_restarting_the_application"> <source>Changing the type of a captured variable '{0}' previously of type '{1}' requires restarting the application.</source> <target state="new">Changing the type of a captured variable '{0}' previously of type '{1}' requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_type_parameters_of_0_requires_restarting_the_application"> <source>Changing type parameters of {0} requires restarting the application.</source> <target state="new">Changing type parameters of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_visibility_of_0_requires_restarting_the_application"> <source>Changing visibility of {0} requires restarting the application.</source> <target state="new">Changing visibility of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Configure_0_code_style"> <source>Configure {0} code style</source> <target state="translated">Configurar estilo de código de {0}</target> <note /> </trans-unit> <trans-unit id="Configure_0_severity"> <source>Configure {0} severity</source> <target state="translated">Configurar severidade de {0}</target> <note /> </trans-unit> <trans-unit id="Configure_severity_for_all_0_analyzers"> <source>Configure severity for all '{0}' analyzers</source> <target state="translated">Configurar gravidade para todos os analisadores '{0}'</target> <note /> </trans-unit> <trans-unit id="Configure_severity_for_all_analyzers"> <source>Configure severity for all analyzers</source> <target state="translated">Configurar gravidade para todos os analisadores</target> <note /> </trans-unit> <trans-unit id="Convert_to_linq"> <source>Convert to LINQ</source> <target state="translated">Converter para LINQ</target> <note /> </trans-unit> <trans-unit id="Add_to_0"> <source>Add to '{0}'</source> <target state="translated">Adicionar para '{0}'</target> <note /> </trans-unit> <trans-unit id="Convert_to_class"> <source>Convert to class</source> <target state="translated">Converter em classe</target> <note /> </trans-unit> <trans-unit id="Convert_to_linq_call_form"> <source>Convert to LINQ (call form)</source> <target state="translated">Converter para LINQ (formulário de chamada)</target> <note /> </trans-unit> <trans-unit id="Convert_to_record"> <source>Convert to record</source> <target state="translated">Converter em Registro</target> <note /> </trans-unit> <trans-unit id="Convert_to_record_struct"> <source>Convert to record struct</source> <target state="translated">Converter em registro de struct</target> <note /> </trans-unit> <trans-unit id="Convert_to_struct"> <source>Convert to struct</source> <target state="translated">Converter para struct</target> <note /> </trans-unit> <trans-unit id="Convert_type_to_0"> <source>Convert type to '{0}'</source> <target state="translated">Converter o tipo em '{0}'</target> <note /> </trans-unit> <trans-unit id="Create_and_assign_field_0"> <source>Create and assign field '{0}'</source> <target state="translated">Criar e atribuir o campo '{0}'</target> <note /> </trans-unit> <trans-unit id="Create_and_assign_property_0"> <source>Create and assign property '{0}'</source> <target state="translated">Criar e atribuir a propriedade '{0}'</target> <note /> </trans-unit> <trans-unit id="Create_and_assign_remaining_as_fields"> <source>Create and assign remaining as fields</source> <target state="translated">Criar e atribuir os restantes como campos</target> <note /> </trans-unit> <trans-unit id="Create_and_assign_remaining_as_properties"> <source>Create and assign remaining as properties</source> <target state="translated">Criar e atribuir os restantes como propriedades</target> <note /> </trans-unit> <trans-unit id="Deleting_0_around_an_active_statement_requires_restarting_the_application"> <source>Deleting {0} around an active statement requires restarting the application.</source> <target state="new">Deleting {0} around an active statement requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Deleting_0_requires_restarting_the_application"> <source>Deleting {0} requires restarting the application.</source> <target state="new">Deleting {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Deleting_captured_variable_0_requires_restarting_the_application"> <source>Deleting captured variable '{0}' requires restarting the application.</source> <target state="new">Deleting captured variable '{0}' requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Do_not_change_this_code_Put_cleanup_code_in_0_method"> <source>Do not change this code. Put cleanup code in '{0}' method</source> <target state="translated">Não altere este código. Coloque o código de limpeza no método '{0}'</target> <note /> </trans-unit> <trans-unit id="DocumentIsOutOfSyncWithDebuggee"> <source>The current content of source file '{0}' does not match the built source. Any changes made to this file while debugging won't be applied until its content matches the built source.</source> <target state="translated">O conteúdo atual do arquivo de origem '{0}' não corresponde à origem criada. Todas as alterações feitas neste arquivo durante a depuração não serão aplicadas até que o conteúdo corresponda à origem criada.</target> <note /> </trans-unit> <trans-unit id="Document_must_be_contained_in_the_workspace_that_created_this_service"> <source>Document must be contained in the workspace that created this service</source> <target state="translated">O Documento deve estar contido no workspace que criou este serviço</target> <note /> </trans-unit> <trans-unit id="EditAndContinue"> <source>Edit and Continue</source> <target state="translated">Editar e Continuar</target> <note /> </trans-unit> <trans-unit id="EditAndContinueDisallowedByModule"> <source>Edit and Continue disallowed by module</source> <target state="translated">Pelo módulo, não é permitido Editar e Continuar</target> <note /> </trans-unit> <trans-unit id="EditAndContinueDisallowedByProject"> <source>Changes made in project '{0}' require restarting the application: {1}</source> <target state="needs-review-translation">As alterações feitas no projeto '{0}' impedirão que a sessão de depuração continue: {1}</target> <note /> </trans-unit> <trans-unit id="Edit_and_continue_is_not_supported_by_the_runtime"> <source>Edit and continue is not supported by the runtime.</source> <target state="translated">Editar e continuar não é suportado pelo tempo de execução.</target> <note /> </trans-unit> <trans-unit id="ErrorReadingFile"> <source>Error while reading file '{0}': {1}</source> <target state="translated">Erro ao ler o arquivo '{0}': {1}</target> <note /> </trans-unit> <trans-unit id="Error_creating_instance_of_CodeFixProvider"> <source>Error creating instance of CodeFixProvider</source> <target state="translated">Erro ao criar a instância de CodeFixProvider</target> <note /> </trans-unit> <trans-unit id="Error_creating_instance_of_CodeFixProvider_0"> <source>Error creating instance of CodeFixProvider '{0}'</source> <target state="translated">Erro ao criar instância de CodeFixProvider '{0}'</target> <note /> </trans-unit> <trans-unit id="Example"> <source>Example:</source> <target state="translated">Exemplo:</target> <note>Singular form when we want to show an example, but only have one to show.</note> </trans-unit> <trans-unit id="Examples"> <source>Examples:</source> <target state="translated">Exemplos:</target> <note>Plural form when we have multiple examples to show.</note> </trans-unit> <trans-unit id="Explicitly_implemented_methods_of_records_must_have_parameter_names_that_match_the_compiler_generated_equivalent_0"> <source>Explicitly implemented methods of records must have parameter names that match the compiler generated equivalent '{0}'</source> <target state="translated">Métodos explicitamente implementados de registros devem ter nomes de parâmetro que correspondem ao compilador gerado '{0}' equivalente</target> <note /> </trans-unit> <trans-unit id="Extract_base_class"> <source>Extract base class...</source> <target state="translated">Extrair a classe base...</target> <note /> </trans-unit> <trans-unit id="Extract_interface"> <source>Extract interface...</source> <target state="translated">Extrair a interface...</target> <note /> </trans-unit> <trans-unit id="Extract_local_function"> <source>Extract local function</source> <target state="translated">Extrair a função local</target> <note /> </trans-unit> <trans-unit id="Extract_method"> <source>Extract method</source> <target state="translated">Extrair método</target> <note /> </trans-unit> <trans-unit id="Failed_to_analyze_data_flow_for_0"> <source>Failed to analyze data-flow for: {0}</source> <target state="translated">Falha ao analisar o fluxo de dados para: {0}</target> <note /> </trans-unit> <trans-unit id="Fix_formatting"> <source>Fix formatting</source> <target state="translated">Corrigir a formatação</target> <note /> </trans-unit> <trans-unit id="Fix_typo_0"> <source>Fix typo '{0}'</source> <target state="translated">Corrigir erro de digitação '{0}'</target> <note /> </trans-unit> <trans-unit id="Format_document"> <source>Format document</source> <target state="translated">Formatar o documento</target> <note /> </trans-unit> <trans-unit id="Formatting_document"> <source>Formatting document</source> <target state="translated">Formatando documento</target> <note /> </trans-unit> <trans-unit id="Generate_comparison_operators"> <source>Generate comparison operators</source> <target state="translated">Gerar operadores de comparação</target> <note /> </trans-unit> <trans-unit id="Generate_constructor_in_0_with_fields"> <source>Generate constructor in '{0}' (with fields)</source> <target state="translated">Gerar o construtor em '{0}' (com campos)</target> <note /> </trans-unit> <trans-unit id="Generate_constructor_in_0_with_properties"> <source>Generate constructor in '{0}' (with properties)</source> <target state="translated">Gerar o construtor em '{0}' (com propriedades)</target> <note /> </trans-unit> <trans-unit id="Generate_for_0"> <source>Generate for '{0}'</source> <target state="translated">Gerar para '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_parameter_0"> <source>Generate parameter '{0}'</source> <target state="translated">Gerar o parâmetro '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_parameter_0_and_overrides_implementations"> <source>Generate parameter '{0}' (and overrides/implementations)</source> <target state="translated">Gerar o parâmetro '{0}' (e as substituições/implementações)</target> <note /> </trans-unit> <trans-unit id="Illegal_backslash_at_end_of_pattern"> <source>Illegal \ at end of pattern</source> <target state="translated">\ ilegal no final do padrão</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \</note> </trans-unit> <trans-unit id="Illegal_x_y_with_x_less_than_y"> <source>Illegal {x,y} with x &gt; y</source> <target state="translated">{x,y} ilegal com x&gt; y</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: a{1,0}</note> </trans-unit> <trans-unit id="Implement_0_explicitly"> <source>Implement '{0}' explicitly</source> <target state="translated">Implementar '{0}' explicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_0_implicitly"> <source>Implement '{0}' implicitly</source> <target state="translated">Implementar '{0}' implicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_abstract_class"> <source>Implement abstract class</source> <target state="translated">Implementar classe abstrata</target> <note /> </trans-unit> <trans-unit id="Implement_all_interfaces_explicitly"> <source>Implement all interfaces explicitly</source> <target state="translated">Implementar todas as interfaces explicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_all_interfaces_implicitly"> <source>Implement all interfaces implicitly</source> <target state="translated">Implementar todas as interfaces implicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_all_members_explicitly"> <source>Implement all members explicitly</source> <target state="translated">Implementar todos os membros explicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_explicitly"> <source>Implement explicitly</source> <target state="translated">Implementar explicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_implicitly"> <source>Implement implicitly</source> <target state="translated">Implementar implicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_remaining_members_explicitly"> <source>Implement remaining members explicitly</source> <target state="translated">Implementar os membros restantes explicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_through_0"> <source>Implement through '{0}'</source> <target state="translated">Implementar por meio de '{0}'</target> <note /> </trans-unit> <trans-unit id="Implementing_a_record_positional_parameter_0_as_read_only_requires_restarting_the_application"> <source>Implementing a record positional parameter '{0}' as read only requires restarting the application,</source> <target state="new">Implementing a record positional parameter '{0}' as read only requires restarting the application,</target> <note /> </trans-unit> <trans-unit id="Implementing_a_record_positional_parameter_0_with_a_set_accessor_requires_restarting_the_application"> <source>Implementing a record positional parameter '{0}' with a set accessor requires restarting the application.</source> <target state="new">Implementing a record positional parameter '{0}' with a set accessor requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Incomplete_character_escape"> <source>Incomplete \p{X} character escape</source> <target state="translated">Escape de caractere incompleto \p{X}</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \p{ Cc }</note> </trans-unit> <trans-unit id="Indent_all_arguments"> <source>Indent all arguments</source> <target state="translated">Recuar todos os argumentos</target> <note /> </trans-unit> <trans-unit id="Indent_all_parameters"> <source>Indent all parameters</source> <target state="translated">Recuar todos os parâmetros</target> <note /> </trans-unit> <trans-unit id="Indent_wrapped_arguments"> <source>Indent wrapped arguments</source> <target state="translated">Recuar argumentos encapsulados</target> <note /> </trans-unit> <trans-unit id="Indent_wrapped_parameters"> <source>Indent wrapped parameters</source> <target state="translated">Recuar parâmetros encapsulados</target> <note /> </trans-unit> <trans-unit id="Inline_0"> <source>Inline '{0}'</source> <target state="translated">Embutir '{0}'</target> <note /> </trans-unit> <trans-unit id="Inline_and_keep_0"> <source>Inline and keep '{0}'</source> <target state="translated">Embutir e manter '{0}'</target> <note /> </trans-unit> <trans-unit id="Insufficient_hexadecimal_digits"> <source>Insufficient hexadecimal digits</source> <target state="translated">Dígitos hexadecimais insuficientes</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \x</note> </trans-unit> <trans-unit id="Introduce_constant"> <source>Introduce constant</source> <target state="translated">Introduzir a constante</target> <note /> </trans-unit> <trans-unit id="Introduce_field"> <source>Introduce field</source> <target state="translated">Introduzir campo</target> <note /> </trans-unit> <trans-unit id="Introduce_local"> <source>Introduce local</source> <target state="translated">Introduzir o local</target> <note /> </trans-unit> <trans-unit id="Introduce_parameter"> <source>Introduce parameter</source> <target state="new">Introduce parameter</target> <note /> </trans-unit> <trans-unit id="Introduce_parameter_for_0"> <source>Introduce parameter for '{0}'</source> <target state="new">Introduce parameter for '{0}'</target> <note /> </trans-unit> <trans-unit id="Introduce_parameter_for_all_occurrences_of_0"> <source>Introduce parameter for all occurrences of '{0}'</source> <target state="new">Introduce parameter for all occurrences of '{0}'</target> <note /> </trans-unit> <trans-unit id="Introduce_query_variable"> <source>Introduce query variable</source> <target state="translated">Introduzir a variável de consulta</target> <note /> </trans-unit> <trans-unit id="Invalid_group_name_Group_names_must_begin_with_a_word_character"> <source>Invalid group name: Group names must begin with a word character</source> <target state="translated">Nome de grupo inválido: nomes de grupos devem começar com um caractere de palavra</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?&lt;a &gt;a)</note> </trans-unit> <trans-unit id="Invalid_selection"> <source>Invalid selection.</source> <target state="new">Invalid selection.</target> <note /> </trans-unit> <trans-unit id="Make_class_abstract"> <source>Make class 'abstract'</source> <target state="translated">Tornar a classe 'abstract'</target> <note /> </trans-unit> <trans-unit id="Make_member_static"> <source>Make static</source> <target state="translated">Tornar estático</target> <note /> </trans-unit> <trans-unit id="Invert_conditional"> <source>Invert conditional</source> <target state="translated">Inverter condicional</target> <note /> </trans-unit> <trans-unit id="Making_a_method_an_iterator_requires_restarting_the_application"> <source>Making a method an iterator requires restarting the application.</source> <target state="new">Making a method an iterator requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Making_a_method_asynchronous_requires_restarting_the_application"> <source>Making a method asynchronous requires restarting the application.</source> <target state="new">Making a method asynchronous requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Malformed"> <source>malformed</source> <target state="translated">malformado</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?(0</note> </trans-unit> <trans-unit id="Malformed_character_escape"> <source>Malformed \p{X} character escape</source> <target state="translated">Escape de caractere malformado \p{X}</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \p {Cc}</note> </trans-unit> <trans-unit id="Malformed_named_back_reference"> <source>Malformed \k&lt;...&gt; named back reference</source> <target state="translated">Referência inversa \k&lt;...&gt; mal formada</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \k'</note> </trans-unit> <trans-unit id="Merge_with_nested_0_statement"> <source>Merge with nested '{0}' statement</source> <target state="translated">Mesclar com a instrução '{0}' aninhada</target> <note /> </trans-unit> <trans-unit id="Merge_with_next_0_statement"> <source>Merge with next '{0}' statement</source> <target state="translated">Mesclar com a próxima instrução '{0}'</target> <note /> </trans-unit> <trans-unit id="Merge_with_outer_0_statement"> <source>Merge with outer '{0}' statement</source> <target state="translated">Mesclar com a instrução '{0}' externa</target> <note /> </trans-unit> <trans-unit id="Merge_with_previous_0_statement"> <source>Merge with previous '{0}' statement</source> <target state="translated">Mesclar com a instrução '{0}' anterior</target> <note /> </trans-unit> <trans-unit id="MethodMustReturnStreamThatSupportsReadAndSeek"> <source>{0} must return a stream that supports read and seek operations.</source> <target state="translated">{0} precisa retornar um fluxo compatível com as operações de leitura e busca.</target> <note /> </trans-unit> <trans-unit id="Missing_control_character"> <source>Missing control character</source> <target state="translated">Caractere de controle ausente</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \c</note> </trans-unit> <trans-unit id="Modifying_0_which_contains_a_static_variable_requires_restarting_the_application"> <source>Modifying {0} which contains a static variable requires restarting the application.</source> <target state="new">Modifying {0} which contains a static variable requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_0_which_contains_an_Aggregate_Group_By_or_Join_query_clauses_requires_restarting_the_application"> <source>Modifying {0} which contains an Aggregate, Group By, or Join query clauses requires restarting the application.</source> <target state="new">Modifying {0} which contains an Aggregate, Group By, or Join query clauses requires restarting the application.</target> <note>{Locked="Aggregate"}{Locked="Group By"}{Locked="Join"} are VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Modifying_0_which_contains_the_stackalloc_operator_requires_restarting_the_application"> <source>Modifying {0} which contains the stackalloc operator requires restarting the application.</source> <target state="new">Modifying {0} which contains the stackalloc operator requires restarting the application.</target> <note>{Locked="stackalloc"} "stackalloc" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Modifying_a_catch_finally_handler_with_an_active_statement_in_the_try_block_requires_restarting_the_application"> <source>Modifying a catch/finally handler with an active statement in the try block requires restarting the application.</source> <target state="new">Modifying a catch/finally handler with an active statement in the try block requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_a_catch_handler_around_an_active_statement_requires_restarting_the_application"> <source>Modifying a catch handler around an active statement requires restarting the application.</source> <target state="new">Modifying a catch handler around an active statement requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_a_generic_method_requires_restarting_the_application"> <source>Modifying a generic method requires restarting the application.</source> <target state="new">Modifying a generic method requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_a_method_inside_the_context_of_a_generic_type_requires_restarting_the_application"> <source>Modifying a method inside the context of a generic type requires restarting the application.</source> <target state="new">Modifying a method inside the context of a generic type requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_a_try_catch_finally_statement_when_the_finally_block_is_active_requires_restarting_the_application"> <source>Modifying a try/catch/finally statement when the finally block is active requires restarting the application.</source> <target state="new">Modifying a try/catch/finally statement when the finally block is active requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_an_active_0_which_contains_On_Error_or_Resume_statements_requires_restarting_the_application"> <source>Modifying an active {0} which contains On Error or Resume statements requires restarting the application.</source> <target state="new">Modifying an active {0} which contains On Error or Resume statements requires restarting the application.</target> <note>{Locked="On Error"}{Locked="Resume"} is VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Modifying_body_of_0_requires_restarting_the_application_because_the_body_has_too_many_statements"> <source>Modifying the body of {0} requires restarting the application because the body has too many statements.</source> <target state="new">Modifying the body of {0} requires restarting the application because the body has too many statements.</target> <note /> </trans-unit> <trans-unit id="Modifying_body_of_0_requires_restarting_the_application_due_to_internal_error_1"> <source>Modifying the body of {0} requires restarting the application due to internal error: {1}</source> <target state="new">Modifying the body of {0} requires restarting the application due to internal error: {1}</target> <note>{1} is a multi-line exception message including a stacktrace. Place it at the end of the message and don't add any punctation after or around {1}</note> </trans-unit> <trans-unit id="Modifying_source_file_0_requires_restarting_the_application_because_the_file_is_too_big"> <source>Modifying source file '{0}' requires restarting the application because the file is too big.</source> <target state="new">Modifying source file '{0}' requires restarting the application because the file is too big.</target> <note /> </trans-unit> <trans-unit id="Modifying_source_file_0_requires_restarting_the_application_due_to_internal_error_1"> <source>Modifying source file '{0}' requires restarting the application due to internal error: {1}</source> <target state="new">Modifying source file '{0}' requires restarting the application due to internal error: {1}</target> <note>{2} is a multi-line exception message including a stacktrace. Place it at the end of the message and don't add any punctation after or around {1}</note> </trans-unit> <trans-unit id="Modifying_source_with_experimental_language_features_enabled_requires_restarting_the_application"> <source>Modifying source with experimental language features enabled requires restarting the application.</source> <target state="new">Modifying source with experimental language features enabled requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_the_initializer_of_0_in_a_generic_type_requires_restarting_the_application"> <source>Modifying the initializer of {0} in a generic type requires restarting the application.</source> <target state="new">Modifying the initializer of {0} in a generic type requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_whitespace_or_comments_in_0_inside_the_context_of_a_generic_type_requires_restarting_the_application"> <source>Modifying whitespace or comments in {0} inside the context of a generic type requires restarting the application.</source> <target state="new">Modifying whitespace or comments in {0} inside the context of a generic type requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_whitespace_or_comments_in_a_generic_0_requires_restarting_the_application"> <source>Modifying whitespace or comments in a generic {0} requires restarting the application.</source> <target state="new">Modifying whitespace or comments in a generic {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Move_contents_to_namespace"> <source>Move contents to namespace...</source> <target state="translated">Mover conteúdo para o namespace...</target> <note /> </trans-unit> <trans-unit id="Move_file_to_0"> <source>Move file to '{0}'</source> <target state="translated">Mover o arquivo para '{0}'</target> <note /> </trans-unit> <trans-unit id="Move_file_to_project_root_folder"> <source>Move file to project root folder</source> <target state="translated">Mover o arquivo para a pasta raiz do projeto</target> <note /> </trans-unit> <trans-unit id="Move_to_namespace"> <source>Move to namespace...</source> <target state="translated">Mover para o namespace...</target> <note /> </trans-unit> <trans-unit id="Moving_0_requires_restarting_the_application"> <source>Moving {0} requires restarting the application.</source> <target state="new">Moving {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Nested_quantifier_0"> <source>Nested quantifier {0}</source> <target state="translated">Quantificador aninhado {0}</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: a**. In this case {0} will be '*', the extra unnecessary quantifier.</note> </trans-unit> <trans-unit id="No_common_root_node_for_extraction"> <source>No common root node for extraction.</source> <target state="new">No common root node for extraction.</target> <note /> </trans-unit> <trans-unit id="No_valid_location_to_insert_method_call"> <source>No valid location to insert method call.</source> <target state="translated">Não há nenhum local válido para inserir a chamada de método.</target> <note /> </trans-unit> <trans-unit id="No_valid_selection_to_perform_extraction"> <source>No valid selection to perform extraction.</source> <target state="new">No valid selection to perform extraction.</target> <note /> </trans-unit> <trans-unit id="Not_enough_close_parens"> <source>Not enough )'s</source> <target state="translated">Não há )'s suficientes</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (a</note> </trans-unit> <trans-unit id="Operators"> <source>Operators</source> <target state="translated">Operadores</target> <note /> </trans-unit> <trans-unit id="Property_reference_cannot_be_updated"> <source>Property reference cannot be updated</source> <target state="translated">A referência de propriedade não pode ser atualizada</target> <note /> </trans-unit> <trans-unit id="Pull_0_up"> <source>Pull '{0}' up</source> <target state="translated">Efetuar pull de '{0}'</target> <note /> </trans-unit> <trans-unit id="Pull_0_up_to_1"> <source>Pull '{0}' up to '{1}'</source> <target state="translated">Efetue pull de '{0}' até '{1}'</target> <note /> </trans-unit> <trans-unit id="Pull_members_up_to_base_type"> <source>Pull members up to base type...</source> <target state="translated">Efetuar pull de membros até o tipo base...</target> <note /> </trans-unit> <trans-unit id="Pull_members_up_to_new_base_class"> <source>Pull member(s) up to new base class...</source> <target state="translated">Efetuar pull de membros até a nova classe base...</target> <note /> </trans-unit> <trans-unit id="Quantifier_x_y_following_nothing"> <source>Quantifier {x,y} following nothing</source> <target state="translated">Nada precede o quantificador {x,y}</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: *</note> </trans-unit> <trans-unit id="Reference_to_undefined_group"> <source>reference to undefined group</source> <target state="translated">referência a grupo indefinido</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?(1))</note> </trans-unit> <trans-unit id="Reference_to_undefined_group_name_0"> <source>Reference to undefined group name {0}</source> <target state="translated">Referência ao nome do grupo indefinido {0}</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \k&lt;a&gt;. Here, {0} will be the name of the undefined group ('a')</note> </trans-unit> <trans-unit id="Reference_to_undefined_group_number_0"> <source>Reference to undefined group number {0}</source> <target state="translated">Referência ao grupo número {0} indefinido</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?&lt;-1&gt;). Here, {0} will be the number of the undefined group ('1')</note> </trans-unit> <trans-unit id="Regex_all_control_characters_long"> <source>All control characters. This includes the Cc, Cf, Cs, Co, and Cn categories.</source> <target state="translated">Todos os caracteres de controle. Isso inclui as categorias Cc, Cf, Cs, Co e Cn.</target> <note /> </trans-unit> <trans-unit id="Regex_all_control_characters_short"> <source>all control characters</source> <target state="translated">todos os caracteres de controle</target> <note /> </trans-unit> <trans-unit id="Regex_all_diacritic_marks_long"> <source>All diacritic marks. This includes the Mn, Mc, and Me categories.</source> <target state="translated">Todas as marcas diacríticas. Isso inclui as categorias Mn, Mc e Me.</target> <note /> </trans-unit> <trans-unit id="Regex_all_diacritic_marks_short"> <source>all diacritic marks</source> <target state="translated">todas as marcas diacríticas</target> <note /> </trans-unit> <trans-unit id="Regex_all_letter_characters_long"> <source>All letter characters. This includes the Lu, Ll, Lt, Lm, and Lo characters.</source> <target state="translated">Todos os caracteres de letra. Isso inclui os caracteres Lu, Ll, Lt, Lm e Lo.</target> <note /> </trans-unit> <trans-unit id="Regex_all_letter_characters_short"> <source>all letter characters</source> <target state="translated">todos os caracteres de letra</target> <note /> </trans-unit> <trans-unit id="Regex_all_numbers_long"> <source>All numbers. This includes the Nd, Nl, and No categories.</source> <target state="translated">Todos os números. Isso inclui as categorias Nd, Nl e No.</target> <note /> </trans-unit> <trans-unit id="Regex_all_numbers_short"> <source>all numbers</source> <target state="translated">todos os números</target> <note /> </trans-unit> <trans-unit id="Regex_all_punctuation_characters_long"> <source>All punctuation characters. This includes the Pc, Pd, Ps, Pe, Pi, Pf, and Po categories.</source> <target state="translated">Todos os caracteres de pontuação. Isso inclui as categorias Pc, Pd, Ps, Pe, Pi, Pf e Po.</target> <note /> </trans-unit> <trans-unit id="Regex_all_punctuation_characters_short"> <source>all punctuation characters</source> <target state="translated">todos os caracteres de pontuação</target> <note /> </trans-unit> <trans-unit id="Regex_all_separator_characters_long"> <source>All separator characters. This includes the Zs, Zl, and Zp categories.</source> <target state="translated">Todos os caracteres separadores. Isso inclui as categorias Zs, Zl e Zp.</target> <note /> </trans-unit> <trans-unit id="Regex_all_separator_characters_short"> <source>all separator characters</source> <target state="translated">todos os caracteres separadores</target> <note /> </trans-unit> <trans-unit id="Regex_all_symbols_long"> <source>All symbols. This includes the Sm, Sc, Sk, and So categories.</source> <target state="translated">Todos os símbolos. Isso inclui as categorias Sm, Sc, Sk e So.</target> <note /> </trans-unit> <trans-unit id="Regex_all_symbols_short"> <source>all symbols</source> <target state="translated">todos os símbolos</target> <note /> </trans-unit> <trans-unit id="Regex_alternation_long"> <source>You can use the vertical bar (|) character to match any one of a series of patterns, where the | character separates each pattern.</source> <target state="translated">Você pode usar o caractere de barra vertical (|) para corresponder a qualquer uma das séries de padrões, em que o caractere | separa cada padrão.</target> <note /> </trans-unit> <trans-unit id="Regex_alternation_short"> <source>alternation</source> <target state="translated">alternação</target> <note /> </trans-unit> <trans-unit id="Regex_any_character_group_long"> <source>The period character (.) matches any character except \n (the newline character, \u000A). If a regular expression pattern is modified by the RegexOptions.Singleline option, or if the portion of the pattern that contains the . character class is modified by the 's' option, . matches any character.</source> <target state="translated">O caractere de ponto (.) corresponde a qualquer caractere, exceto \n (o caractere de nova linha, \u000A). Se um padrão de expressão regular for modificado pela opção RegexOptions.Singleline ou se a parte do padrão que contém a classe de caractere . for modificada pela opção 's', . corresponderá a qualquer caractere.</target> <note /> </trans-unit> <trans-unit id="Regex_any_character_group_short"> <source>any character</source> <target state="translated">qualquer caractere</target> <note /> </trans-unit> <trans-unit id="Regex_atomic_group_long"> <source>Atomic groups (known in some other regular expression engines as a nonbacktracking subexpression, an atomic subexpression, or a once-only subexpression) disable backtracking. The regular expression engine will match as many characters in the input string as it can. When no further match is possible, it will not backtrack to attempt alternate pattern matches. (That is, the subexpression matches only strings that would be matched by the subexpression alone; it does not attempt to match a string based on the subexpression and any subexpressions that follow it.) This option is recommended if you know that backtracking will not succeed. Preventing the regular expression engine from performing unnecessary searching improves performance.</source> <target state="translated">Grupos atômicos (conhecidos em alguns outros mecanismos de expressão regulares como uma subexpressão sem rastreamento inverso, uma subexpressão atômica ou uma subexpressão de apenas uma vez) desabilita o rastreamento inverso. O mecanismo de expressão regular corresponderá o máximo possível de caracteres em uma cadeia de caracteres de entrada possível. Quando não for mais possível corresponder, ele não fará o rastreamento inverso para tentar alternar as correspondências de padrão. (Ou seja, a subexpressão corresponderá somente às cadeias de caracteres que seriam correspondidas pela subexpressão sozinha. Ela não tentará corresponder a uma cadeia de caracteres com base na subexpressão e nas subexpressões seguintes.) Essa opção é recomendada quando você sabe que o rastreamento inverso não será bem-sucedido. Impedir o mecanismo de expressão regular de executar pesquisas desnecessárias melhora o desempenho.</target> <note /> </trans-unit> <trans-unit id="Regex_atomic_group_short"> <source>atomic group</source> <target state="translated">grupo atômico</target> <note /> </trans-unit> <trans-unit id="Regex_backspace_character_long"> <source>Matches a backspace character, \u0008</source> <target state="translated">Corresponde a um caractere de backspace, \u0008</target> <note /> </trans-unit> <trans-unit id="Regex_backspace_character_short"> <source>backspace character</source> <target state="translated">caractere de backspace</target> <note /> </trans-unit> <trans-unit id="Regex_balancing_group_long"> <source>A balancing group definition deletes the definition of a previously defined group and stores, in the current group, the interval between the previously defined group and the current group. 'name1' is the current group (optional), 'name2' is a previously defined group, and 'subexpression' is any valid regular expression pattern. The balancing group definition deletes the definition of name2 and stores the interval between name2 and name1 in name1. If no name2 group is defined, the match backtracks. Because deleting the last definition of name2 reveals the previous definition of name2, this construct lets you use the stack of captures for group name2 as a counter for keeping track of nested constructs such as parentheses or opening and closing brackets. The balancing group definition uses 'name2' as a stack. The beginning character of each nested construct is placed in the group and in its Group.Captures collection. When the closing character is matched, its corresponding opening character is removed from the group, and the Captures collection is decreased by one. After the opening and closing characters of all nested constructs have been matched, 'name1' is empty.</source> <target state="translated">Uma definição de grupo de balanceamento exclui a definição de um grupo definido anteriormente e armazena, no grupo atual, o intervalo entre o grupo definido anteriormente e o grupo atual. 'name1' é o grupo atual (opcional), 'name2' é um grupo definido anteriormente e 'subexpression' é qualquer padrão de expressão regular válido. A definição de grupo de balanceamento exclui a definição de name2 e armazena o intervalo entre name2 e name1 no name1. Se não for definido nenhum name2, a correspondência retrocederá. Como a exclusão da última definição de name2 revela a definição anterior de name2, esse constructo permite o uso da pilha de capturas para o grupo name2 como um contador para manter o controle de constructos aninhados, como parênteses ou colchetes de abertura e fechamento. A definição de grupo de balanceamento usa 'name2' como uma pilha. O caractere inicial de cada constructo aninhado é colocado no grupo e em sua coleção Group.Captures. Quando o caractere de fechamento é correspondido, seu caractere de abertura correspondente é removido do grupo e a coleção Captures é reduzida em um. Após a correspondência dos caracteres de abertura e fechamento de todas as construções aninhadas, 'name1' ficará vazio.</target> <note /> </trans-unit> <trans-unit id="Regex_balancing_group_short"> <source>balancing group</source> <target state="translated">grupo de balanceamento</target> <note /> </trans-unit> <trans-unit id="Regex_base_group"> <source>base-group</source> <target state="translated">grupo base</target> <note /> </trans-unit> <trans-unit id="Regex_bell_character_long"> <source>Matches a bell (alarm) character, \u0007</source> <target state="translated">Corresponde a um caractere de sino (alarme), \u0007</target> <note /> </trans-unit> <trans-unit id="Regex_bell_character_short"> <source>bell character</source> <target state="translated">caractere de sino</target> <note /> </trans-unit> <trans-unit id="Regex_carriage_return_character_long"> <source>Matches a carriage-return character, \u000D. Note that \r is not equivalent to the newline character, \n.</source> <target state="translated">Corresponde a um caractere de retorno de carro, \u000D. Observe que \r não é equivalente ao caractere de nova linha, \n.</target> <note /> </trans-unit> <trans-unit id="Regex_carriage_return_character_short"> <source>carriage-return character</source> <target state="translated">caractere de retorno de carro</target> <note /> </trans-unit> <trans-unit id="Regex_character_class_subtraction_long"> <source>Character class subtraction yields a set of characters that is the result of excluding the characters in one character class from another character class. 'base_group' is a positive or negative character group or range. The 'excluded_group' component is another positive or negative character group, or another character class subtraction expression (that is, you can nest character class subtraction expressions).</source> <target state="translated">A subtração de classe de caracteres produz um conjunto de caracteres que é o resultado da exclusão de caracteres em uma classe de caracteres de outra classe de caracteres. 'base_group' é um grupo ou intervalo de caracteres positivos ou negativos. O componente 'excluded_group' é outro grupo de caracteres positivos ou negativos ou outra expressão de subtração de classe de caracteres (ou seja, você pode aninhar expressões de subtração de classes de caracteres).</target> <note /> </trans-unit> <trans-unit id="Regex_character_class_subtraction_short"> <source>character class subtraction</source> <target state="translated">subtração de classe de caracteres</target> <note /> </trans-unit> <trans-unit id="Regex_character_group"> <source>character-group</source> <target state="translated">grupo de caracteres</target> <note /> </trans-unit> <trans-unit id="Regex_comment"> <source>comment</source> <target state="translated">comentário</target> <note /> </trans-unit> <trans-unit id="Regex_conditional_expression_match_long"> <source>This language element attempts to match one of two patterns depending on whether it can match an initial pattern. 'expression' is the initial pattern to match, 'yes' is the pattern to match if expression is matched, and 'no' is the optional pattern to match if expression is not matched.</source> <target state="translated">Este elemento de linguagem tenta corresponder a um de dois padrões, dependendo da possibilidade de correspondência com um padrão inicial. 'expression' é o padrão inicial, 'yes' é o padrão quando a expressão é correspondida e 'no' é o padrão opcional quando a expressão não é correspondida.</target> <note /> </trans-unit> <trans-unit id="Regex_conditional_expression_match_short"> <source>conditional expression match</source> <target state="translated">correspondência de expressão condicional</target> <note /> </trans-unit> <trans-unit id="Regex_conditional_group_match_long"> <source>This language element attempts to match one of two patterns depending on whether it has matched a specified capturing group. 'name' is the name (or number) of a capturing group, 'yes' is the expression to match if 'name' (or 'number') has a match, and 'no' is the optional expression to match if it does not.</source> <target state="translated">Este elemento de linguagem tenta corresponder a um de dois padrões, dependendo da correspondência a um grupo de captura especificado. 'name' é o nome (ou número) de um grupo de captura, 'yes' é a expressão a ser correspondida quando 'name' (ou 'number') é correspondido e 'no' é a expressão opcional a ser correspondida caso contrário.</target> <note /> </trans-unit> <trans-unit id="Regex_conditional_group_match_short"> <source>conditional group match</source> <target state="translated">correspondência de grupo condicional</target> <note /> </trans-unit> <trans-unit id="Regex_contiguous_matches_long"> <source>The \G anchor specifies that a match must occur at the point where the previous match ended. When you use this anchor with the Regex.Matches or Match.NextMatch method, it ensures that all matches are contiguous.</source> <target state="translated">A âncora \G especifica que uma correspondência precisa ocorrer no ponto em que a correspondência anterior foi finalizada. Quando você usa essa âncora com o método Regex.Matchs ou Match.NextMatch, ela garante que todas as correspondências sejam contíguas.</target> <note /> </trans-unit> <trans-unit id="Regex_contiguous_matches_short"> <source>contiguous matches</source> <target state="translated">correspondências contíguas</target> <note /> </trans-unit> <trans-unit id="Regex_control_character_long"> <source>Matches an ASCII control character, where X is the letter of the control character. For example, \cC is CTRL-C.</source> <target state="translated">Corresponde a um caractere de controle ASCII, em que X é a letra do caractere de controle. Por exemplo, \cC é CTRL-C.</target> <note /> </trans-unit> <trans-unit id="Regex_control_character_short"> <source>control character</source> <target state="translated">caractere de controle</target> <note /> </trans-unit> <trans-unit id="Regex_decimal_digit_character_long"> <source>\d matches any decimal digit. It is equivalent to the \p{Nd} regular expression pattern, which includes the standard decimal digits 0-9 as well as the decimal digits of a number of other character sets. If ECMAScript-compliant behavior is specified, \d is equivalent to [0-9]</source> <target state="translated">\d corresponde a qualquer dígito decimal. Equivale ao padrão de expressão regular \p{Nd}, que inclui os dígitos decimais padrão 0 a 9, bem como os dígitos decimais de vários outros conjuntos de caracteres. Se o comportamento em conformidade com o ECMAScript for especificado, \d será equivalente a [0-9]</target> <note /> </trans-unit> <trans-unit id="Regex_decimal_digit_character_short"> <source>decimal-digit character</source> <target state="translated">caractere de dígito decimal</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_line_comment_long"> <source>A number sign (#) marks an x-mode comment, which starts at the unescaped # character at the end of the regular expression pattern and continues until the end of the line. To use this construct, you must either enable the x option (through inline options) or supply the RegexOptions.IgnorePatternWhitespace value to the option parameter when instantiating the Regex object or calling a static Regex method.</source> <target state="translated">Um sinal de número (#) marca um comentário de modo x, que começa no caractere # sem escape no final do padrão de expressão regular e continua até o fim da linha. Para usar esse constructo, habilite a opção x (por meio de opções embutidas) ou forneça o valor de RegexOptions.IgnorePatternWhitespace para o parâmetro de opção ao criar a instância do objeto Regex ou chamar um método Regex estático.</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_line_comment_short"> <source>end-of-line comment</source> <target state="translated">comentário de fim da linha</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_string_only_long"> <source>The \z anchor specifies that a match must occur at the end of the input string. Like the $ language element, \z ignores the RegexOptions.Multiline option. Unlike the \Z language element, \z does not match a \n character at the end of a string. Therefore, it can only match the last line of the input string.</source> <target state="translated">A âncora \z especifica que uma correspondência precisa ocorrer no final da cadeia de caracteres de entrada. Como o elemento de linguagem $, \z ignora a opção RegexOptions.Multiline. Ao contrário do elemento de linguagem \Z, \z não corresponde a um caractere \n no final de uma cadeia de caracteres. Portanto, ele só pode corresponder à última linha da cadeia de caracteres de entrada.</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_string_only_short"> <source>end of string only</source> <target state="translated">fim da cadeia de caracteres somente</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_string_or_before_ending_newline_long"> <source>The \Z anchor specifies that a match must occur at the end of the input string, or before \n at the end of the input string. It is identical to the $ anchor, except that \Z ignores the RegexOptions.Multiline option. Therefore, in a multiline string, it can only match the end of the last line, or the last line before \n. The \Z anchor matches \n but does not match \r\n (the CR/LF character combination). To match CR/LF, include \r?\Z in the regular expression pattern.</source> <target state="translated">A âncora \Z especifica que uma correspondência precisa ocorrer no final da cadeia de caracteres de entrada ou antes de \n no final da cadeia de caracteres de entrada. Ela é idêntica à âncora $, exceto que \Z ignora a opção RegexOptions.Multiline. Portanto, em uma cadeia de caracteres multilinha, ela pode corresponder somente ao final da última linha ou à última linha antes de \n. A âncora \Z corresponde a \n, mas não corresponde à \r\n (à combinação de caracteres CR/LF). Para corresponder a CR/LF, inclua \r?\Z no padrão de expressão regular.</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_string_or_before_ending_newline_short"> <source>end of string or before ending newline</source> <target state="translated">fim da cadeia de caracteres ou antes do fim da nova linha</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_string_or_line_long"> <source>The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions.Multiline option, the match can also occur at the end of a line. The $ anchor matches \n but does not match \r\n (the combination of carriage return and newline characters, or CR/LF). To match the CR/LF character combination, include \r?$ in the regular expression pattern.</source> <target state="translated">A âncora $ especifica que o padrão anterior precisa ocorrer no final da cadeia de caracteres de entrada ou antes de \n no final da cadeia de caracteres de entrada. Se você usar $ com a opção RegexOptions.Multiline, a correspondência também poderá ocorrer no final de uma linha. A âncora $ corresponde a \n, mas não corresponde a \r\n (a combinação dos caracteres de retorno de carro e de nova linha ou CR/LF). Para a âncora corresponder à combinação de caracteres CR/LF, inclua \r?$ no padrão de expressão regular.</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_string_or_line_short"> <source>end of string or line</source> <target state="translated">fim da cadeia de caracteres ou da linha</target> <note /> </trans-unit> <trans-unit id="Regex_escape_character_long"> <source>Matches an escape character, \u001B</source> <target state="translated">Corresponde a um caractere de escape, \u001B</target> <note /> </trans-unit> <trans-unit id="Regex_escape_character_short"> <source>escape character</source> <target state="translated">caractere de escape</target> <note /> </trans-unit> <trans-unit id="Regex_excluded_group"> <source>excluded-group</source> <target state="translated">grupo excluído</target> <note /> </trans-unit> <trans-unit id="Regex_expression"> <source>expression</source> <target state="translated">expressão</target> <note /> </trans-unit> <trans-unit id="Regex_form_feed_character_long"> <source>Matches a form-feed character, \u000C</source> <target state="translated">Corresponde ao caractere de avanço de página, \u000C</target> <note /> </trans-unit> <trans-unit id="Regex_form_feed_character_short"> <source>form-feed character</source> <target state="translated">caractere de avanço de página</target> <note /> </trans-unit> <trans-unit id="Regex_group_options_long"> <source>This grouping construct applies or disables the specified options within a subexpression. The options to enable are specified after the question mark, and the options to disable after the minus sign. The allowed options are: i Use case-insensitive matching. m Use multiline mode, where ^ and $ match the beginning and end of each line (instead of the beginning and end of the input string). s Use single-line mode, where the period (.) matches every character (instead of every character except \n). n Do not capture unnamed groups. The only valid captures are explicitly named or numbered groups of the form (?&lt;name&gt; subexpression). x Exclude unescaped white space from the pattern, and enable comments after a number sign (#).</source> <target state="translated">Este constructo de agrupamento aplica ou desabilita as opções especificadas dentro de uma subexpressão. As opções a serem habilitadas são especificadas após o ponto de interrogação e as opções a serem desabilitadas, após o sinal de menos. As opções permitidas são: i Usar a correspondência que não diferencia maiúsculas de minúsculas. m Usar o modo multilinha, em que ^ e $ correspondem ao início e ao fim de cada linha (em vez de ao início e ao fim da cadeia de caracteres de entrada). s Usar o modo de linha única, no qual o ponto (.) corresponde a cada caractere (em vez de a cada caractere exceto \n). n Não capturar os grupos sem nome. As únicas capturas válidas são os grupos nomeados ou numerados no formato (?&lt;name&gt; subexpressão). x Excluir o espaço em branco sem escape do padrão e habilitar os comentários após um sinal de número (#).</target> <note /> </trans-unit> <trans-unit id="Regex_group_options_short"> <source>group options</source> <target state="translated">opções de grupo</target> <note /> </trans-unit> <trans-unit id="Regex_hexadecimal_escape_long"> <source>Matches an ASCII character, where ## is a two-digit hexadecimal character code.</source> <target state="translated">Corresponde a um caractere ASCII, em que ## é um código de caractere hexadecimal de dois dígitos.</target> <note /> </trans-unit> <trans-unit id="Regex_hexadecimal_escape_short"> <source>hexadecimal escape</source> <target state="translated">escape hexadecimal</target> <note /> </trans-unit> <trans-unit id="Regex_inline_comment_long"> <source>The (?# comment) construct lets you include an inline comment in a regular expression. The regular expression engine does not use any part of the comment in pattern matching, although the comment is included in the string that is returned by the Regex.ToString method. The comment ends at the first closing parenthesis.</source> <target state="translated">O constructo (?# comentário) permite incluir um comentário embutido em uma expressão regular. O mecanismo de expressão regular não usa nenhuma parte do comentário na correspondência de padrões, embora o comentário seja incluído na cadeia de caracteres retornada pelo método Regex.ToString. O comentário termina no primeiro parêntese de fechamento.</target> <note /> </trans-unit> <trans-unit id="Regex_inline_comment_short"> <source>inline comment</source> <target state="translated">comentário embutido</target> <note /> </trans-unit> <trans-unit id="Regex_inline_options_long"> <source>Enables or disables specific pattern matching options for the remainder of a regular expression. The options to enable are specified after the question mark, and the options to disable after the minus sign. The allowed options are: i Use case-insensitive matching. m Use multiline mode, where ^ and $ match the beginning and end of each line (instead of the beginning and end of the input string). s Use single-line mode, where the period (.) matches every character (instead of every character except \n). n Do not capture unnamed groups. The only valid captures are explicitly named or numbered groups of the form (?&lt;name&gt; subexpression). x Exclude unescaped white space from the pattern, and enable comments after a number sign (#).</source> <target state="translated">Habilita ou desabilita as opções de correspondência de padrões específicas para o restante de uma expressão regular. As opções a serem habilitadas são especificadas após o ponto de interrogação e as opções a serem desabilitadas, após o sinal de menos. As opções permitidas são: i Usar a correspondência que não diferencia maiúsculas de minúsculas. m Usar o modo multilinha, no qual ^ e $ correspondem ao início e ao fim de cada linha (em vez do início e do fim da cadeia de caracteres de entrada). s Usar o modo de linha única, no qual o ponto (.) corresponde a cada caractere (em vez de cada caractere exceto \n). n Não capturar grupos sem nome. As únicas capturas válidas são os grupos nomeados ou numerados explicitamente do formato (?&lt;name&gt; subexpressão). x Excluir o espaço em branco sem escape do padrão e habilitar os comentários após um sinal de número (#).</target> <note /> </trans-unit> <trans-unit id="Regex_inline_options_short"> <source>inline options</source> <target state="translated">opções embutidas</target> <note /> </trans-unit> <trans-unit id="Regex_issue_0"> <source>Regex issue: {0}</source> <target state="translated">Problema do Regex: {0}</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. {0} will be the actual text of one of the above Regular Expression errors.</note> </trans-unit> <trans-unit id="Regex_letter_lowercase"> <source>letter, lowercase</source> <target state="translated">letra, minúscula</target> <note /> </trans-unit> <trans-unit id="Regex_letter_modifier"> <source>letter, modifier</source> <target state="translated">letra, modificador</target> <note /> </trans-unit> <trans-unit id="Regex_letter_other"> <source>letter, other</source> <target state="translated">letra, outro</target> <note /> </trans-unit> <trans-unit id="Regex_letter_titlecase"> <source>letter, titlecase</source> <target state="translated">letra, inicial maiúscula</target> <note /> </trans-unit> <trans-unit id="Regex_letter_uppercase"> <source>letter, uppercase</source> <target state="translated">letra, maiúscula</target> <note /> </trans-unit> <trans-unit id="Regex_mark_enclosing"> <source>mark, enclosing</source> <target state="translated">marca, delimitação</target> <note /> </trans-unit> <trans-unit id="Regex_mark_nonspacing"> <source>mark, nonspacing</source> <target state="translated">marca, não espaçamento</target> <note /> </trans-unit> <trans-unit id="Regex_mark_spacing_combining"> <source>mark, spacing combining</source> <target state="translated">marca, combinação de espaçamento</target> <note /> </trans-unit> <trans-unit id="Regex_match_at_least_n_times_lazy_long"> <source>The {n,}? quantifier matches the preceding element at least n times, where n is any integer, but as few times as possible. It is the lazy counterpart of the greedy quantifier {n,}</source> <target state="translated">O quantificador {n,}? corresponde ao elemento precedente pelo menos n vezes, em que n é qualquer inteiro, mas o menor número de vezes possível. Ele é a contraparte lenta do quantificador greedy {n,}</target> <note /> </trans-unit> <trans-unit id="Regex_match_at_least_n_times_lazy_short"> <source>match at least 'n' times (lazy)</source> <target state="translated">corresponder pelo menos 'n' vezes (lento)</target> <note /> </trans-unit> <trans-unit id="Regex_match_at_least_n_times_long"> <source>The {n,} quantifier matches the preceding element at least n times, where n is any integer. {n,} is a greedy quantifier whose lazy equivalent is {n,}?</source> <target state="translated">O quantificador {n,} corresponde ao elemento precedente pelo menos n vezes, em que n é qualquer número inteiro. {n,} é um quantificador greedy cujo equivalente lento é {n,}?</target> <note /> </trans-unit> <trans-unit id="Regex_match_at_least_n_times_short"> <source>match at least 'n' times</source> <target state="translated">corresponder a pelo menos 'n' vezes</target> <note /> </trans-unit> <trans-unit id="Regex_match_between_m_and_n_times_lazy_long"> <source>The {n,m}? quantifier matches the preceding element between n and m times, where n and m are integers, but as few times as possible. It is the lazy counterpart of the greedy quantifier {n,m}</source> <target state="translated">O quantificador {n,m}? corresponde ao elemento precedente entre n e m vezes, em que n e m são inteiros, mas o menor número de vezes possível. Ele é a contraparte lenta do quantificador greedy {n,m}</target> <note /> </trans-unit> <trans-unit id="Regex_match_between_m_and_n_times_lazy_short"> <source>match at least 'n' times (lazy)</source> <target state="translated">corresponder pelo menos 'n' vezes (lento)</target> <note /> </trans-unit> <trans-unit id="Regex_match_between_m_and_n_times_long"> <source>The {n,m} quantifier matches the preceding element at least n times, but no more than m times, where n and m are integers. {n,m} is a greedy quantifier whose lazy equivalent is {n,m}?</source> <target state="translated">O quantificador {n,m} corresponde ao elemento precedente pelo menos n vezes, mas no máximo m vezes, em que n e m são inteiros. {n,m} é um quantificador greedy cujo equivalente lento é {n,m}?</target> <note /> </trans-unit> <trans-unit id="Regex_match_between_m_and_n_times_short"> <source>match between 'm' and 'n' times</source> <target state="translated">corresponder entre 'm' e 'n' vezes</target> <note /> </trans-unit> <trans-unit id="Regex_match_exactly_n_times_lazy_long"> <source>The {n}? quantifier matches the preceding element exactly n times, where n is any integer. It is the lazy counterpart of the greedy quantifier {n}+</source> <target state="translated">O quantificador {n}? corresponde ao elemento precedente exatamente n vezes, em que n é qualquer inteiro. Ele é a contraparte lenta do quantificador greedy {n}+</target> <note /> </trans-unit> <trans-unit id="Regex_match_exactly_n_times_lazy_short"> <source>match exactly 'n' times (lazy)</source> <target state="translated">corresponder exatamente 'n' vezes (lento)</target> <note /> </trans-unit> <trans-unit id="Regex_match_exactly_n_times_long"> <source>The {n} quantifier matches the preceding element exactly n times, where n is any integer. {n} is a greedy quantifier whose lazy equivalent is {n}?</source> <target state="translated">O quantificador {n} corresponde ao elemento precedente exatamente n vezes, em que n é qualquer número inteiro. {n} é um quantificador greedy cujo equivalente lento é {n}?</target> <note /> </trans-unit> <trans-unit id="Regex_match_exactly_n_times_short"> <source>match exactly 'n' times</source> <target state="translated">corresponder exatamente 'n' vezes</target> <note /> </trans-unit> <trans-unit id="Regex_match_one_or_more_times_lazy_long"> <source>The +? quantifier matches the preceding element one or more times, but as few times as possible. It is the lazy counterpart of the greedy quantifier +</source> <target state="translated">O quantificador +? corresponde ao elemento precedente uma ou mais vezes, mas o menor número de vezes possível. Ele é a contraparte lenta do quantificador greedy +</target> <note /> </trans-unit> <trans-unit id="Regex_match_one_or_more_times_lazy_short"> <source>match one or more times (lazy)</source> <target state="translated">corresponder uma ou mais vezes (lento)</target> <note /> </trans-unit> <trans-unit id="Regex_match_one_or_more_times_long"> <source>The + quantifier matches the preceding element one or more times. It is equivalent to the {1,} quantifier. + is a greedy quantifier whose lazy equivalent is +?.</source> <target state="translated">O quantificador + corresponde ao elemento precedente uma ou mais vezes. Ele equivale ao quantificador {1,}. + é um quantificador greedy cujo equivalente lento é +?.</target> <note /> </trans-unit> <trans-unit id="Regex_match_one_or_more_times_short"> <source>match one or more times</source> <target state="translated">corresponder uma ou mais vezes</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_more_times_lazy_long"> <source>The *? quantifier matches the preceding element zero or more times, but as few times as possible. It is the lazy counterpart of the greedy quantifier *</source> <target state="translated">O quantificador *? corresponde ao elemento precedente zero ou mais vezes, mas o menor número de vezes possível. Ele é a contraparte lenta do quantificador greedy *</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_more_times_lazy_short"> <source>match zero or more times (lazy)</source> <target state="translated">corresponder zero ou mais vezes (lento)</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_more_times_long"> <source>The * quantifier matches the preceding element zero or more times. It is equivalent to the {0,} quantifier. * is a greedy quantifier whose lazy equivalent is *?.</source> <target state="translated">O quantificador * corresponde ao elemento precedente zero ou mais vezes. Ele equivale ao quantificador {0,}. * é um quantificador greedy cujo equivalente lento é *?.</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_more_times_short"> <source>match zero or more times</source> <target state="translated">corresponder zero ou mais vezes</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_one_time_lazy_long"> <source>The ?? quantifier matches the preceding element zero or one time, but as few times as possible. It is the lazy counterpart of the greedy quantifier ?</source> <target state="translated">O quantificador ?? corresponde ao elemento precedente zero ou uma vez, mas o menor número de vezes possível. Ele é a contraparte lenta do quantificador greedy ?</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_one_time_lazy_short"> <source>match zero or one time (lazy)</source> <target state="translated">corresponder nenhuma ou uma vez (lento)</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_one_time_long"> <source>The ? quantifier matches the preceding element zero or one time. It is equivalent to the {0,1} quantifier. ? is a greedy quantifier whose lazy equivalent is ??.</source> <target state="translated">O quantificador ? corresponde ao elemento precedente zero ou uma vez. Ele equivale ao quantificador {0,1}. ? é um quantificador greedy cujo equivalente lento é ??.</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_one_time_short"> <source>match zero or one time</source> <target state="translated">corresponder nenhuma ou uma vez</target> <note /> </trans-unit> <trans-unit id="Regex_matched_subexpression_long"> <source>This grouping construct captures a matched 'subexpression', where 'subexpression' is any valid regular expression pattern. Captures that use parentheses are numbered automatically from left to right based on the order of the opening parentheses in the regular expression, starting from one. The capture that is numbered zero is the text matched by the entire regular expression pattern.</source> <target state="translated">Este constructo de agrupamento captura uma 'subexpression' correspondente, em que 'subexpression' é qualquer padrão de expressão regular válido. As capturas que usam parênteses são numeradas automaticamente da esquerda para a direita com base na ordem dos parênteses de abertura na expressão regular, começando com um. A captura numerada como zero é o texto correspondente ao padrão de expressão regular inteiro.</target> <note /> </trans-unit> <trans-unit id="Regex_matched_subexpression_short"> <source>matched subexpression</source> <target state="translated">subexpressão correspondente</target> <note /> </trans-unit> <trans-unit id="Regex_name"> <source>name</source> <target state="translated">nome</target> <note /> </trans-unit> <trans-unit id="Regex_name1"> <source>name1</source> <target state="translated">name1</target> <note /> </trans-unit> <trans-unit id="Regex_name2"> <source>name2</source> <target state="translated">name2</target> <note /> </trans-unit> <trans-unit id="Regex_name_or_number"> <source>name-or-number</source> <target state="translated">nome ou número</target> <note /> </trans-unit> <trans-unit id="Regex_named_backreference_long"> <source>A named or numbered backreference. 'name' is the name of a capturing group defined in the regular expression pattern.</source> <target state="translated">Uma referência inversa nomeada ou numerada. 'name' é o nome de um grupo de captura definido no padrão de expressão regular.</target> <note /> </trans-unit> <trans-unit id="Regex_named_backreference_short"> <source>named backreference</source> <target state="translated">referência inversa nomeada</target> <note /> </trans-unit> <trans-unit id="Regex_named_matched_subexpression_long"> <source>Captures a matched subexpression and lets you access it by name or by number. 'name' is a valid group name, and 'subexpression' is any valid regular expression pattern. 'name' must not contain any punctuation characters and cannot begin with a number. If the RegexOptions parameter of a regular expression pattern matching method includes the RegexOptions.ExplicitCapture flag, or if the n option is applied to this subexpression, the only way to capture a subexpression is to explicitly name capturing groups.</source> <target state="translated">Captura uma subexpressão correspondida e permite que você a acesse por nome ou número. 'name' é um nome de grupo válido e 'subexpression' é qualquer padrão de expressão regular válido. 'name' não pode conter nenhum caractere de pontuação e não pode começar com um número. Se o parâmetro RegexOptions de um método de correspondência de padrões de expressão regular incluir o sinalizador RegexOptions.ExplicitCapture ou se a opção n for aplicada a essa subexpressão, a única maneira de capturar uma subexpressão será nomear explicitamente os grupos de captura.</target> <note /> </trans-unit> <trans-unit id="Regex_named_matched_subexpression_short"> <source>named matched subexpression</source> <target state="translated">subexpressão de correspondência nomeada</target> <note /> </trans-unit> <trans-unit id="Regex_negative_character_group_long"> <source>A negative character group specifies a list of characters that must not appear in an input string for a match to occur. The list of characters are specified individually. Two or more character ranges can be concatenated. For example, to specify the range of decimal digits from "0" through "9", the range of lowercase letters from "a" through "f", and the range of uppercase letters from "A" through "F", use [0-9a-fA-F].</source> <target state="translated">Um grupo de caracteres negativos especifica uma lista de caracteres que não podem aparecer em uma cadeia de caracteres de entrada para que uma correspondência ocorra. A lista de caracteres é especificada individualmente. Dois ou mais intervalos de caracteres podem ser concatenados. Por exemplo, para especificar o intervalo de dígitos decimais de "0" a "9", o intervalo de letras minúsculas de "a" até "f" e o intervalo de letras maiúsculas de "A" até "F", use [0-9a-fA-F].</target> <note /> </trans-unit> <trans-unit id="Regex_negative_character_group_short"> <source>negative character group</source> <target state="translated">grupo de caracteres negativos</target> <note /> </trans-unit> <trans-unit id="Regex_negative_character_range_long"> <source>A negative character range specifies a list of characters that must not appear in an input string for a match to occur. 'firstCharacter' is the character that begins the range, and 'lastCharacter' is the character that ends the range. Two or more character ranges can be concatenated. For example, to specify the range of decimal digits from "0" through "9", the range of lowercase letters from "a" through "f", and the range of uppercase letters from "A" through "F", use [0-9a-fA-F].</source> <target state="translated">Um intervalo de caracteres negativos especifica uma lista de caracteres que não podem aparecer em uma cadeia de caracteres de entrada para que uma correspondência ocorra. 'firstCharacter' é o caractere que inicia o intervalo e 'lastCharacter' é o caractere que termina o intervalo. Dois ou mais intervalos de caracteres podem ser concatenados. Por exemplo, para especificar o intervalo de dígitos decimais de "0" a "9", o intervalo de letras minúsculas de "a" até "f" e o intervalo de letras maiúsculas de "A" até "F", use [0-9a-fA-F].</target> <note /> </trans-unit> <trans-unit id="Regex_negative_character_range_short"> <source>negative character range</source> <target state="translated">intervalo de caracteres negativos</target> <note /> </trans-unit> <trans-unit id="Regex_negative_unicode_category_long"> <source>The regular expression construct \P{ name } matches any character that does not belong to a Unicode general category or named block, where name is the category abbreviation or named block name.</source> <target state="translated">O constructo de expressão regular \P{ name } corresponde a qualquer caractere que não pertença a uma categoria Unicode genérica nem a um bloco nomeado, em que o nome seja a abreviação da categoria ou o nome do bloco nomeado.</target> <note /> </trans-unit> <trans-unit id="Regex_negative_unicode_category_short"> <source>negative unicode category</source> <target state="translated">categoria unicode negativa</target> <note /> </trans-unit> <trans-unit id="Regex_new_line_character_long"> <source>Matches a new-line character, \u000A</source> <target state="translated">Corresponde a um caractere de nova linha, \u000A</target> <note /> </trans-unit> <trans-unit id="Regex_new_line_character_short"> <source>new-line character</source> <target state="translated">caractere de nova linha</target> <note /> </trans-unit> <trans-unit id="Regex_no"> <source>no</source> <target state="translated">não</target> <note /> </trans-unit> <trans-unit id="Regex_non_digit_character_long"> <source>\D matches any non-digit character. It is equivalent to the \P{Nd} regular expression pattern. If ECMAScript-compliant behavior is specified, \D is equivalent to [^0-9]</source> <target state="translated">\D corresponde a qualquer caractere que não seja um dígito. Ele equivale ao padrão de expressão regular \p{Nd}. Se o comportamento em conformidade com o ECMAScript for especificado, \D será equivalente a [^0-9]</target> <note /> </trans-unit> <trans-unit id="Regex_non_digit_character_short"> <source>non-digit character</source> <target state="translated">caractere que não é dígito</target> <note /> </trans-unit> <trans-unit id="Regex_non_white_space_character_long"> <source>\S matches any non-white-space character. It is equivalent to the [^\f\n\r\t\v\x85\p{Z}] regular expression pattern, or the opposite of the regular expression pattern that is equivalent to \s, which matches white-space characters. If ECMAScript-compliant behavior is specified, \S is equivalent to [^ \f\n\r\t\v]</source> <target state="translated">\S corresponde a qualquer caractere que não seja um espaço em branco. Ele equivale ao padrão de expressão regular [^\f\n\r\t\v\x85\p{Z}] ou ao oposto do padrão de expressão regular equivalente a \s, que corresponde a caracteres de espaço em branco. Se o comportamento em conformidade com o ECMAScript for especificado, \S será equivalente a [^ \f\n\r\t\v]</target> <note /> </trans-unit> <trans-unit id="Regex_non_white_space_character_short"> <source>non-white-space character</source> <target state="translated">caractere que não é de espaço em branco</target> <note /> </trans-unit> <trans-unit id="Regex_non_word_boundary_long"> <source>The \B anchor specifies that the match must not occur on a word boundary. It is the opposite of the \b anchor.</source> <target state="translated">A âncora \B especifica que a correspondência não pode ocorrer em um limite de palavra. Ela é o oposto da âncora \b.</target> <note /> </trans-unit> <trans-unit id="Regex_non_word_boundary_short"> <source>non-word boundary</source> <target state="translated">limite que não é de palavra</target> <note /> </trans-unit> <trans-unit id="Regex_non_word_character_long"> <source>\W matches any non-word character. It matches any character except for those in the following Unicode categories: Ll Letter, Lowercase Lu Letter, Uppercase Lt Letter, Titlecase Lo Letter, Other Lm Letter, Modifier Mn Mark, Nonspacing Nd Number, Decimal Digit Pc Punctuation, Connector If ECMAScript-compliant behavior is specified, \W is equivalent to [^a-zA-Z_0-9]</source> <target state="translated">\W corresponde a qualquer caractere que não seja uma palavra. Ele corresponde a qualquer caractere, exceto os das categorias Unicode a seguir: Ll Letra, Minúscula Lu Letra, Maiúscula Lt Letra, Inicial Maiúscula Lo Letra, Outro Lm Letra, Modificador Mn Marca, Não Espaçamento Nd Número, Dígito Decimal Pc Pontuação, Conector Se o comportamento em conformidade com o ECMAScript for especificado, \W será equivalente a [^a-zA-Z_0-9]</target> <note>Note: Ll, Lu, Lt, Lo, Lm, Mn, Nd, and Pc are all things that should not be localized. </note> </trans-unit> <trans-unit id="Regex_non_word_character_short"> <source>non-word character</source> <target state="translated">caractere que não é palavra</target> <note /> </trans-unit> <trans-unit id="Regex_noncapturing_group_long"> <source>This construct does not capture the substring that is matched by a subexpression: The noncapturing group construct is typically used when a quantifier is applied to a group, but the substrings captured by the group are of no interest. If a regular expression includes nested grouping constructs, an outer noncapturing group construct does not apply to the inner nested group constructs.</source> <target state="translated">Este constructo não captura a substring correspondida por uma subexpressão: O constructo do grupo que não é de captura geralmente é usado quando um quantificador é aplicado a um grupo, mas as substrings capturadas pelo grupo não são de interesse. Se uma expressão regular inclui constructos de agrupamento aninhado, um constructo externo de grupo de não captura não se aplica aos constructos internos de grupo aninhado.</target> <note /> </trans-unit> <trans-unit id="Regex_noncapturing_group_short"> <source>noncapturing group</source> <target state="translated">grupo que não é de captura</target> <note /> </trans-unit> <trans-unit id="Regex_number_decimal_digit"> <source>number, decimal digit</source> <target state="translated">número, dígito decimal</target> <note /> </trans-unit> <trans-unit id="Regex_number_letter"> <source>number, letter</source> <target state="translated">número, letra</target> <note /> </trans-unit> <trans-unit id="Regex_number_other"> <source>number, other</source> <target state="translated">número, outro</target> <note /> </trans-unit> <trans-unit id="Regex_numbered_backreference_long"> <source>A numbered backreference, where 'number' is the ordinal position of the capturing group in the regular expression. For example, \4 matches the contents of the fourth capturing group. There is an ambiguity between octal escape codes (such as \16) and \number backreferences that use the same notation. If the ambiguity is a problem, you can use the \k&lt;name&gt; notation, which is unambiguous and cannot be confused with octal character codes. Similarly, hexadecimal codes such as \xdd are unambiguous and cannot be confused with backreferences.</source> <target state="translated">Uma referência inversa numerada, em que 'number' é a posição ordinal do grupo de captura na expressão regular. Por exemplo, \4 corresponde ao conteúdo do quarto grupo de captura. Há uma ambiguidade entre os códigos de escape octais (como \16) e as referências inversas \number que usam a mesma notação. Se a ambiguidade causar algum problema, use a notação \k&lt;name&gt;, que não é ambígua e não pode ser confundida com códigos de caracteres octais. Da mesma forma, os códigos hexadecimais como \xdd não são ambíguos e não podem ser confundidos com referências inversas.</target> <note /> </trans-unit> <trans-unit id="Regex_numbered_backreference_short"> <source>numbered backreference</source> <target state="translated">referência inversa numerada</target> <note /> </trans-unit> <trans-unit id="Regex_other_control"> <source>other, control</source> <target state="translated">outro, controle</target> <note /> </trans-unit> <trans-unit id="Regex_other_format"> <source>other, format</source> <target state="translated">outro, formato</target> <note /> </trans-unit> <trans-unit id="Regex_other_not_assigned"> <source>other, not assigned</source> <target state="translated">outro, não atribuído</target> <note /> </trans-unit> <trans-unit id="Regex_other_private_use"> <source>other, private use</source> <target state="translated">outro, uso privado</target> <note /> </trans-unit> <trans-unit id="Regex_other_surrogate"> <source>other, surrogate</source> <target state="translated">outro, alternativo</target> <note /> </trans-unit> <trans-unit id="Regex_positive_character_group_long"> <source>A positive character group specifies a list of characters, any one of which may appear in an input string for a match to occur.</source> <target state="translated">Um grupo de caracteres positivos especifica uma lista de caracteres, em que qualquer um deles pode aparecer em uma cadeia de caracteres de entrada para que uma correspondência ocorra.</target> <note /> </trans-unit> <trans-unit id="Regex_positive_character_group_short"> <source>positive character group</source> <target state="translated">grupo de caracteres positivos</target> <note /> </trans-unit> <trans-unit id="Regex_positive_character_range_long"> <source>A positive character range specifies a range of characters, any one of which may appear in an input string for a match to occur. 'firstCharacter' is the character that begins the range and 'lastCharacter' is the character that ends the range. </source> <target state="translated">Um intervalo de caracteres positivos especifica um intervalo de caracteres, em que qualquer um deles pode aparecer em uma cadeia de caracteres de entrada para que uma correspondência ocorra. 'firstCharacter' é o caractere que inicia o intervalo e 'lastCharacter' é o caractere que termina o intervalo. </target> <note /> </trans-unit> <trans-unit id="Regex_positive_character_range_short"> <source>positive character range</source> <target state="translated">intervalo de caracteres positivos</target> <note /> </trans-unit> <trans-unit id="Regex_punctuation_close"> <source>punctuation, close</source> <target state="translated">pontuação, fechar</target> <note /> </trans-unit> <trans-unit id="Regex_punctuation_connector"> <source>punctuation, connector</source> <target state="translated">pontuação, conector</target> <note /> </trans-unit> <trans-unit id="Regex_punctuation_dash"> <source>punctuation, dash</source> <target state="translated">pontuação, traço</target> <note /> </trans-unit> <trans-unit id="Regex_punctuation_final_quote"> <source>punctuation, final quote</source> <target state="translated">pontuação, aspa final</target> <note /> </trans-unit> <trans-unit id="Regex_punctuation_initial_quote"> <source>punctuation, initial quote</source> <target state="translated">pontuação, aspa inicial</target> <note /> </trans-unit> <trans-unit id="Regex_punctuation_open"> <source>punctuation, open</source> <target state="translated">pontuação, abrir</target> <note /> </trans-unit> <trans-unit id="Regex_punctuation_other"> <source>punctuation, other</source> <target state="translated">pontuação, outros</target> <note /> </trans-unit> <trans-unit id="Regex_separator_line"> <source>separator, line</source> <target state="translated">separador, linha</target> <note /> </trans-unit> <trans-unit id="Regex_separator_paragraph"> <source>separator, paragraph</source> <target state="translated">separador, parágrafo</target> <note /> </trans-unit> <trans-unit id="Regex_separator_space"> <source>separator, space</source> <target state="translated">separador, espaço</target> <note /> </trans-unit> <trans-unit id="Regex_start_of_string_only_long"> <source>The \A anchor specifies that a match must occur at the beginning of the input string. It is identical to the ^ anchor, except that \A ignores the RegexOptions.Multiline option. Therefore, it can only match the start of the first line in a multiline input string.</source> <target state="translated">A âncora \A especifica que uma correspondência precisa ocorrer no início da cadeia de caracteres de entrada. Ela é idêntica à âncora ^, exceto que \A ignora a opção RegexOptions.Multiline. Portanto, ela só pode corresponder ao início da primeira linha em uma cadeia de caracteres de entrada multilinha.</target> <note /> </trans-unit> <trans-unit id="Regex_start_of_string_only_short"> <source>start of string only</source> <target state="translated">somente início de cadeia de caracteres</target> <note /> </trans-unit> <trans-unit id="Regex_start_of_string_or_line_long"> <source>The ^ anchor specifies that the following pattern must begin at the first character position of the string. If you use ^ with the RegexOptions.Multiline option, the match must occur at the beginning of each line.</source> <target state="translated">A âncora ^ especifica que o padrão a seguir precisa começar na primeira posição de caractere da cadeia de caracteres. Se você usar ^ com a opção RegexOptions.Multiline, a correspondência deverá ocorrer no início de cada linha.</target> <note /> </trans-unit> <trans-unit id="Regex_start_of_string_or_line_short"> <source>start of string or line</source> <target state="translated">início de cadeia de caracteres ou de linha</target> <note /> </trans-unit> <trans-unit id="Regex_subexpression"> <source>subexpression</source> <target state="translated">subexpressão</target> <note /> </trans-unit> <trans-unit id="Regex_symbol_currency"> <source>symbol, currency</source> <target state="translated">símbolo, moeda</target> <note /> </trans-unit> <trans-unit id="Regex_symbol_math"> <source>symbol, math</source> <target state="translated">símbolo, matemática</target> <note /> </trans-unit> <trans-unit id="Regex_symbol_modifier"> <source>symbol, modifier</source> <target state="translated">símbolo, modificador</target> <note /> </trans-unit> <trans-unit id="Regex_symbol_other"> <source>symbol, other</source> <target state="translated">símbolo, outro</target> <note /> </trans-unit> <trans-unit id="Regex_tab_character_long"> <source>Matches a tab character, \u0009</source> <target state="translated">Corresponde a um caractere de tabulação, \u0009</target> <note /> </trans-unit> <trans-unit id="Regex_tab_character_short"> <source>tab character</source> <target state="translated">caractere de tabulação</target> <note /> </trans-unit> <trans-unit id="Regex_unicode_category_long"> <source>The regular expression construct \p{ name } matches any character that belongs to a Unicode general category or named block, where name is the category abbreviation or named block name.</source> <target state="translated">O constructo de expressão regular \p{ name } corresponde a qualquer caractere que pertença a uma categoria genérica Unicode ou a um bloco nomeado, em que o nome seja a abreviação da categoria ou o nome do bloco nomeado.</target> <note /> </trans-unit> <trans-unit id="Regex_unicode_category_short"> <source>unicode category</source> <target state="translated">categoria unicode</target> <note /> </trans-unit> <trans-unit id="Regex_unicode_escape_long"> <source>Matches a UTF-16 code unit whose value is #### hexadecimal.</source> <target state="translated">Corresponde a uma unidade de código UTF-16 cujo valor é o hexadecimal ####.</target> <note /> </trans-unit> <trans-unit id="Regex_unicode_escape_short"> <source>unicode escape</source> <target state="translated">escape unicode</target> <note /> </trans-unit> <trans-unit id="Regex_unicode_general_category_0"> <source>Unicode General Category: {0}</source> <target state="translated">Categoria Geral Unicode: {0}</target> <note /> </trans-unit> <trans-unit id="Regex_vertical_tab_character_long"> <source>Matches a vertical-tab character, \u000B</source> <target state="translated">Corresponde a um caractere de tabulação vertical, \u000B</target> <note /> </trans-unit> <trans-unit id="Regex_vertical_tab_character_short"> <source>vertical-tab character</source> <target state="translated">caractere de tabulação vertical</target> <note /> </trans-unit> <trans-unit id="Regex_white_space_character_long"> <source>\s matches any white-space character. It is equivalent to the following escape sequences and Unicode categories: \f The form feed character, \u000C \n The newline character, \u000A \r The carriage return character, \u000D \t The tab character, \u0009 \v The vertical tab character, \u000B \x85 The ellipsis or NEXT LINE (NEL) character (…), \u0085 \p{Z} Matches any separator character If ECMAScript-compliant behavior is specified, \s is equivalent to [ \f\n\r\t\v]</source> <target state="translated">\s corresponde a qualquer caractere de espaço em branco. Ele equivale às seguintes sequências de escape e categorias Unicode: \f O caractere de avanço de página, \u000C \n O caractere de nova linha, \u000A \r O caractere de retorno de carro, \u000D \t O caractere de tabulação, \u0009 \v O caractere de tabulação vertical, \u000B \x85 A elipse ou o caractere NEL (NOVA LINHA) (...), \u0085 \p{Z} Corresponde a qualquer caractere separador Se o comportamento em conformidade com o ECMAScript for especificado, \s será equivalente a [ \f\n\r\t\v]</target> <note /> </trans-unit> <trans-unit id="Regex_white_space_character_short"> <source>white-space character</source> <target state="translated">o caractere de espaço em branco</target> <note /> </trans-unit> <trans-unit id="Regex_word_boundary_long"> <source>The \b anchor specifies that the match must occur on a boundary between a word character (the \w language element) and a non-word character (the \W language element). Word characters consist of alphanumeric characters and underscores; a non-word character is any character that is not alphanumeric or an underscore. The match may also occur on a word boundary at the beginning or end of the string. The \b anchor is frequently used to ensure that a subexpression matches an entire word instead of just the beginning or end of a word.</source> <target state="translated">A âncora \b especifica que a correspondência precisa ocorrer em um limite entre um caractere de palavra (o elemento de linguagem \w) e um caractere que não seja de palavra (o elemento de linguagem \W). Os caracteres de palavra consistem em caracteres alfanuméricos e sublinhados; um caractere que não é de palavra é qualquer caractere que não é alfanumérico nem sublinhado. A correspondência também pode ocorrer em um limite de palavra no início ou no fim da cadeia de caracteres. A âncora \b é usada geralmente para garantir que uma subexpressão corresponda a uma palavra inteira em vez de apenas ao início ou ao fim de uma palavra.</target> <note /> </trans-unit> <trans-unit id="Regex_word_boundary_short"> <source>word boundary</source> <target state="translated">limite de palavra</target> <note /> </trans-unit> <trans-unit id="Regex_word_character_long"> <source>\w matches any word character. A word character is a member of any of the following Unicode categories: Ll Letter, Lowercase Lu Letter, Uppercase Lt Letter, Titlecase Lo Letter, Other Lm Letter, Modifier Mn Mark, Nonspacing Nd Number, Decimal Digit Pc Punctuation, Connector If ECMAScript-compliant behavior is specified, \w is equivalent to [a-zA-Z_0-9]</source> <target state="translated">\w corresponde a qualquer caractere de palavra. Um caractere de palavra é membro de qualquer uma das seguintes categorias Unicode: Ll Letra, Minúscula Lu Letra, Maiúscula Lt Letra, Inicial Maiúscula Lo Letra, Outro Lm Letra, Modificador Mn Marca, Não Espaçamento Nd Número, Dígito Decimal Pc Pontuação, Conector Se o comportamento em conformidade com o ECMAScript for especificado, \w será equivalente a [a-zA-Z_0-9]</target> <note>Note: Ll, Lu, Lt, Lo, Lm, Mn, Nd, and Pc are all things that should not be localized.</note> </trans-unit> <trans-unit id="Regex_word_character_short"> <source>word character</source> <target state="translated">caractere de palavra</target> <note /> </trans-unit> <trans-unit id="Regex_yes"> <source>yes</source> <target state="translated">sim</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_negative_lookahead_assertion_long"> <source>A zero-width negative lookahead assertion, where for the match to be successful, the input string must not match the regular expression pattern in subexpression. The matched string is not included in the match result. A zero-width negative lookahead assertion is typically used either at the beginning or at the end of a regular expression. At the beginning of a regular expression, it can define a specific pattern that should not be matched when the beginning of the regular expression defines a similar but more general pattern to be matched. In this case, it is often used to limit backtracking. At the end of a regular expression, it can define a subexpression that cannot occur at the end of a match.</source> <target state="translated">Uma asserção lookahead negativa de largura zero, em que, para que a correspondência seja bem-sucedida, a cadeia de caracteres de entrada não pode corresponder ao padrão de expressão regular na subexpressão. A cadeia de caracteres correspondente não está incluída no resultado correspondente. Uma asserção lookahead negativa de largura zero normalmente é usada no início ou no final de uma expressão regular. No início de uma expressão regular, ela pode definir um padrão específico que não deve ser correspondido quando o início da expressão regular define um padrão semelhante, mas mais geral, a ser correspondido. Nesse caso, ela geralmente é usada para limitar o rastreamento inverso. No final de uma expressão regular, ela pode definir uma subexpressão que não pode ocorrer no final de uma correspondência.</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_negative_lookahead_assertion_short"> <source>zero-width negative lookahead assertion</source> <target state="translated">asserção lookahead negativa de largura zero</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_negative_lookbehind_assertion_long"> <source>A zero-width negative lookbehind assertion, where for a match to be successful, 'subexpression' must not occur at the input string to the left of the current position. Any substring that does not match 'subexpression' is not included in the match result. Zero-width negative lookbehind assertions are typically used at the beginning of regular expressions. The pattern that they define precludes a match in the string that follows. They are also used to limit backtracking when the last character or characters in a captured group must not be one or more of the characters that match that group's regular expression pattern.</source> <target state="translated">Uma asserção lookbehind negativa de largura zero, em que, para que uma correspondência seja bem-sucedida, a 'subexpression' não pode ocorrer na cadeia de caracteres de entrada à esquerda da posição atual. As substrings que não corresponderem à 'subexpression' não serão incluídas no resultado correspondente. As declarações de lookbehind negativas de largura zero normalmente são usadas no início de expressões regulares. O padrão que elas definem impede uma correspondência na cadeia de caracteres seguinte. Elas também são usadas para limitar o rastreamento inverso quando o último caractere ou caracteres em um grupo capturado não pode ser um ou mais dos caracteres que correspondem ao padrão dessa expressão regular do grupo.</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_negative_lookbehind_assertion_short"> <source>zero-width negative lookbehind assertion</source> <target state="translated">asserção lookbehind negativa de largura zero</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_positive_lookahead_assertion_long"> <source>A zero-width positive lookahead assertion, where for a match to be successful, the input string must match the regular expression pattern in 'subexpression'. The matched substring is not included in the match result. A zero-width positive lookahead assertion does not backtrack. Typically, a zero-width positive lookahead assertion is found at the end of a regular expression pattern. It defines a substring that must be found at the end of a string for a match to occur but that should not be included in the match. It is also useful for preventing excessive backtracking. You can use a zero-width positive lookahead assertion to ensure that a particular captured group begins with text that matches a subset of the pattern defined for that captured group.</source> <target state="translated">Uma asserção lookahead positiva de largura zero, em que para que uma correspondência seja bem-sucedida, a cadeia de caracteres de entrada precisa corresponder ao padrão de expressão regular na 'subexpression'. A substring correspondente não é incluída no resultado correspondente. Uma asserção lookahead positiva de largura zero não retrocede. Normalmente, uma asserção lookahead positiva de largura zero é encontrada no final de um padrão de expressão regular. Ela define uma substring que precisa ser encontrada no final de uma cadeia de caracteres para que uma correspondência ocorra, mas que não deve ser incluída na correspondência. Ela também é útil para impedir o rastreamento inverso excessivo. Você pode usar uma asserção lookahead positiva de largura zero para garantir que um determinado grupo capturado comece com um texto que corresponda a um subconjunto do padrão definido para esse grupo capturado.</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_positive_lookahead_assertion_short"> <source>zero-width positive lookahead assertion</source> <target state="translated">asserção lookahead positiva de largura zero</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_positive_lookbehind_assertion_long"> <source>A zero-width positive lookbehind assertion, where for a match to be successful, 'subexpression' must occur at the input string to the left of the current position. 'subexpression' is not included in the match result. A zero-width positive lookbehind assertion does not backtrack. Zero-width positive lookbehind assertions are typically used at the beginning of regular expressions. The pattern that they define is a precondition for a match, although it is not a part of the match result.</source> <target state="translated">Uma asserção lookbehind positiva de largura zero, em que, para que uma correspondência seja bem-sucedida, a 'subexpression' precisa ocorrer na cadeia de caracteres de entrada à esquerda da posição atual. A 'subexpression' não é incluída no resultado correspondente. Uma asserção lookbehind positiva de largura zero não retrocede. As declarações de lookbehind positivas de largura zero normalmente são usadas no início de expressões regulares. O padrão que elas definem é uma pré-condição para uma correspondência, apesar de não fazer parte do resultado correspondente.</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_positive_lookbehind_assertion_short"> <source>zero-width positive lookbehind assertion</source> <target state="translated">asserção lookbehind positiva de largura zero</target> <note /> </trans-unit> <trans-unit id="Related_method_signatures_found_in_metadata_will_not_be_updated"> <source>Related method signatures found in metadata will not be updated.</source> <target state="translated">As assinaturas de método relacionadas encontradas nos metadados não serão atualizadas.</target> <note /> </trans-unit> <trans-unit id="Removal_of_document_not_supported"> <source>Removal of document not supported</source> <target state="translated">Não há suporte para a remoção do documento</target> <note /> </trans-unit> <trans-unit id="Remove_async_modifier"> <source>Remove 'async' modifier</source> <target state="translated">Remover o modificador 'async'</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_casts"> <source>Remove unnecessary casts</source> <target state="translated">Remover conversões desnecessárias</target> <note /> </trans-unit> <trans-unit id="Remove_unused_variables"> <source>Remove unused variables</source> <target state="translated">Remover variáveis não utilizadas</target> <note /> </trans-unit> <trans-unit id="Removing_0_that_accessed_captured_variables_1_and_2_declared_in_different_scopes_requires_restarting_the_application"> <source>Removing {0} that accessed captured variables '{1}' and '{2}' declared in different scopes requires restarting the application.</source> <target state="new">Removing {0} that accessed captured variables '{1}' and '{2}' declared in different scopes requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Removing_0_that_contains_an_active_statement_requires_restarting_the_application"> <source>Removing {0} that contains an active statement requires restarting the application.</source> <target state="new">Removing {0} that contains an active statement requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Renaming_0_requires_restarting_the_application"> <source>Renaming {0} requires restarting the application.</source> <target state="new">Renaming {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Renaming_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime"> <source>Renaming {0} requires restarting the application because it is not supported by the runtime.</source> <target state="new">Renaming {0} requires restarting the application because it is not supported by the runtime.</target> <note /> </trans-unit> <trans-unit id="Renaming_a_captured_variable_from_0_to_1_requires_restarting_the_application"> <source>Renaming a captured variable, from '{0}' to '{1}' requires restarting the application.</source> <target state="new">Renaming a captured variable, from '{0}' to '{1}' requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Replace_0_with_1"> <source>Replace '{0}' with '{1}' </source> <target state="translated">Substituir '{0}' por '{1}'</target> <note /> </trans-unit> <trans-unit id="Resolve_conflict_markers"> <source>Resolve conflict markers</source> <target state="translated">Resolver marcadores de conflitos</target> <note /> </trans-unit> <trans-unit id="RudeEdit"> <source>Rude edit</source> <target state="translated">Edição rudimentar</target> <note /> </trans-unit> <trans-unit id="Selection_does_not_contain_a_valid_token"> <source>Selection does not contain a valid token.</source> <target state="new">Selection does not contain a valid token.</target> <note /> </trans-unit> <trans-unit id="Selection_not_contained_inside_a_type"> <source>Selection not contained inside a type.</source> <target state="new">Selection not contained inside a type.</target> <note /> </trans-unit> <trans-unit id="Sort_accessibility_modifiers"> <source>Sort accessibility modifiers</source> <target state="translated">Classificar modificadores de acessibilidade</target> <note /> </trans-unit> <trans-unit id="Split_into_consecutive_0_statements"> <source>Split into consecutive '{0}' statements</source> <target state="translated">Dividir em instruções '{0}' consecutivas</target> <note /> </trans-unit> <trans-unit id="Split_into_nested_0_statements"> <source>Split into nested '{0}' statements</source> <target state="translated">Dividir em instruções '{0}' aninhadas</target> <note /> </trans-unit> <trans-unit id="StreamMustSupportReadAndSeek"> <source>Stream must support read and seek operations.</source> <target state="translated">O fluxo deve fornecer suporte a operações de leitura e busca.</target> <note /> </trans-unit> <trans-unit id="Suppress_0"> <source>Suppress {0}</source> <target state="translated">Suprimir {0}</target> <note /> </trans-unit> <trans-unit id="Switching_between_lambda_and_local_function_requires_restarting_the_application"> <source>Switching between a lambda and a local function requires restarting the application.</source> <target state="new">Switching between a lambda and a local function requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="TODO_colon_free_unmanaged_resources_unmanaged_objects_and_override_finalizer"> <source>TODO: free unmanaged resources (unmanaged objects) and override finalizer</source> <target state="new">TODO: free unmanaged resources (unmanaged objects) and override finalizer</target> <note /> </trans-unit> <trans-unit id="TODO_colon_override_finalizer_only_if_0_has_code_to_free_unmanaged_resources"> <source>TODO: override finalizer only if '{0}' has code to free unmanaged resources</source> <target state="new">TODO: override finalizer only if '{0}' has code to free unmanaged resources</target> <note /> </trans-unit> <trans-unit id="Target_type_matches"> <source>Target type matches</source> <target state="translated">Correspondências de tipos de destino</target> <note /> </trans-unit> <trans-unit id="The_assembly_0_containing_type_1_references_NET_Framework"> <source>The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported.</source> <target state="translated">O assembly '{0}' contendo o tipo '{1}' referencia o .NET Framework, mas não há suporte para isso.</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_a_local_function_call_without_its_declaration"> <source>The selection contains a local function call without its declaration.</source> <target state="translated">A seleção contém uma chamada de função local sem sua declaração.</target> <note /> </trans-unit> <trans-unit id="Too_many_bars_in_conditional_grouping"> <source>Too many | in (?()|)</source> <target state="translated">Muitos | em (?()|)</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?(0)a|b|)</note> </trans-unit> <trans-unit id="Too_many_close_parens"> <source>Too many )'s</source> <target state="translated">Muitos )'s</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: )</note> </trans-unit> <trans-unit id="UnableToReadSourceFileOrPdb"> <source>Unable to read source file '{0}' or the PDB built for the containing project. Any changes made to this file while debugging won't be applied until its content matches the built source.</source> <target state="translated">Não é possível ler o arquivo de origem '{0}' ou o PDB criado para o projeto que o contém. Todas as alterações feitas neste arquivo durante a depuração não serão aplicadas até que o conteúdo corresponda ao código-fonte compilado.</target> <note /> </trans-unit> <trans-unit id="Unknown_property"> <source>Unknown property</source> <target state="translated">Propriedade desconhecida</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \p{}</note> </trans-unit> <trans-unit id="Unknown_property_0"> <source>Unknown property '{0}'</source> <target state="translated">Propriedade desconhecida '{0}'</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \p{xxx}. Here, {0} will be the name of the unknown property ('xxx')</note> </trans-unit> <trans-unit id="Unrecognized_control_character"> <source>Unrecognized control character</source> <target state="translated">Caractere de controle não reconhecido</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: [\c]</note> </trans-unit> <trans-unit id="Unrecognized_escape_sequence_0"> <source>Unrecognized escape sequence \{0}</source> <target state="translated">Sequência de escape não reconhecida \{0}</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \m. Here, {0} will be the unrecognized character ('m')</note> </trans-unit> <trans-unit id="Unrecognized_grouping_construct"> <source>Unrecognized grouping construct</source> <target state="translated">Constructo de agrupamento não reconhecida</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?&lt;</note> </trans-unit> <trans-unit id="Unterminated_character_class_set"> <source>Unterminated [] set</source> <target state="translated">Conjunto [] não finalizado</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: [</note> </trans-unit> <trans-unit id="Unterminated_regex_comment"> <source>Unterminated (?#...) comment</source> <target state="translated">Comentário (?#...) não finalizado</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?#</note> </trans-unit> <trans-unit id="Unwrap_all_arguments"> <source>Unwrap all arguments</source> <target state="translated">Desencapsular todos os argumentos</target> <note /> </trans-unit> <trans-unit id="Unwrap_all_parameters"> <source>Unwrap all parameters</source> <target state="translated">Desencapsular todos os parâmetros</target> <note /> </trans-unit> <trans-unit id="Unwrap_and_indent_all_arguments"> <source>Unwrap and indent all arguments</source> <target state="translated">Desencapsular e recuar todos os argumentos</target> <note /> </trans-unit> <trans-unit id="Unwrap_and_indent_all_parameters"> <source>Unwrap and indent all parameters</source> <target state="translated">Desencapsular e recuar todos os parâmetros</target> <note /> </trans-unit> <trans-unit id="Unwrap_argument_list"> <source>Unwrap argument list</source> <target state="translated">Desencapsular a lista de argumentos</target> <note /> </trans-unit> <trans-unit id="Unwrap_call_chain"> <source>Unwrap call chain</source> <target state="translated">Desencapsular cadeia de chamadas</target> <note /> </trans-unit> <trans-unit id="Unwrap_expression"> <source>Unwrap expression</source> <target state="translated">Desencapsular a expressão</target> <note /> </trans-unit> <trans-unit id="Unwrap_parameter_list"> <source>Unwrap parameter list</source> <target state="translated">Desencapsular a lista de parâmetros</target> <note /> </trans-unit> <trans-unit id="Updating_0_requires_restarting_the_application"> <source>Updating '{0}' requires restarting the application.</source> <target state="new">Updating '{0}' requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_a_0_around_an_active_statement_requires_restarting_the_application"> <source>Updating a {0} around an active statement requires restarting the application.</source> <target state="new">Updating a {0} around an active statement requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_a_complex_statement_containing_an_await_expression_requires_restarting_the_application"> <source>Updating a complex statement containing an await expression requires restarting the application.</source> <target state="new">Updating a complex statement containing an await expression requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_an_active_statement_requires_restarting_the_application"> <source>Updating an active statement requires restarting the application.</source> <target state="new">Updating an active statement requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_async_or_iterator_modifier_around_an_active_statement_requires_restarting_the_application"> <source>Updating async or iterator modifier around an active statement requires restarting the application.</source> <target state="new">Updating async or iterator modifier around an active statement requires restarting the application.</target> <note>{Locked="async"}{Locked="iterator"} "async" and "iterator" are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Updating_reloadable_type_marked_by_0_attribute_or_its_member_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime"> <source>Updating a reloadable type (marked by {0}) or its member requires restarting the application because is not supported by the runtime.</source> <target state="new">Updating a reloadable type (marked by {0}) or its member requires restarting the application because is not supported by the runtime.</target> <note /> </trans-unit> <trans-unit id="Updating_the_Handles_clause_of_0_requires_restarting_the_application"> <source>Updating the Handles clause of {0} requires restarting the application.</source> <target state="new">Updating the Handles clause of {0} requires restarting the application.</target> <note>{Locked="Handles"} "Handles" is VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Updating_the_Implements_clause_of_a_0_requires_restarting_the_application"> <source>Updating the Implements clause of a {0} requires restarting the application.</source> <target state="new">Updating the Implements clause of a {0} requires restarting the application.</target> <note>{Locked="Implements"} "Implements" is VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Updating_the_alias_of_Declare_statement_requires_restarting_the_application"> <source>Updating the alias of Declare statement requires restarting the application.</source> <target state="new">Updating the alias of Declare statement requires restarting the application.</target> <note>{Locked="Declare"} "Declare" is VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime"> <source>Updating the attributes of {0} requires restarting the application because it is not supported by the runtime.</source> <target state="new">Updating the attributes of {0} requires restarting the application because it is not supported by the runtime.</target> <note /> </trans-unit> <trans-unit id="Updating_the_base_class_and_or_base_interface_s_of_0_requires_restarting_the_application"> <source>Updating the base class and/or base interface(s) of {0} requires restarting the application.</source> <target state="new">Updating the base class and/or base interface(s) of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_initializer_of_0_requires_restarting_the_application"> <source>Updating the initializer of {0} requires restarting the application.</source> <target state="new">Updating the initializer of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_kind_of_a_property_event_accessor_requires_restarting_the_application"> <source>Updating the kind of a property/event accessor requires restarting the application.</source> <target state="new">Updating the kind of a property/event accessor requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_kind_of_a_type_requires_restarting_the_application"> <source>Updating the kind of a type requires restarting the application.</source> <target state="new">Updating the kind of a type requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_library_name_of_Declare_statement_requires_restarting_the_application"> <source>Updating the library name of Declare statement requires restarting the application.</source> <target state="new">Updating the library name of Declare statement requires restarting the application.</target> <note>{Locked="Declare"} "Declare" is VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Updating_the_modifiers_of_0_requires_restarting_the_application"> <source>Updating the modifiers of {0} requires restarting the application.</source> <target state="new">Updating the modifiers of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_size_of_a_0_requires_restarting_the_application"> <source>Updating the size of a {0} requires restarting the application.</source> <target state="new">Updating the size of a {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_type_of_0_requires_restarting_the_application"> <source>Updating the type of {0} requires restarting the application.</source> <target state="new">Updating the type of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_underlying_type_of_0_requires_restarting_the_application"> <source>Updating the underlying type of {0} requires restarting the application.</source> <target state="new">Updating the underlying type of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_variance_of_0_requires_restarting_the_application"> <source>Updating the variance of {0} requires restarting the application.</source> <target state="new">Updating the variance of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_lambda_expressions"> <source>Use block body for lambda expressions</source> <target state="translated">Usar o corpo do bloco para expressões lambda</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambda_expressions"> <source>Use expression body for lambda expressions</source> <target state="translated">Usar corpo da expressão para expressões lambda</target> <note /> </trans-unit> <trans-unit id="Use_interpolated_verbatim_string"> <source>Use interpolated verbatim string</source> <target state="translated">Usar cadeia de caracteres verbatim interpolada</target> <note /> </trans-unit> <trans-unit id="Value_colon"> <source>Value:</source> <target state="translated">Valor:</target> <note /> </trans-unit> <trans-unit id="Warning_colon_changing_namespace_may_produce_invalid_code_and_change_code_meaning"> <source>Warning: Changing namespace may produce invalid code and change code meaning.</source> <target state="translated">Aviso: a alteração do namespace pode produzir código inválido e mudar o significado do código.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_semantics_may_change_when_converting_statement"> <source>Warning: Semantics may change when converting statement.</source> <target state="translated">Aviso: a semântica pode ser alterada ao converter a instrução.</target> <note /> </trans-unit> <trans-unit id="Wrap_and_align_call_chain"> <source>Wrap and align call chain</source> <target state="translated">Encapsular e alinhar cadeia de chamadas</target> <note /> </trans-unit> <trans-unit id="Wrap_and_align_expression"> <source>Wrap and align expression</source> <target state="translated">Quebrar e alinhar expressão</target> <note /> </trans-unit> <trans-unit id="Wrap_and_align_long_call_chain"> <source>Wrap and align long call chain</source> <target state="translated">Encapsular e alinhar cadeia longa de chamadas</target> <note /> </trans-unit> <trans-unit id="Wrap_call_chain"> <source>Wrap call chain</source> <target state="translated">Encapsular cadeia de chamadas</target> <note /> </trans-unit> <trans-unit id="Wrap_every_argument"> <source>Wrap every argument</source> <target state="translated">Encapsular cada argumento</target> <note /> </trans-unit> <trans-unit id="Wrap_every_parameter"> <source>Wrap every parameter</source> <target state="translated">Encapsular cada parâmetro</target> <note /> </trans-unit> <trans-unit id="Wrap_expression"> <source>Wrap expression</source> <target state="translated">Encapsular a expressão</target> <note /> </trans-unit> <trans-unit id="Wrap_long_argument_list"> <source>Wrap long argument list</source> <target state="translated">Encapsular a lista de argumentos longa</target> <note /> </trans-unit> <trans-unit id="Wrap_long_call_chain"> <source>Wrap long call chain</source> <target state="translated">Encapsular cadeia longa de chamadas</target> <note /> </trans-unit> <trans-unit id="Wrap_long_parameter_list"> <source>Wrap long parameter list</source> <target state="translated">Encapsular a lista de parâmetros longa</target> <note /> </trans-unit> <trans-unit id="Wrapping"> <source>Wrapping</source> <target state="translated">Quebra de linha</target> <note /> </trans-unit> <trans-unit id="You_can_use_the_navigation_bar_to_switch_contexts"> <source>You can use the navigation bar to switch contexts.</source> <target state="translated">Você pode usar a barra de navegação para mudar de contexto.</target> <note /> </trans-unit> <trans-unit id="_0_cannot_be_null_or_empty"> <source>'{0}' cannot be null or empty.</source> <target state="translated">'{0}' não pode ser nulo nem vazio.</target> <note /> </trans-unit> <trans-unit id="_0_cannot_be_null_or_whitespace"> <source>'{0}' cannot be null or whitespace.</source> <target state="translated">'{0}' não pode ser nulo nem espaço em branco.</target> <note /> </trans-unit> <trans-unit id="_0_dash_1"> <source>{0} - {1}</source> <target state="translated">{0} - {1}</target> <note /> </trans-unit> <trans-unit id="_0_is_not_null_here"> <source>'{0}' is not null here.</source> <target state="translated">'{0}' não é nulo aqui.</target> <note /> </trans-unit> <trans-unit id="_0_may_be_null_here"> <source>'{0}' may be null here.</source> <target state="translated">'{0}' pode ser nulo aqui.</target> <note /> </trans-unit> <trans-unit id="_10000000ths_of_a_second"> <source>10,000,000ths of a second</source> <target state="translated">Dez milionésimos de um segundo</target> <note /> </trans-unit> <trans-unit id="_10000000ths_of_a_second_description"> <source>The "fffffff" custom format specifier represents the seven most significant digits of the seconds fraction; that is, it represents the ten millionths of a second in a date and time value. Although it's possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "fffffff" representa os sete dígitos mais significativos da fração de segundos. Ou seja, representa os dez milionésimos de segundo em um valor de data e hora. Embora seja possível exibir os dez milionésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT 3.5 (e posteriores) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_10000000ths_of_a_second_non_zero"> <source>10,000,000ths of a second (non-zero)</source> <target state="translated">Dez milionésimos de um segundo (diferente de zero)</target> <note /> </trans-unit> <trans-unit id="_10000000ths_of_a_second_non_zero_description"> <source>The "FFFFFFF" custom format specifier represents the seven most significant digits of the seconds fraction; that is, it represents the ten millionths of a second in a date and time value. However, trailing zeros or seven zero digits aren't displayed. Although it's possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "FFFFFFF" representa os sete dígitos mais significativos da fração de segundos. Ou seja, representa os dez milionésimos de segundo em um valor de data e hora. No entanto, zeros à direita ou sete dígitos de zero não são exibidos. Embora seja possível exibir os dez milionésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT 3.5 (e posteriores) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_1000000ths_of_a_second"> <source>1,000,000ths of a second</source> <target state="translated">Milionésimos de um segundo</target> <note /> </trans-unit> <trans-unit id="_1000000ths_of_a_second_description"> <source>The "ffffff" custom format specifier represents the six most significant digits of the seconds fraction; that is, it represents the millionths of a second in a date and time value. Although it's possible to display the millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "FFFFFF" representa os seis dígitos mais significativos da fração de segundos. Ou seja, ele representa os milionésimos de segundo em um valor de data e hora. Embora seja possível exibir os milionésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT 3.5 (e posteriores) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_1000000ths_of_a_second_non_zero"> <source>1,000,000ths of a second (non-zero)</source> <target state="translated">Milionésimos de um segundo (diferente de zero)</target> <note /> </trans-unit> <trans-unit id="_1000000ths_of_a_second_non_zero_description"> <source>The "FFFFFF" custom format specifier represents the six most significant digits of the seconds fraction; that is, it represents the millionths of a second in a date and time value. However, trailing zeros or six zero digits aren't displayed. Although it's possible to display the millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "FFFFFF" representa os seis dígitos mais significativos da fração de segundos. Ou seja, ele representa os milionésimos de segundo em um valor de data e hora. No entanto, zeros à direita ou seis dígitos de zero não são exibidos. Embora seja possível exibir os milionésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT 3.5 (e posteriores) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_100000ths_of_a_second"> <source>100,000ths of a second</source> <target state="translated">Cem milésimos de um segundo</target> <note /> </trans-unit> <trans-unit id="_100000ths_of_a_second_description"> <source>The "fffff" custom format specifier represents the five most significant digits of the seconds fraction; that is, it represents the hundred thousandths of a second in a date and time value. Although it's possible to display the hundred thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "fffff" representa os cinco dígitos mais significativos da fração de segundos. Ou seja, representa as centenas de milésimos de segundo em um valor de data e hora. Embora seja possível exibir as centenas de milésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT 3.5 (e posteriores) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_100000ths_of_a_second_non_zero"> <source>100,000ths of a second (non-zero)</source> <target state="translated">Cem milésimos de um segundo (diferente de zero)</target> <note /> </trans-unit> <trans-unit id="_100000ths_of_a_second_non_zero_description"> <source>The "FFFFF" custom format specifier represents the five most significant digits of the seconds fraction; that is, it represents the hundred thousandths of a second in a date and time value. However, trailing zeros or five zero digits aren't displayed. Although it's possible to display the hundred thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "FFFFF" representa os cinco dígitos mais significativos da fração de segundos. Ou seja, representa as centenas de milésimos de segundo em um valor de data e hora. No entanto, zeros à direita ou cinco dígitos de zero não são exibidos. Embora seja possível exibir as centenas de milésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT 3.5 (e posteriores) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_10000ths_of_a_second"> <source>10,000ths of a second</source> <target state="translated">Dez milésimos de um segundo</target> <note /> </trans-unit> <trans-unit id="_10000ths_of_a_second_description"> <source>The "ffff" custom format specifier represents the four most significant digits of the seconds fraction; that is, it represents the ten thousandths of a second in a date and time value. Although it's possible to display the ten thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT version 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "ffff" representa os quatro dígitos mais significativos da fração de segundos. Ou seja, representa os dez milésimos de segundo em um valor de data e hora. Embora seja possível exibir os dez milésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT versão 3.5 (e posterior) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_10000ths_of_a_second_non_zero"> <source>10,000ths of a second (non-zero)</source> <target state="translated">Dez milésimos de um segundo (diferente de zero)</target> <note /> </trans-unit> <trans-unit id="_10000ths_of_a_second_non_zero_description"> <source>The "FFFF" custom format specifier represents the four most significant digits of the seconds fraction; that is, it represents the ten thousandths of a second in a date and time value. However, trailing zeros or four zero digits aren't displayed. Although it's possible to display the ten thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "FFFF" representa os quatro dígitos mais significativos da fração de segundos. Ou seja, representa os dez milésimos de segundo em um valor de data e hora. No entanto, zeros à direita ou quatro dígitos de zero não são exibidos. Embora seja possível exibir os dez milésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT 3.5 (e posteriores) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_1000ths_of_a_second"> <source>1,000ths of a second</source> <target state="translated">Milésimos de um segundo</target> <note /> </trans-unit> <trans-unit id="_1000ths_of_a_second_description"> <source>The "fff" custom format specifier represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.</source> <target state="translated">O especificador de formato personalizado "fff" representa os três dígitos mais significativos da fração de segundos. Ou seja, ele representa os milissegundos em um valor de data e hora.</target> <note /> </trans-unit> <trans-unit id="_1000ths_of_a_second_non_zero"> <source>1,000ths of a second (non-zero)</source> <target state="translated">Milésimos de um segundo (diferente de zero)</target> <note /> </trans-unit> <trans-unit id="_1000ths_of_a_second_non_zero_description"> <source>The "FFF" custom format specifier represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value. However, trailing zeros or three zero digits aren't displayed.</source> <target state="translated">O especificador de formato personalizado "FFF" representa os três dígitos mais significativos da fração de segundos. Ou seja, ele representa os milissegundos em um valor de data e hora. No entanto, zeros à direita ou três dígitos de zero não são exibidos.</target> <note /> </trans-unit> <trans-unit id="_100ths_of_a_second"> <source>100ths of a second</source> <target state="translated">Centésimos de um segundo</target> <note /> </trans-unit> <trans-unit id="_100ths_of_a_second_description"> <source>The "ff" custom format specifier represents the two most significant digits of the seconds fraction; that is, it represents the hundredths of a second in a date and time value.</source> <target state="translated">O especificador de formato personalizado "ff" representa os dois dígitos mais significativos da fração de segundos. Ou seja, ele representa os centésimos de segundo em um valor de data e hora.</target> <note /> </trans-unit> <trans-unit id="_100ths_of_a_second_non_zero"> <source>100ths of a second (non-zero)</source> <target state="translated">Centésimos de segundo (diferente de zero)</target> <note /> </trans-unit> <trans-unit id="_100ths_of_a_second_non_zero_description"> <source>The "FF" custom format specifier represents the two most significant digits of the seconds fraction; that is, it represents the hundredths of a second in a date and time value. However, trailing zeros or two zero digits aren't displayed.</source> <target state="translated">O especificador de formato personalizado "FF" representa os dois dígitos mais significativos da fração de segundos. Ou seja, ele representa os centésimos de segundo em um valor de data e hora. No entanto, zeros à direita ou dois dígitos de zero não são exibidos.</target> <note /> </trans-unit> <trans-unit id="_10ths_of_a_second"> <source>10ths of a second</source> <target state="translated">Décimos de segundo</target> <note /> </trans-unit> <trans-unit id="_10ths_of_a_second_description"> <source>The "f" custom format specifier represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. If the "f" format specifier is used without other format specifiers, it's interpreted as the "f" standard date and time format specifier. When you use "f" format specifiers as part of a format string supplied to the ParseExact or TryParseExact method, the number of "f" format specifiers indicates the number of most significant digits of the seconds fraction that must be present to successfully parse the string.</source> <target state="new">The "f" custom format specifier represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. If the "f" format specifier is used without other format specifiers, it's interpreted as the "f" standard date and time format specifier. When you use "f" format specifiers as part of a format string supplied to the ParseExact or TryParseExact method, the number of "f" format specifiers indicates the number of most significant digits of the seconds fraction that must be present to successfully parse the string.</target> <note>{Locked="ParseExact"}{Locked="TryParseExact"}{Locked=""f""}</note> </trans-unit> <trans-unit id="_10ths_of_a_second_non_zero"> <source>10ths of a second (non-zero)</source> <target state="translated">Décimos de segundo (diferente de zero)</target> <note /> </trans-unit> <trans-unit id="_10ths_of_a_second_non_zero_description"> <source>The "F" custom format specifier represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. Nothing is displayed if the digit is zero. If the "F" format specifier is used without other format specifiers, it's interpreted as the "F" standard date and time format specifier. The number of "F" format specifiers used with the ParseExact, TryParseExact, ParseExact, or TryParseExact method indicates the maximum number of most significant digits of the seconds fraction that can be present to successfully parse the string.</source> <target state="translated">O especificador de formato personalizado "F" representa o dígito mais significativo da fração de segundos; ou seja, ele representa os décimos de segundo em um valor de data e hora. Nada será exibido se o dígito for zero. Se o especificador de formato "F" for usado sem outros especificadores de formato, ele será interpretado como o especificador de formato padrão de data e hora "F". O número de especificadores de formato "F" usados com o método ParseExact, TryParseExact, ParseExact ou TryParseExact indica o número máximo de dígitos significativos da fração de segundos que podem estar presentes para analisar a cadeia de caracteres com êxito.</target> <note /> </trans-unit> <trans-unit id="_12_hour_clock_1_2_digits"> <source>12 hour clock (1-2 digits)</source> <target state="translated">Relógio de 12 horas (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="_12_hour_clock_1_2_digits_description"> <source>The "h" custom format specifier represents the hour as a number from 1 through 12; that is, the hour is represented by a 12-hour clock that counts the whole hours since midnight or noon. A particular hour after midnight is indistinguishable from the same hour after noon. The hour is not rounded, and a single-digit hour is formatted without a leading zero. For example, given a time of 5:43 in the morning or afternoon, this custom format specifier displays "5". If the "h" format specifier is used without other custom format specifiers, it's interpreted as a standard date and time format specifier and throws a FormatException.</source> <target state="translated">O especificador de formato personalizado "h" representa a hora como um número de 1 a 12. Ou seja, a hora é representada por um relógio de 12 horas que conta todas as horas desde a meia-noite ou o meio-dia. Uma determinada hora após a meia-noite é indistinguível da mesma hora após o meio-dia. A hora não é arredondada e uma hora de dígito único é formatada sem um zero à esquerda. Por exemplo, dado um horário de 5:43 na manhã ou à tarde, este especificador de formato personalizado exibe "5". Se o especificador de formato "h" for usado sem outros especificadores de formato personalizado, ele será interpretado como um especificador de formato padrão de data e hora e gerará uma FormatException.</target> <note /> </trans-unit> <trans-unit id="_12_hour_clock_2_digits"> <source>12 hour clock (2 digits)</source> <target state="translated">Relógio de 12 horas (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="_12_hour_clock_2_digits_description"> <source>The "hh" custom format specifier (plus any number of additional "h" specifiers) represents the hour as a number from 01 through 12; that is, the hour is represented by a 12-hour clock that counts the whole hours since midnight or noon. A particular hour after midnight is indistinguishable from the same hour after noon. The hour is not rounded, and a single-digit hour is formatted with a leading zero. For example, given a time of 5:43 in the morning or afternoon, this format specifier displays "05".</source> <target state="translated">O especificador de formato personalizado "hh" (mais qualquer número de especificadores "h" adicionais) representa a hora como um número de 01 a 12. Ou seja, a hora é representada por um relógio de 12 horas que conta todas as horas desde a meia-noite ou o meio-dia. Uma determinada hora após a meia-noite é indistinguível da mesma hora após o meio-dia. A hora não é arredondada e uma hora de dígito único é formatada com um zero à esquerda. Por exemplo, dado um horário de 5:43 na manhã ou à tarde, esse especificador de formato exibe "05".</target> <note /> </trans-unit> <trans-unit id="_24_hour_clock_1_2_digits"> <source>24 hour clock (1-2 digits)</source> <target state="translated">Relógio de 24 horas (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="_24_hour_clock_1_2_digits_description"> <source>The "H" custom format specifier represents the hour as a number from 0 through 23; that is, the hour is represented by a zero-based 24-hour clock that counts the hours since midnight. A single-digit hour is formatted without a leading zero. If the "H" format specifier is used without other custom format specifiers, it's interpreted as a standard date and time format specifier and throws a FormatException.</source> <target state="translated">O especificador de formato personalizado "H" representa a hora como um número de 0 a 23. Ou seja, a hora é representada por um relógio de 24 horas com base em zero que conta as horas desde a meia-noite. Uma hora de dígito único é formatada sem um zero à esquerda. Se o especificador de formato "H" for usado sem outros especificadores de formato personalizado, ele será interpretado como um especificador de formato padrão de data e hora e gerará uma FormatException.</target> <note /> </trans-unit> <trans-unit id="_24_hour_clock_2_digits"> <source>24 hour clock (2 digits)</source> <target state="translated">Relógio de 24 horas (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="_24_hour_clock_2_digits_description"> <source>The "HH" custom format specifier (plus any number of additional "H" specifiers) represents the hour as a number from 00 through 23; that is, the hour is represented by a zero-based 24-hour clock that counts the hours since midnight. A single-digit hour is formatted with a leading zero.</source> <target state="translated">O especificador de formato personalizado "HH" (mais qualquer número de especificadores "H" adicionais) representa a hora como um número de 00 a 23. Ou seja, a hora é representada por um relógio de 24 horas com base em zero que conta as horas desde a meia-noite. Uma hora de dígito único é formatada com um zero à esquerda.</target> <note /> </trans-unit> <trans-unit id="and_update_call_sites_directly"> <source>and update call sites directly</source> <target state="new">and update call sites directly</target> <note /> </trans-unit> <trans-unit id="code"> <source>code</source> <target state="translated">código</target> <note /> </trans-unit> <trans-unit id="date_separator"> <source>date separator</source> <target state="translated">separador de data</target> <note /> </trans-unit> <trans-unit id="date_separator_description"> <source>The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture. Note: To change the date separator for a particular date and time string, specify the separator character within a literal string delimiter. For example, the custom format string mm'/'dd'/'yyyy produces a result string in which "/" is always used as the date separator. To change the date separator for all dates for a culture, either change the value of the DateTimeFormatInfo.DateSeparator property of the current culture, or instantiate a DateTimeFormatInfo object, assign the character to its DateSeparator property, and call an overload of the formatting method that includes an IFormatProvider parameter. If the "/" format specifier is used without other custom format specifiers, it's interpreted as a standard date and time format specifier and throws a FormatException.</source> <target state="translated">O especificador de formato personalizado "/" representa o separador de data, que é usado para diferenciar anos, meses e dias. O separador de data localizado apropriado é recuperado da propriedade DateTimeFormatInfo.DateSeparator da cultura atual ou especificada. Observação: para alterar o separador de data de uma determinada cadeia de caracteres de data e hora, especifique o caractere separador em um delimitador de cadeia de caracteres literal. Por exemplo, a cadeia de caracteres de formato personalizado mm'/'dd'/'yyyy produz uma cadeia de resultado na qual "/" é sempre usado como separador de data. Para alterar o separador de data para todas as datas para uma cultura, altere o valor da propriedade DateTimeFormatInfo.DateSeparator da cultura atual ou crie uma instância de um objeto DateTimeFormatInfo, atribua o caractere à sua propriedade DateSeparator e chame uma sobrecarga do método de formatação que inclui um parâmetro IFormatProvider. Se o especificador de formato "/" for usado sem outros especificadores de formato personalizado, ele será interpretado como um especificador de formato padrão de data e hora e gerará uma FormatException.</target> <note /> </trans-unit> <trans-unit id="day_of_the_month_1_2_digits"> <source>day of the month (1-2 digits)</source> <target state="translated">dia do mês (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="day_of_the_month_1_2_digits_description"> <source>The "d" custom format specifier represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero. If the "d" format specifier is used without other custom format specifiers, it's interpreted as the "d" standard date and time format specifier.</source> <target state="translated">O especificador de formato personalizado "d" representa o dia do mês como um número de 1 a 31. Um dia de dígito único é formatado sem um zero à esquerda. Se o especificador de formato "d" for usado sem outros especificadores de formato personalizado, ele será interpretado como o especificador de formato padrão de data e hora "d".</target> <note /> </trans-unit> <trans-unit id="day_of_the_month_2_digits"> <source>day of the month (2 digits)</source> <target state="translated">dia do mês (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="day_of_the_month_2_digits_description"> <source>The "dd" custom format string represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero.</source> <target state="translated">A cadeia de caracteres de formato personalizado "dd" representa o dia do mês como um número de 01 a 31. Um dia de dígito único é formatado com um zero à esquerda.</target> <note /> </trans-unit> <trans-unit id="day_of_the_week_abbreviated"> <source>day of the week (abbreviated)</source> <target state="translated">dia da semana (abreviado)</target> <note /> </trans-unit> <trans-unit id="day_of_the_week_abbreviated_description"> <source>The "ddd" custom format specifier represents the abbreviated name of the day of the week. The localized abbreviated name of the day of the week is retrieved from the DateTimeFormatInfo.AbbreviatedDayNames property of the current or specified culture.</source> <target state="translated">O especificador de formato personalizado "ddd" representa o nome abreviado do dia da semana. O nome abreviado localizado do dia da semana é recuperado da propriedade DateTimeFormatInfo.AbbreviatedDayNames da cultura atual ou especificada.</target> <note /> </trans-unit> <trans-unit id="day_of_the_week_full"> <source>day of the week (full)</source> <target state="translated">dia da semana (completo)</target> <note /> </trans-unit> <trans-unit id="day_of_the_week_full_description"> <source>The "dddd" custom format specifier (plus any number of additional "d" specifiers) represents the full name of the day of the week. The localized name of the day of the week is retrieved from the DateTimeFormatInfo.DayNames property of the current or specified culture.</source> <target state="translated">O especificador de formato personalizado "dddd" (mais qualquer número de especificadores "d" adicionais) representa o nome completo do dia da semana. O nome localizado do dia da semana é recuperado da propriedade DateTimeFormatInfo.DayNames da cultura atual ou especificada.</target> <note /> </trans-unit> <trans-unit id="discard"> <source>discard</source> <target state="translated">discard</target> <note /> </trans-unit> <trans-unit id="from_metadata"> <source>from metadata</source> <target state="translated">de metadados</target> <note /> </trans-unit> <trans-unit id="full_long_date_time"> <source>full long date/time</source> <target state="translated">data/hora completa por extenso</target> <note /> </trans-unit> <trans-unit id="full_long_date_time_description"> <source>The "F" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.FullDateTimePattern property. For example, the custom format string for the invariant culture is "dddd, dd MMMM yyyy HH:mm:ss".</source> <target state="translated">O especificador de formato padrão "F" representa uma cadeia de caracteres de formato de data e hora personalizada que é definida pela propriedade DateTimeFormatInfo. FullDateTimePattern atual. Por exemplo, a cadeia de caracteres de formato personalizado para a cultura invariável é "dddd, dd MMMM yyyy HH:mm:ss".</target> <note /> </trans-unit> <trans-unit id="full_short_date_time"> <source>full short date/time</source> <target state="translated">data/hora abreviada por extenso</target> <note /> </trans-unit> <trans-unit id="full_short_date_time_description"> <source>The Full Date Short Time ("f") Format Specifier The "f" standard format specifier represents a combination of the long date ("D") and short time ("t") patterns, separated by a space.</source> <target state="translated">O Especificador de Formato de Data por Extenso Hora Abreviada ("f") O especificador de formato padrão "f" representa uma combinação de padrões de data por extenso ("D") e tempo abreviado ("t"), separados por um espaço.</target> <note /> </trans-unit> <trans-unit id="general_long_date_time"> <source>general long date/time</source> <target state="translated">data/hora geral por extenso</target> <note /> </trans-unit> <trans-unit id="general_long_date_time_description"> <source>The "G" standard format specifier represents a combination of the short date ("d") and long time ("T") patterns, separated by a space.</source> <target state="translated">O especificador de formato padrão "G" representa uma combinação dos padrões de data abreviada ("d") e hora por extenso ("T"), separados por um espaço.</target> <note /> </trans-unit> <trans-unit id="general_short_date_time"> <source>general short date/time</source> <target state="translated">data/hora abreviada geral</target> <note /> </trans-unit> <trans-unit id="general_short_date_time_description"> <source>The "g" standard format specifier represents a combination of the short date ("d") and short time ("t") patterns, separated by a space.</source> <target state="translated">O especificador de formato padrão "g" representa uma combinação dos padrões de data abreviada ("d") e hora abreviada ("t"), separados por um espaço.</target> <note /> </trans-unit> <trans-unit id="generic_overload"> <source>generic overload</source> <target state="translated">sobrecarga genérica</target> <note /> </trans-unit> <trans-unit id="generic_overloads"> <source>generic overloads</source> <target state="translated">sobrecargas genéricas</target> <note /> </trans-unit> <trans-unit id="in_0_1_2"> <source>in {0} ({1} - {2})</source> <target state="translated">em {0} ({1} – {2})</target> <note /> </trans-unit> <trans-unit id="in_Source_attribute"> <source>in Source (attribute)</source> <target state="translated">na Origem (atributo)</target> <note /> </trans-unit> <trans-unit id="into_extracted_method_to_invoke_at_call_sites"> <source>into extracted method to invoke at call sites</source> <target state="new">into extracted method to invoke at call sites</target> <note /> </trans-unit> <trans-unit id="into_new_overload"> <source>into new overload</source> <target state="new">into new overload</target> <note /> </trans-unit> <trans-unit id="long_date"> <source>long date</source> <target state="translated">data completa</target> <note /> </trans-unit> <trans-unit id="long_date_description"> <source>The "D" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.LongDatePattern property. For example, the custom format string for the invariant culture is "dddd, dd MMMM yyyy".</source> <target state="translated">O especificador de formato padrão "D" representa uma cadeia de caracteres de formato de data e hora personalizada que é definida pela propriedade DateTimeFormatInfo.LongDatePattern atual. Por exemplo, a cadeia de caracteres de formato personalizado para a cultura invariável é "dddd, dd MMMM yyyy".</target> <note /> </trans-unit> <trans-unit id="long_time"> <source>long time</source> <target state="translated">hora completa</target> <note /> </trans-unit> <trans-unit id="long_time_description"> <source>The "T" standard format specifier represents a custom date and time format string that is defined by a specific culture's DateTimeFormatInfo.LongTimePattern property. For example, the custom format string for the invariant culture is "HH:mm:ss".</source> <target state="translated">O especificador de formato padrão "T" representa uma cadeia de caracteres de formato personalizado de data e hora que é definida pela propriedade DateTimeFormatInfo.LongTimePattern de uma cultura específica. Por exemplo, a cadeia de caracteres de formato personalizado para a cultura invariável é "HH:mm:ss".</target> <note /> </trans-unit> <trans-unit id="member_kind_and_name"> <source>{0} '{1}'</source> <target state="translated">{0} '{1}'</target> <note>e.g. "method 'M'"</note> </trans-unit> <trans-unit id="minute_1_2_digits"> <source>minute (1-2 digits)</source> <target state="translated">minuto (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="minute_1_2_digits_description"> <source>The "m" custom format specifier represents the minute as a number from 0 through 59. The minute represents whole minutes that have passed since the last hour. A single-digit minute is formatted without a leading zero. If the "m" format specifier is used without other custom format specifiers, it's interpreted as the "m" standard date and time format specifier.</source> <target state="translated">O especificador de formato personalizado "m" representa o minuto como um número de 0 a 59. O minuto representa minutos inteiros que passaram desde a última hora. Um minuto de dígito único é formatado sem um zero à esquerda. Se o especificador de formato "m" for usado sem outros especificadores de formato personalizado, ele será interpretado como o especificador de formato padrão de data e hora "m".</target> <note /> </trans-unit> <trans-unit id="minute_2_digits"> <source>minute (2 digits)</source> <target state="translated">minuto (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="minute_2_digits_description"> <source>The "mm" custom format specifier (plus any number of additional "m" specifiers) represents the minute as a number from 00 through 59. The minute represents whole minutes that have passed since the last hour. A single-digit minute is formatted with a leading zero.</source> <target state="translated">O especificador de formato personalizado "mm" (mais qualquer número de especificadores "m" adicionais) representa o minuto como um número de 00 a 59. O minuto representa minutos inteiros que passaram desde a última hora. Um minuto de dígito único é formatado com um zero à esquerda.</target> <note /> </trans-unit> <trans-unit id="month_1_2_digits"> <source>month (1-2 digits)</source> <target state="translated">mês (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="month_1_2_digits_description"> <source>The "M" custom format specifier represents the month as a number from 1 through 12 (or from 1 through 13 for calendars that have 13 months). A single-digit month is formatted without a leading zero. If the "M" format specifier is used without other custom format specifiers, it's interpreted as the "M" standard date and time format specifier.</source> <target state="translated">O especificador de formato personalizado "M" representa o mês como um número de 1 a 12 (ou de 1 a 13 para calendários com 13 meses). Um mês de dígito único é formatado sem um zero à esquerda. Se o especificador de formato "M" for usado sem outros especificadores de formato personalizado, ele será interpretado como o especificador de formato padrão de data e hora "M".</target> <note /> </trans-unit> <trans-unit id="month_2_digits"> <source>month (2 digits)</source> <target state="translated">mês (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="month_2_digits_description"> <source>The "MM" custom format specifier represents the month as a number from 01 through 12 (or from 1 through 13 for calendars that have 13 months). A single-digit month is formatted with a leading zero.</source> <target state="translated">O especificador de formato personalizado "MM" representa o mês como um número de 01 a 12 (ou de 1 a 13 para calendários com 13 meses). Um mês de dígito único é formatado com um zero à esquerda.</target> <note /> </trans-unit> <trans-unit id="month_abbreviated"> <source>month (abbreviated)</source> <target state="translated">mês (abreviado)</target> <note /> </trans-unit> <trans-unit id="month_abbreviated_description"> <source>The "MMM" custom format specifier represents the abbreviated name of the month. The localized abbreviated name of the month is retrieved from the DateTimeFormatInfo.AbbreviatedMonthNames property of the current or specified culture.</source> <target state="translated">O especificador de formato personalizado "MMM" representa o nome abreviado do mês. O nome abreviado localizado do mês é recuperado da propriedade DateTimeFormatInfo.AbbreviatedMonthNames da cultura atual ou especificada.</target> <note /> </trans-unit> <trans-unit id="month_day"> <source>month day</source> <target state="translated">dia do mês</target> <note /> </trans-unit> <trans-unit id="month_day_description"> <source>The "M" or "m" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.MonthDayPattern property. For example, the custom format string for the invariant culture is "MMMM dd".</source> <target state="translated">O especificador de formato padrão "M" ou "m" representa uma cadeia de caracteres de formato personalizado de data e hora definida pela propriedade DateTimeFormatInfo.MonthDayPattern atual. Por exemplo, a cadeia de caracteres de formato personalizado para a cultura invariável é "MMMM dd".</target> <note /> </trans-unit> <trans-unit id="month_full"> <source>month (full)</source> <target state="translated">mês (completo)</target> <note /> </trans-unit> <trans-unit id="month_full_description"> <source>The "MMMM" custom format specifier represents the full name of the month. The localized name of the month is retrieved from the DateTimeFormatInfo.MonthNames property of the current or specified culture.</source> <target state="translated">O especificador de formato personalizado "MMMM" representa o nome completo do mês. O nome localizado do mês é recuperado da propriedade DateTimeFormatInfo.MonthNames da cultura atual ou especificada.</target> <note /> </trans-unit> <trans-unit id="overload"> <source>overload</source> <target state="translated">sobrecarga</target> <note /> </trans-unit> <trans-unit id="overloads_"> <source>overloads</source> <target state="translated">sobrecargas</target> <note /> </trans-unit> <trans-unit id="_0_Keyword"> <source>{0} Keyword</source> <target state="translated">{0} Palavra-chave</target> <note /> </trans-unit> <trans-unit id="Encapsulate_field_colon_0_and_use_property"> <source>Encapsulate field: '{0}' (and use property)</source> <target state="translated">Encapsular campo: "{0}" (e usar propriedade)</target> <note /> </trans-unit> <trans-unit id="Encapsulate_field_colon_0_but_still_use_field"> <source>Encapsulate field: '{0}' (but still use field)</source> <target state="translated">Encapsular campo: "{0}" (mas ainda usar o campo)</target> <note /> </trans-unit> <trans-unit id="Encapsulate_fields_and_use_property"> <source>Encapsulate fields (and use property)</source> <target state="translated">Encapsular campos (e usar propriedade)</target> <note /> </trans-unit> <trans-unit id="Encapsulate_fields_but_still_use_field"> <source>Encapsulate fields (but still use field)</source> <target state="translated">Encapsular campos (mas ainda usá-los)</target> <note /> </trans-unit> <trans-unit id="Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct"> <source>Could not extract interface: The selection is not inside a class/interface/struct.</source> <target state="translated">Não foi possível extrair interface: a seleção não está dentro de uma classe/interface/struct.</target> <note /> </trans-unit> <trans-unit id="Could_not_extract_interface_colon_The_type_does_not_contain_any_member_that_can_be_extracted_to_an_interface"> <source>Could not extract interface: The type does not contain any member that can be extracted to an interface.</source> <target state="translated">Não foi possível extrair interface: O tipo não contém membros que podem ser extraídos para uma interface.</target> <note /> </trans-unit> <trans-unit id="can_t_not_construct_final_tree"> <source>can't not construct final tree</source> <target state="translated">não é possível construir a árvore final</target> <note /> </trans-unit> <trans-unit id="Parameters_type_or_return_type_cannot_be_an_anonymous_type_colon_bracket_0_bracket"> <source>Parameters' type or return type cannot be an anonymous type : [{0}]</source> <target state="translated">Tipo dos parâmetros ou tipo de retorno não pode ser um tipo anônimo: [{0}]</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_no_active_statement"> <source>The selection contains no active statement.</source> <target state="translated">A seleção não contém instrução ativa.</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_an_error_or_unknown_type"> <source>The selection contains an error or unknown type.</source> <target state="translated">A seleção contém um erro ou tipo desconhecido.</target> <note /> </trans-unit> <trans-unit id="Type_parameter_0_is_hidden_by_another_type_parameter_1"> <source>Type parameter '{0}' is hidden by another type parameter '{1}'.</source> <target state="translated">Parâmetro de tipo "{0}" está oculto por outro parâmetro de tipo "{1}".</target> <note /> </trans-unit> <trans-unit id="The_address_of_a_variable_is_used_inside_the_selected_code"> <source>The address of a variable is used inside the selected code.</source> <target state="translated">O endereço de uma variável é usado dentro do código selecionado.</target> <note /> </trans-unit> <trans-unit id="Assigning_to_readonly_fields_must_be_done_in_a_constructor_colon_bracket_0_bracket"> <source>Assigning to readonly fields must be done in a constructor : [{0}].</source> <target state="translated">A atribuição a campos somente leitura deve ser feita em um construtor: [{0}].</target> <note /> </trans-unit> <trans-unit id="generated_code_is_overlapping_with_hidden_portion_of_the_code"> <source>generated code is overlapping with hidden portion of the code</source> <target state="translated">o código gerado se sobrepõe à porção oculta do código</target> <note /> </trans-unit> <trans-unit id="Add_optional_parameters_to_0"> <source>Add optional parameters to '{0}'</source> <target state="translated">Adicionar parâmetros opcionais ao '{0}'</target> <note /> </trans-unit> <trans-unit id="Add_parameters_to_0"> <source>Add parameters to '{0}'</source> <target state="translated">Adicionar parâmetros ao '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_delegating_constructor_0_1"> <source>Generate delegating constructor '{0}({1})'</source> <target state="translated">Gerar construtor delegante "{0}({1})"</target> <note /> </trans-unit> <trans-unit id="Generate_constructor_0_1"> <source>Generate constructor '{0}({1})'</source> <target state="translated">Gerar construtor "{0}({1})"</target> <note /> </trans-unit> <trans-unit id="Generate_field_assigning_constructor_0_1"> <source>Generate field assigning constructor '{0}({1})'</source> <target state="translated">Gerar construtor de atribuição de campo "{0}({1})"</target> <note /> </trans-unit> <trans-unit id="Generate_Equals_and_GetHashCode"> <source>Generate Equals and GetHashCode</source> <target state="translated">Gerar Equals e GetHashCode</target> <note /> </trans-unit> <trans-unit id="Generate_Equals_object"> <source>Generate Equals(object)</source> <target state="translated">Gerar Equals(object)</target> <note /> </trans-unit> <trans-unit id="Generate_GetHashCode"> <source>Generate GetHashCode()</source> <target state="translated">Gerar GetHashCode()</target> <note /> </trans-unit> <trans-unit id="Generate_constructor_in_0"> <source>Generate constructor in '{0}'</source> <target state="translated">Gerar construtor em '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_all"> <source>Generate all</source> <target state="translated">Gerar todos</target> <note /> </trans-unit> <trans-unit id="Generate_enum_member_1_0"> <source>Generate enum member '{1}.{0}'</source> <target state="translated">Gerar membro enum '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_constant_1_0"> <source>Generate constant '{1}.{0}'</source> <target state="translated">Gerar constante '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_read_only_property_1_0"> <source>Generate read-only property '{1}.{0}'</source> <target state="translated">Gerar propriedade somente leitura '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_property_1_0"> <source>Generate property '{1}.{0}'</source> <target state="translated">Gerar propriedade '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_read_only_field_1_0"> <source>Generate read-only field '{1}.{0}'</source> <target state="translated">Gerar campo somente leitura '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_field_1_0"> <source>Generate field '{1}.{0}'</source> <target state="translated">Gerar campo '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_local_0"> <source>Generate local '{0}'</source> <target state="translated">Gerar local '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_0_1_in_new_file"> <source>Generate {0} '{1}' in new file</source> <target state="translated">Gerar {0} '{1}' no novo arquivo</target> <note /> </trans-unit> <trans-unit id="Generate_nested_0_1"> <source>Generate nested {0} '{1}'</source> <target state="translated">Gerar {0} '{1}' aninhado</target> <note /> </trans-unit> <trans-unit id="Global_Namespace"> <source>Global Namespace</source> <target state="translated">Namespace Global</target> <note /> </trans-unit> <trans-unit id="Implement_interface_abstractly"> <source>Implement interface abstractly</source> <target state="translated">Implementar interface de forma abstrata</target> <note /> </trans-unit> <trans-unit id="Implement_interface_through_0"> <source>Implement interface through '{0}'</source> <target state="translated">Implementar interface por meio de "{0}"</target> <note /> </trans-unit> <trans-unit id="Implement_interface"> <source>Implement interface</source> <target state="translated">Implementar a interface</target> <note /> </trans-unit> <trans-unit id="Introduce_field_for_0"> <source>Introduce field for '{0}'</source> <target state="translated">Encapsular campo para "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_local_for_0"> <source>Introduce local for '{0}'</source> <target state="translated">Introduzir local para "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_constant_for_0"> <source>Introduce constant for '{0}'</source> <target state="translated">Introduzir constante para "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_local_constant_for_0"> <source>Introduce local constant for '{0}'</source> <target state="translated">Introduzir constante local para "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_field_for_all_occurrences_of_0"> <source>Introduce field for all occurrences of '{0}'</source> <target state="translated">Introduzir campo para todas as ocorrências de "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_local_for_all_occurrences_of_0"> <source>Introduce local for all occurrences of '{0}'</source> <target state="translated">Introduzir local para todas as ocorrências de "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_constant_for_all_occurrences_of_0"> <source>Introduce constant for all occurrences of '{0}'</source> <target state="translated">Introduzir constante para todas as ocorrências de "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_local_constant_for_all_occurrences_of_0"> <source>Introduce local constant for all occurrences of '{0}'</source> <target state="translated">Introduzir constante de local para todas as ocorrências de "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_query_variable_for_all_occurrences_of_0"> <source>Introduce query variable for all occurrences of '{0}'</source> <target state="translated">Introduzir variável de consulta para todas as ocorrências de "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_query_variable_for_0"> <source>Introduce query variable for '{0}'</source> <target state="translated">Introduzir variável de consulta para "{0}"</target> <note /> </trans-unit> <trans-unit id="Anonymous_Types_colon"> <source>Anonymous Types:</source> <target state="translated">Tipos Anônimos:</target> <note /> </trans-unit> <trans-unit id="is_"> <source>is</source> <target state="translated">é</target> <note /> </trans-unit> <trans-unit id="Represents_an_object_whose_operations_will_be_resolved_at_runtime"> <source>Represents an object whose operations will be resolved at runtime.</source> <target state="translated">Representa um objeto cujas operações serão resolvidas no tempo de execução.</target> <note /> </trans-unit> <trans-unit id="constant"> <source>constant</source> <target state="translated">constante</target> <note /> </trans-unit> <trans-unit id="field"> <source>field</source> <target state="translated">Campo</target> <note /> </trans-unit> <trans-unit id="local_constant"> <source>local constant</source> <target state="translated">constante local</target> <note /> </trans-unit> <trans-unit id="local_variable"> <source>local variable</source> <target state="translated">variável local</target> <note /> </trans-unit> <trans-unit id="label"> <source>label</source> <target state="translated">Rótulo</target> <note /> </trans-unit> <trans-unit id="period_era"> <source>period/era</source> <target state="translated">período/era</target> <note /> </trans-unit> <trans-unit id="period_era_description"> <source>The "g" or "gg" custom format specifiers (plus any number of additional "g" specifiers) represents the period or era, such as A.D. The formatting operation ignores this specifier if the date to be formatted doesn't have an associated period or era string. If the "g" format specifier is used without other custom format specifiers, it's interpreted as the "g" standard date and time format specifier.</source> <target state="translated">Os especificadores de formato personalizado "g" ou "gg" (mais qualquer número de especificadores "g" adicionais) representam o período ou a era, como D.C. A operação de formatação ignorará o especificador se a data a ser formatada não tiver um período associado ou uma cadeia de caracteres de era. Se o especificador de formato "g" for usado sem outros especificadores de formato personalizado, ele será interpretado como o especificador de formato padrão de data e hora "g".</target> <note /> </trans-unit> <trans-unit id="property_accessor"> <source>property accessor</source> <target state="new">property accessor</target> <note /> </trans-unit> <trans-unit id="range_variable"> <source>range variable</source> <target state="translated">variável de intervalo</target> <note /> </trans-unit> <trans-unit id="parameter"> <source>parameter</source> <target state="translated">parâmetro</target> <note /> </trans-unit> <trans-unit id="in_"> <source>in</source> <target state="translated">Em</target> <note /> </trans-unit> <trans-unit id="Summary_colon"> <source>Summary:</source> <target state="translated">Resumo:</target> <note /> </trans-unit> <trans-unit id="Locals_and_parameters"> <source>Locals and parameters</source> <target state="translated">Locais e parâmetros</target> <note /> </trans-unit> <trans-unit id="Type_parameters_colon"> <source>Type parameters:</source> <target state="translated">Parâmetros de Tipo:</target> <note /> </trans-unit> <trans-unit id="Returns_colon"> <source>Returns:</source> <target state="translated">Devoluções:</target> <note /> </trans-unit> <trans-unit id="Exceptions_colon"> <source>Exceptions:</source> <target state="translated">Exceções:</target> <note /> </trans-unit> <trans-unit id="Remarks_colon"> <source>Remarks:</source> <target state="translated">Comentários:</target> <note /> </trans-unit> <trans-unit id="generating_source_for_symbols_of_this_type_is_not_supported"> <source>generating source for symbols of this type is not supported</source> <target state="translated">gerar fonte para símbolos deste tipo não é suportado</target> <note /> </trans-unit> <trans-unit id="Assembly"> <source>Assembly</source> <target state="translated">assembly</target> <note /> </trans-unit> <trans-unit id="location_unknown"> <source>location unknown</source> <target state="translated">local desconhecido</target> <note /> </trans-unit> <trans-unit id="Unexpected_interface_member_kind_colon_0"> <source>Unexpected interface member kind: {0}</source> <target state="translated">Tipo de membro de interface inesperado: {0}</target> <note /> </trans-unit> <trans-unit id="Unknown_symbol_kind"> <source>Unknown symbol kind</source> <target state="translated">Tipo de símbolo desconhecido</target> <note /> </trans-unit> <trans-unit id="Generate_abstract_property_1_0"> <source>Generate abstract property '{1}.{0}'</source> <target state="translated">Gerar propriedade abstrata '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_abstract_method_1_0"> <source>Generate abstract method '{1}.{0}'</source> <target state="translated">Gerar método abstrato '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_method_1_0"> <source>Generate method '{1}.{0}'</source> <target state="translated">Gerar método '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Requested_assembly_already_loaded_from_0"> <source>Requested assembly already loaded from '{0}'.</source> <target state="translated">Assembly solicitado já carregado de "{0}".</target> <note /> </trans-unit> <trans-unit id="The_symbol_does_not_have_an_icon"> <source>The symbol does not have an icon.</source> <target state="translated">O símbolo não tem um ícone.</target> <note /> </trans-unit> <trans-unit id="Asynchronous_method_cannot_have_ref_out_parameters_colon_bracket_0_bracket"> <source>Asynchronous method cannot have ref/out parameters : [{0}]</source> <target state="translated">Método assíncrono não pode ter parâmetros ref/out: [{0}]</target> <note /> </trans-unit> <trans-unit id="The_member_is_defined_in_metadata"> <source>The member is defined in metadata.</source> <target state="translated">O membro é definido em metadados.</target> <note /> </trans-unit> <trans-unit id="You_can_only_change_the_signature_of_a_constructor_indexer_method_or_delegate"> <source>You can only change the signature of a constructor, indexer, method or delegate.</source> <target state="translated">Você só pode alterar a assinatura de um construtor, indexador, método ou delegate.</target> <note /> </trans-unit> <trans-unit id="This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue"> <source>This symbol has related definitions or references in metadata. Changing its signature may result in build errors. Do you want to continue?</source> <target state="translated">Este símbolo possui definições relacionadas ou referências nos metadados. Alterar sua assinatura pode resultar em erros de compilação. Deseja continuar?</target> <note /> </trans-unit> <trans-unit id="Change_signature"> <source>Change signature...</source> <target state="translated">Alterar assinatura...</target> <note /> </trans-unit> <trans-unit id="Generate_new_type"> <source>Generate new type...</source> <target state="translated">Gerar novo tipo...</target> <note /> </trans-unit> <trans-unit id="User_Diagnostic_Analyzer_Failure"> <source>User Diagnostic Analyzer Failure.</source> <target state="translated">Falha do Analisador de Diagnóstico do Usuário.</target> <note /> </trans-unit> <trans-unit id="Analyzer_0_threw_an_exception_of_type_1_with_message_2"> <source>Analyzer '{0}' threw an exception of type '{1}' with message '{2}'.</source> <target state="translated">O analisador '{0}' gerou uma exceção do tipo '{1}' com a mensagem '{2}'.</target> <note /> </trans-unit> <trans-unit id="Analyzer_0_threw_the_following_exception_colon_1"> <source>Analyzer '{0}' threw the following exception: '{1}'.</source> <target state="translated">O analisador '{0}' gerou a seguinte exceção: '{1}'.</target> <note /> </trans-unit> <trans-unit id="Simplify_Names"> <source>Simplify Names</source> <target state="translated">Simplificar Nomes</target> <note /> </trans-unit> <trans-unit id="Simplify_Member_Access"> <source>Simplify Member Access</source> <target state="translated">Simplificar o Acesso de Membro</target> <note /> </trans-unit> <trans-unit id="Remove_qualification"> <source>Remove qualification</source> <target state="translated">Remover qualificação</target> <note /> </trans-unit> <trans-unit id="Unknown_error_occurred"> <source>Unknown error occurred</source> <target state="translated">Erro desconhecido</target> <note /> </trans-unit> <trans-unit id="Available"> <source>Available</source> <target state="translated">Disponível</target> <note /> </trans-unit> <trans-unit id="Not_Available"> <source>Not Available ⚠</source> <target state="translated">Não Disponível ⚠</target> <note /> </trans-unit> <trans-unit id="_0_1"> <source> {0} - {1}</source> <target state="translated"> {0} - {1}</target> <note /> </trans-unit> <trans-unit id="in_Source"> <source>in Source</source> <target state="translated">na Fonte</target> <note /> </trans-unit> <trans-unit id="in_Suppression_File"> <source>in Suppression File</source> <target state="translated">no Arquivo de Supressão</target> <note /> </trans-unit> <trans-unit id="Remove_Suppression_0"> <source>Remove Suppression {0}</source> <target state="translated">Remover a Supressão {0}</target> <note /> </trans-unit> <trans-unit id="Remove_Suppression"> <source>Remove Suppression</source> <target state="translated">Remover Supressão</target> <note /> </trans-unit> <trans-unit id="Pending"> <source>&lt;Pending&gt;</source> <target state="translated">&lt;Pendente&gt;</target> <note /> </trans-unit> <trans-unit id="Note_colon_Tab_twice_to_insert_the_0_snippet"> <source>Note: Tab twice to insert the '{0}' snippet.</source> <target state="translated">Observação: pressione Tab duas vezes para inserir o snippet '{0}'.</target> <note /> </trans-unit> <trans-unit id="Implement_interface_explicitly_with_Dispose_pattern"> <source>Implement interface explicitly with Dispose pattern</source> <target state="translated">Implementar interface explicitamente com Padrão de descarte</target> <note /> </trans-unit> <trans-unit id="Implement_interface_with_Dispose_pattern"> <source>Implement interface with Dispose pattern</source> <target state="translated">Implementar interface com Padrão de descarte</target> <note /> </trans-unit> <trans-unit id="Re_triage_0_currently_1"> <source>Re-triage {0}(currently '{1}')</source> <target state="translated">Fazer nova triagem de {0}(no momento, "{1}")</target> <note /> </trans-unit> <trans-unit id="Argument_cannot_have_a_null_element"> <source>Argument cannot have a null element.</source> <target state="translated">O argumento não pode ter um elemento nulo.</target> <note /> </trans-unit> <trans-unit id="Argument_cannot_be_empty"> <source>Argument cannot be empty.</source> <target state="translated">O argumento não pode estar vazio.</target> <note /> </trans-unit> <trans-unit id="Reported_diagnostic_with_ID_0_is_not_supported_by_the_analyzer"> <source>Reported diagnostic with ID '{0}' is not supported by the analyzer.</source> <target state="translated">O analisador não dá suporte ao diagnóstico relatado com ID '{0}'.</target> <note /> </trans-unit> <trans-unit id="Computing_fix_all_occurrences_code_fix"> <source>Computing fix all occurrences code fix...</source> <target state="translated">Computando a correção de todas as correções de código de ocorrências…</target> <note /> </trans-unit> <trans-unit id="Fix_all_occurrences"> <source>Fix all occurrences</source> <target state="translated">Corrigir todas as ocorrências</target> <note /> </trans-unit> <trans-unit id="Document"> <source>Document</source> <target state="translated">Documento</target> <note /> </trans-unit> <trans-unit id="Project"> <source>Project</source> <target state="translated">Projeto</target> <note /> </trans-unit> <trans-unit id="Solution"> <source>Solution</source> <target state="translated">Solução</target> <note /> </trans-unit> <trans-unit id="TODO_colon_dispose_managed_state_managed_objects"> <source>TODO: dispose managed state (managed objects)</source> <target state="new">TODO: dispose managed state (managed objects)</target> <note /> </trans-unit> <trans-unit id="TODO_colon_set_large_fields_to_null"> <source>TODO: set large fields to null</source> <target state="new">TODO: set large fields to null</target> <note /> </trans-unit> <trans-unit id="Compiler2"> <source>Compiler</source> <target state="translated">Compilador</target> <note /> </trans-unit> <trans-unit id="Live"> <source>Live</source> <target state="translated">Ao Vivo</target> <note /> </trans-unit> <trans-unit id="enum_value"> <source>enum value</source> <target state="translated">valor de enum</target> <note>{Locked="enum"} "enum" is a C#/VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="const_field"> <source>const field</source> <target state="translated">campo const</target> <note>{Locked="const"} "const" is a C#/VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="method"> <source>method</source> <target state="translated">método</target> <note /> </trans-unit> <trans-unit id="operator_"> <source>operator</source> <target state="translated">Operador</target> <note /> </trans-unit> <trans-unit id="constructor"> <source>constructor</source> <target state="translated">construtor</target> <note /> </trans-unit> <trans-unit id="auto_property"> <source>auto-property</source> <target state="translated">propriedade automática</target> <note /> </trans-unit> <trans-unit id="property_"> <source>property</source> <target state="translated">propriedade</target> <note /> </trans-unit> <trans-unit id="event_accessor"> <source>event accessor</source> <target state="translated">acessador de evento</target> <note /> </trans-unit> <trans-unit id="rfc1123_date_time"> <source>rfc1123 date/time</source> <target state="translated">data/hora rfc1123</target> <note /> </trans-unit> <trans-unit id="rfc1123_date_time_description"> <source>The "R" or "r" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.RFC1123Pattern property. The pattern reflects a defined standard, and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'". When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.</source> <target state="translated">O especificador de formato padrão "R" ou "r" representa uma cadeia de caracteres de formato de data e hora personalizado definida pela propriedade DateTimeFormatInfo.RFC1123Pattern. O padrão reflete um padrão definido e a propriedade é somente leitura. Portanto, é sempre o mesmo, independentemente da cultura usada ou do provedor de formato fornecido. A cadeia de caracteres de formato personalizado é "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'". Quando esse especificador de formato padrão é usado, a operação de análise ou formatação sempre usa a cultura invariável.</target> <note /> </trans-unit> <trans-unit id="round_trip_date_time"> <source>round-trip date/time</source> <target state="translated">data/hora de viagem de ida e volta</target> <note /> </trans-unit> <trans-unit id="round_trip_date_time_description"> <source>The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information and emits a result string that complies with ISO 8601. For DateTime values, this format specifier is designed to preserve date and time values along with the DateTime.Kind property in text. The formatted string can be parsed back by using the DateTime.Parse(String, IFormatProvider, DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set to DateTimeStyles.RoundtripKind. The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values. In this string, the pairs of single quotation marks that delimit individual characters, such as the hyphens, the colons, and the letter "T", indicate that the individual character is a literal that cannot be changed. The apostrophes do not appear in the output string. The "O" or "o" standard format specifier (and the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string) takes advantage of the three ways that ISO 8601 represents time zone information to preserve the Kind property of DateTime values: The time zone component of DateTimeKind.Local date and time values is an offset from UTC (for example, +01:00, -07:00). All DateTimeOffset values are also represented in this format. The time zone component of DateTimeKind.Utc date and time values uses "Z" (which stands for zero offset) to represent UTC. DateTimeKind.Unspecified date and time values have no time zone information. Because the "O" or "o" standard format specifier conforms to an international standard, the formatting or parsing operation that uses the specifier always uses the invariant culture and the Gregorian calendar. Strings that are passed to the Parse, TryParse, ParseExact, and TryParseExact methods of DateTime and DateTimeOffset can be parsed by using the "O" or "o" format specifier if they are in one of these formats. In the case of DateTime objects, the parsing overload that you call should also include a styles parameter with a value of DateTimeStyles.RoundtripKind. Note that if you call a parsing method with the custom format string that corresponds to the "O" or "o" format specifier, you won't get the same results as "O" or "o". This is because parsing methods that use a custom format string can't parse the string representation of date and time values that lack a time zone component or use "Z" to indicate UTC.</source> <target state="translated">O especificador de formato padrão "O" ou "o" representa uma cadeia de caracteres de formato de data e hora personalizado usando um padrão que preserva as informações de fuso horário e emite uma cadeia de resultado que está em conformidade com o ISO 8601. Para valores DateTime, esse especificador de formato é projetado para preservar valores de data e hora juntamente com a propriedade DateTime.Kind no texto. A cadeia de caracteres formatada poderá ser analisada novamente usando o método DateTime.Parse (String, IFormatProvider, DateTimeStyles) ou DateTime.ParseExact se o parâmetro styles estiver definido como DateTimeStyles.RoundtripKind. O especificador de formato padrão "O" ou "o" corresponde à cadeia de caracteres de formato personalizado "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" para valores DateTime e à cadeia de caracteres de formato personalizado "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" para valores de DateTimeOffset. Nessa cadeia de caracteres, os pares de aspas simples que delimitam caracteres individuais, como hifens, dois-pontos e a letra "T", indicam que o caractere individual é um literal que não pode ser alterado. Os apóstrofos não aparecem na cadeia de caracteres de saída. O especificador de formato padrão "O" ou "o" (e a cadeia de caracteres de formato personalizado "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK") aproveita as três maneiras pelas quais o ISO 8601 representa as informações de fuso horário para preservar a propriedade Kind dos valores DateTime: O componente de fuso horário de DateTimeKind.Local dos valores de data e hora é uma diferença do UTC (por exemplo, +01:00, -07:00). Todos os valores de DateTimeOffset também são representados nesse formato. O componente de fuso horário de DateTimeKind.Utc dos valores de data e hora usa "Z" (que significa diferença zero) para representar o UTC. Os valores de data e hora de DateTimeKind.Unspecified não especificados não têm informações de fuso horário. Como o especificador de formato padrão "O" ou "o" está em conformidade com um padrão internacional, a operação de formatação ou análise que usa o especificador sempre usa a cultura invariável e o calendário gregoriano. As cadeias de caracteres que são passadas para os métodos Parse, TryParse, ParseExact e TryParseExact de DateTime e DateTimeOffset podem ser analisadas usando o especificador de formato "O" ou "o" caso elas estejam em um desses formatos. No caso de objetos DateTime, a sobrecarga de análise que você chama também deve incluir um parâmetro styles com um valor de DateTimeStyles.RoundtripKind. Observe que, se você chamar um método de análise com a cadeia de caracteres de formato personalizado que corresponde ao especificador de formato "O" ou "o", você não obterá os mesmos resultados de "O" ou "o". Isso porque os métodos de análise que usam uma cadeia de caracteres de formato personalizado não podem analisar a representação de cadeia de caracteres dos valores de data e hora que não têm um componente de fuso horário ou usar "Z" para indicar o UTC.</target> <note /> </trans-unit> <trans-unit id="second_1_2_digits"> <source>second (1-2 digits)</source> <target state="translated">segundo (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="second_1_2_digits_description"> <source>The "s" custom format specifier represents the seconds as a number from 0 through 59. The result represents whole seconds that have passed since the last minute. A single-digit second is formatted without a leading zero. If the "s" format specifier is used without other custom format specifiers, it's interpreted as the "s" standard date and time format specifier.</source> <target state="translated">O especificador de formato personalizado "s" representa os segundos como um número de 0 a 59. O resultado representa segundos inteiros que passaram desde o último minuto. Um segundo de dígito único é formatado sem um zero à esquerda. Se o especificador de formato "s" for usado sem outros especificadores de formato personalizado, ele será interpretado como o especificador de formato de data e hora padrão "s".</target> <note /> </trans-unit> <trans-unit id="second_2_digits"> <source>second (2 digits)</source> <target state="translated">segundo (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="second_2_digits_description"> <source>The "ss" custom format specifier (plus any number of additional "s" specifiers) represents the seconds as a number from 00 through 59. The result represents whole seconds that have passed since the last minute. A single-digit second is formatted with a leading zero.</source> <target state="translated">O especificador de formato personalizado "ss" (mais qualquer número de especificadores "s" adicionais) representa os segundos como um número de 00 a 59. O resultado representa segundos inteiros que passaram desde o último minuto. Um segundo de dígito único é formatado com um zero à esquerda.</target> <note /> </trans-unit> <trans-unit id="short_date"> <source>short date</source> <target state="translated">data abreviada</target> <note /> </trans-unit> <trans-unit id="short_date_description"> <source>The "d" standard format specifier represents a custom date and time format string that is defined by a specific culture's DateTimeFormatInfo.ShortDatePattern property. For example, the custom format string that is returned by the ShortDatePattern property of the invariant culture is "MM/dd/yyyy".</source> <target state="translated">O especificador de formato padrão "d" representa uma cadeia de caracteres de formato personalizado de data e hora que é definida pela propriedade DateTimeFormatInfo.ShortDatePattern de uma cultura específica. Por exemplo, a cadeia de caracteres de formato personalizado retornada pela propriedade ShortDatePattern da cultura invariável é "MM/dd/yyyy".</target> <note /> </trans-unit> <trans-unit id="short_time"> <source>short time</source> <target state="translated">hora abreviada</target> <note /> </trans-unit> <trans-unit id="short_time_description"> <source>The "t" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.ShortTimePattern property. For example, the custom format string for the invariant culture is "HH:mm".</source> <target state="translated">O especificador de formato padrão "t" representa uma cadeia de caracteres de formato de data e hora personalizada que é definida pela propriedade DateTimeFormatInfo.ShortTimePattern atual. Por exemplo, a cadeia de caracteres de formato personalizado para a cultura invariável é "HH:mm".</target> <note /> </trans-unit> <trans-unit id="sortable_date_time"> <source>sortable date/time</source> <target state="translated">data/hora classificável</target> <note /> </trans-unit> <trans-unit id="sortable_date_time_description"> <source>The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard (ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss". The purpose of the "s" format specifier is to produce result strings that sort consistently in ascending or descending order based on date and time values. As a result, although the "s" standard format specifier represents a date and time value in a consistent format, the formatting operation does not modify the value of the date and time object that is being formatted to reflect its DateTime.Kind property or its DateTimeOffset.Offset value. For example, the result strings produced by formatting the date and time values 2014-11-15T18:32:17+00:00 and 2014-11-15T18:32:17+08:00 are identical. When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.</source> <target state="translated">O especificador de formato padrão "s" representa uma cadeia de caracteres de formato personalizado de data e hora que é definida pela propriedade DateTimeFormatInfo.SortableDateTimePattern. O padrão reflete um padrão definido (ISO 8601) e a propriedade é somente leitura. Portanto, é sempre o mesmo, independentemente da cultura usada ou do provedor de formato fornecido. A cadeia de caracteres de formato personalizado é "yyyy'-'MM'-'dd'T'HH':'mm':'ss". O objetivo do especificador de formato "s" é produzir cadeias de caracteres de resultado que são classificadas consistentemente em ordem crescente ou decrescente com base nos valores de data e hora. Como resultado, embora o especificador de formato padrão "s" represente um valor de data e hora em um formato consistente, a operação de formatação não modifica o valor do objeto de data e hora que está sendo formatado para refletir sua propriedade DateTime.Kind ou seu valor DateTimeOffset.Offset. Por exemplo, as cadeias de caracteres de resultado produzidas pela formatação dos valores de data e hora 2014-11-15T18:32:17+00:00 e 2014-11-15T18:32:17+08:00 são idênticas. Quando esse especificador de formato padrão é usado, a operação de análise ou formatação sempre usa a cultura invariável.</target> <note /> </trans-unit> <trans-unit id="static_constructor"> <source>static constructor</source> <target state="translated">construtor estático</target> <note /> </trans-unit> <trans-unit id="symbol_cannot_be_a_namespace"> <source>'symbol' cannot be a namespace.</source> <target state="translated">"símbolo" não pode ser um namespace.</target> <note /> </trans-unit> <trans-unit id="time_separator"> <source>time separator</source> <target state="translated">separador de hora</target> <note /> </trans-unit> <trans-unit id="time_separator_description"> <source>The ":" custom format specifier represents the time separator, which is used to differentiate hours, minutes, and seconds. The appropriate localized time separator is retrieved from the DateTimeFormatInfo.TimeSeparator property of the current or specified culture. Note: To change the time separator for a particular date and time string, specify the separator character within a literal string delimiter. For example, the custom format string hh'_'dd'_'ss produces a result string in which "_" (an underscore) is always used as the time separator. To change the time separator for all dates for a culture, either change the value of the DateTimeFormatInfo.TimeSeparator property of the current culture, or instantiate a DateTimeFormatInfo object, assign the character to its TimeSeparator property, and call an overload of the formatting method that includes an IFormatProvider parameter. If the ":" format specifier is used without other custom format specifiers, it's interpreted as a standard date and time format specifier and throws a FormatException.</source> <target state="translated">O especificador de formato personalizado ":" representa o separador de hora, que é usado para diferenciar horas, minutos e segundos. O separador de hora localizado apropriado é recuperado da propriedade DateTimeFormatInfo.TimeSeparator da cultura atual ou especificada. Observação: para alterar o separador de hora de uma determinada cadeia de caracteres de data e hora, especifique o caractere separador em um delimitador de cadeia de caracteres literal. Por exemplo, a cadeia de caracteres de formato personalizado hh'_'dd'_'ss produz uma cadeia de caracteres de resultado na qual "_" (um sublinhado) é sempre usado como o separador de hora. Para alterar o separador de hora para todas as datas para uma cultura, altere o valor da propriedade DateTimeFormatInfo.TimeSeparator da cultura atual ou crie uma instância de um objeto DateTimeFormatInfo, atribua o caractere à propriedade TimeSeparator e chame uma sobrecarga do método de formatação que inclui um parâmetro IFormatProvider. Se o especificador de formato ":" for usado sem outros especificadores de formato personalizado, ele será interpretado como um especificador de formato padrão de data e hora e gerará uma FormatException.</target> <note /> </trans-unit> <trans-unit id="time_zone"> <source>time zone</source> <target state="translated">fuso horário</target> <note /> </trans-unit> <trans-unit id="time_zone_description"> <source>The "K" custom format specifier represents the time zone information of a date and time value. When this format specifier is used with DateTime values, the result string is defined by the value of the DateTime.Kind property: For the local time zone (a DateTime.Kind property value of DateTimeKind.Local), this specifier is equivalent to the "zzz" specifier and produces a result string containing the local offset from Coordinated Universal Time (UTC); for example, "-07:00". For a UTC time (a DateTime.Kind property value of DateTimeKind.Utc), the result string includes a "Z" character to represent a UTC date. For a time from an unspecified time zone (a time whose DateTime.Kind property equals DateTimeKind.Unspecified), the result is equivalent to String.Empty. For DateTimeOffset values, the "K" format specifier is equivalent to the "zzz" format specifier, and produces a result string containing the DateTimeOffset value's offset from UTC. If the "K" format specifier is used without other custom format specifiers, it's interpreted as a standard date and time format specifier and throws a FormatException.</source> <target state="translated">O especificador de formato personalizado "K" representa as informações de fuso horário de um valor de data e hora. Quando esse especificador de formato é usado com valores DateTime, a cadeia de caracteres de resultado é definida pelo valor da propriedade DateTime.Kind: Para o fuso horário local (um valor da propriedade DateTime.Kind de DateTimeKind.Local), este especificador é equivalente ao especificador "zzz" e produz uma cadeia de caracteres de resultado contendo o deslocamento local do UTC (Tempo Universal Coordenado); por exemplo, "-07:00". Para uma hora UTC (um valor de propriedade DateTime.Kind de DateTimeKind.Utc), a cadeia de caracteres de resultado inclui um caractere "Z" para representar uma data UTC. Para um horário de um fuso horário não especificado (uma hora cuja propriedade DateTime.Kind seja igual a DateTimeKind.Unspecified), o resultado é equivalente a String.Empty. Para os valores de DateTimeOffset, o especificador de formato "K" é equivalente ao especificador de formato "zzz" e produz uma cadeia de caracteres de resultado contendo o deslocamento do valor de DateTimeOffset do UTC. Se o especificador de formato "K" for usado sem outros especificadores de formato personalizado, ele será interpretado como um especificador de formato padrão de data e hora e gerará uma FormatException.</target> <note /> </trans-unit> <trans-unit id="type"> <source>type</source> <target state="new">type</target> <note /> </trans-unit> <trans-unit id="type_constraint"> <source>type constraint</source> <target state="translated">restrição de tipo</target> <note /> </trans-unit> <trans-unit id="type_parameter"> <source>type parameter</source> <target state="translated">parâmetro de tipo</target> <note /> </trans-unit> <trans-unit id="attribute"> <source>attribute</source> <target state="translated">atributo</target> <note /> </trans-unit> <trans-unit id="Replace_0_and_1_with_property"> <source>Replace '{0}' and '{1}' with property</source> <target state="translated">Substituir "{0}" e "{1}" por propriedades</target> <note /> </trans-unit> <trans-unit id="Replace_0_with_property"> <source>Replace '{0}' with property</source> <target state="translated">Substituir "{0}" por uma propriedade</target> <note /> </trans-unit> <trans-unit id="Method_referenced_implicitly"> <source>Method referenced implicitly</source> <target state="translated">Método referenciado implicitamente</target> <note /> </trans-unit> <trans-unit id="Generate_type_0"> <source>Generate type '{0}'</source> <target state="translated">Gerar tipo '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_0_1"> <source>Generate {0} '{1}'</source> <target state="translated">Gerar {0} '{1}'</target> <note /> </trans-unit> <trans-unit id="Change_0_to_1"> <source>Change '{0}' to '{1}'.</source> <target state="translated">Alterar '{0}' para '{1}'.</target> <note /> </trans-unit> <trans-unit id="Non_invoked_method_cannot_be_replaced_with_property"> <source>Non-invoked method cannot be replaced with property.</source> <target state="translated">O método não invocado não pode ser substituído por uma propriedade.</target> <note /> </trans-unit> <trans-unit id="Only_methods_with_a_single_argument_which_is_not_an_out_variable_declaration_can_be_replaced_with_a_property"> <source>Only methods with a single argument, which is not an out variable declaration, can be replaced with a property.</source> <target state="translated">Somente os métodos com um único argumento, que não é uma declaração de variável externa, podem ser substituídos por uma propriedade.</target> <note /> </trans-unit> <trans-unit id="Roslyn_HostError"> <source>Roslyn.HostError</source> <target state="translated">Roslyn.HostError</target> <note /> </trans-unit> <trans-unit id="An_instance_of_analyzer_0_cannot_be_created_from_1_colon_2"> <source>An instance of analyzer {0} cannot be created from {1}: {2}.</source> <target state="translated">Uma instância do analisador de {0} não pode ser criada de {1} : {2}.</target> <note /> </trans-unit> <trans-unit id="The_assembly_0_does_not_contain_any_analyzers"> <source>The assembly {0} does not contain any analyzers.</source> <target state="translated">O assembly {0} não contém quaisquer analisadores.</target> <note /> </trans-unit> <trans-unit id="Unable_to_load_Analyzer_assembly_0_colon_1"> <source>Unable to load Analyzer assembly {0}: {1}</source> <target state="translated">Não é possível carregar o assembly do Analisador {0} : {1}</target> <note /> </trans-unit> <trans-unit id="Make_method_synchronous"> <source>Make method synchronous</source> <target state="translated">Tornar o método síncrono</target> <note /> </trans-unit> <trans-unit id="from_0"> <source>from {0}</source> <target state="translated">de {0}</target> <note /> </trans-unit> <trans-unit id="Find_and_install_latest_version"> <source>Find and install latest version</source> <target state="translated">Localizar e instalar a versão mais recente</target> <note /> </trans-unit> <trans-unit id="Use_local_version_0"> <source>Use local version '{0}'</source> <target state="translated">Usar a versão local '{0}'</target> <note /> </trans-unit> <trans-unit id="Use_locally_installed_0_version_1_This_version_used_in_colon_2"> <source>Use locally installed '{0}' version '{1}' This version used in: {2}</source> <target state="translated">Use a versão '{0}' instalada localmente '{1}' Essa versão é usada no: {2}</target> <note /> </trans-unit> <trans-unit id="Find_and_install_latest_version_of_0"> <source>Find and install latest version of '{0}'</source> <target state="translated">Localizar e instalar a versão mais recente de '{0}'</target> <note /> </trans-unit> <trans-unit id="Install_with_package_manager"> <source>Install with package manager...</source> <target state="translated">Instalar com o gerenciador de pacotes...</target> <note /> </trans-unit> <trans-unit id="Install_0_1"> <source>Install '{0} {1}'</source> <target state="translated">Instalar '{0} {1}'</target> <note /> </trans-unit> <trans-unit id="Install_version_0"> <source>Install version '{0}'</source> <target state="translated">Instalar a versão '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_variable_0"> <source>Generate variable '{0}'</source> <target state="translated">Gerar variável '{0}'</target> <note /> </trans-unit> <trans-unit id="Classes"> <source>Classes</source> <target state="translated">Classes</target> <note /> </trans-unit> <trans-unit id="Constants"> <source>Constants</source> <target state="translated">Constantes</target> <note /> </trans-unit> <trans-unit id="Delegates"> <source>Delegates</source> <target state="translated">Delega</target> <note /> </trans-unit> <trans-unit id="Enums"> <source>Enums</source> <target state="translated">Enums</target> <note /> </trans-unit> <trans-unit id="Events"> <source>Events</source> <target state="translated">Eventos</target> <note /> </trans-unit> <trans-unit id="Extension_methods"> <source>Extension methods</source> <target state="translated">Métodos de extensão</target> <note /> </trans-unit> <trans-unit id="Fields"> <source>Fields</source> <target state="translated">Campos</target> <note /> </trans-unit> <trans-unit id="Interfaces"> <source>Interfaces</source> <target state="translated">Interfaces</target> <note /> </trans-unit> <trans-unit id="Locals"> <source>Locals</source> <target state="translated">Locais</target> <note /> </trans-unit> <trans-unit id="Methods"> <source>Methods</source> <target state="translated">Métodos</target> <note /> </trans-unit> <trans-unit id="Modules"> <source>Modules</source> <target state="translated">Módulos</target> <note /> </trans-unit> <trans-unit id="Namespaces"> <source>Namespaces</source> <target state="translated">Namespaces</target> <note /> </trans-unit> <trans-unit id="Properties"> <source>Properties</source> <target state="translated">Propriedades</target> <note /> </trans-unit> <trans-unit id="Structures"> <source>Structures</source> <target state="translated">Estruturas</target> <note /> </trans-unit> <trans-unit id="Parameters_colon"> <source>Parameters:</source> <target state="translated">Parâmetros:</target> <note /> </trans-unit> <trans-unit id="Variadic_SignatureHelpItem_must_have_at_least_one_parameter"> <source>Variadic SignatureHelpItem must have at least one parameter.</source> <target state="translated">Variadic SignatureHelpItem deve ter pelo menos um parâmetro.</target> <note /> </trans-unit> <trans-unit id="Replace_0_with_method"> <source>Replace '{0}' with method</source> <target state="translated">Substituir '{0}' com método</target> <note /> </trans-unit> <trans-unit id="Replace_0_with_methods"> <source>Replace '{0}' with methods</source> <target state="translated">Substituir '{0}' com métodos</target> <note /> </trans-unit> <trans-unit id="Property_referenced_implicitly"> <source>Property referenced implicitly</source> <target state="translated">Propriedade referenciada implicitamente</target> <note /> </trans-unit> <trans-unit id="Property_cannot_safely_be_replaced_with_a_method_call"> <source>Property cannot safely be replaced with a method call</source> <target state="translated">A propriedade não pode ser substituída com segurança com uma chamada de método</target> <note /> </trans-unit> <trans-unit id="Convert_to_interpolated_string"> <source>Convert to interpolated string</source> <target state="translated">Converter para cadeia de caracteres interpolada</target> <note /> </trans-unit> <trans-unit id="Move_type_to_0"> <source>Move type to {0}</source> <target state="translated">Mover tipo para {0}</target> <note /> </trans-unit> <trans-unit id="Rename_file_to_0"> <source>Rename file to {0}</source> <target state="translated">Renomear arquivo para {0}</target> <note /> </trans-unit> <trans-unit id="Rename_type_to_0"> <source>Rename type to {0}</source> <target state="translated">Renomear tipo para {0}</target> <note /> </trans-unit> <trans-unit id="Remove_tag"> <source>Remove tag</source> <target state="translated">Remover tag</target> <note /> </trans-unit> <trans-unit id="Add_missing_param_nodes"> <source>Add missing param nodes</source> <target state="translated">Adicionar nós de parâmetro ausentes</target> <note /> </trans-unit> <trans-unit id="Make_containing_scope_async"> <source>Make containing scope async</source> <target state="translated">Tornar o escopo contentor assíncrono</target> <note /> </trans-unit> <trans-unit id="Make_containing_scope_async_return_Task"> <source>Make containing scope async (return Task)</source> <target state="translated">Tornar o escopo contentor assíncrono (retornar Task)</target> <note /> </trans-unit> <trans-unit id="paren_Unknown_paren"> <source>(Unknown)</source> <target state="translated">(Desconhecido)</target> <note /> </trans-unit> <trans-unit id="Use_framework_type"> <source>Use framework type</source> <target state="translated">Usar o tipo de estrutura</target> <note /> </trans-unit> <trans-unit id="Install_package_0"> <source>Install package '{0}'</source> <target state="translated">Instalar o pacote '{0}'</target> <note /> </trans-unit> <trans-unit id="project_0"> <source>project {0}</source> <target state="translated">projeto {0}</target> <note /> </trans-unit> <trans-unit id="Fully_qualify_0"> <source>Fully qualify '{0}'</source> <target state="translated">Qualificar '{0}' totalmente</target> <note /> </trans-unit> <trans-unit id="Remove_reference_to_0"> <source>Remove reference to '{0}'.</source> <target state="translated">Remova a referência a '{0}'.</target> <note /> </trans-unit> <trans-unit id="Keywords"> <source>Keywords</source> <target state="translated">Palavras-chave</target> <note /> </trans-unit> <trans-unit id="Snippets"> <source>Snippets</source> <target state="translated">Snippets</target> <note /> </trans-unit> <trans-unit id="All_lowercase"> <source>All lowercase</source> <target state="translated">Tudo em minúsculas</target> <note /> </trans-unit> <trans-unit id="All_uppercase"> <source>All uppercase</source> <target state="translated">Tudo em maiúsculas</target> <note /> </trans-unit> <trans-unit id="First_word_capitalized"> <source>First word capitalized</source> <target state="translated">Primeira palavra em maiúsculas</target> <note /> </trans-unit> <trans-unit id="Pascal_Case"> <source>Pascal Case</source> <target state="translated">Pascal Case</target> <note /> </trans-unit> <trans-unit id="Remove_document_0"> <source>Remove document '{0}'</source> <target state="translated">Remover documento '{0}'</target> <note /> </trans-unit> <trans-unit id="Add_document_0"> <source>Add document '{0}'</source> <target state="translated">Adicionar documento '{0}'</target> <note /> </trans-unit> <trans-unit id="Add_argument_name_0"> <source>Add argument name '{0}'</source> <target state="translated">Adicionar nome de argumento '{0}'</target> <note /> </trans-unit> <trans-unit id="Take_0"> <source>Take '{0}'</source> <target state="translated">Obter '{0}'</target> <note /> </trans-unit> <trans-unit id="Take_both"> <source>Take both</source> <target state="translated">Obter ambos</target> <note /> </trans-unit> <trans-unit id="Take_bottom"> <source>Take bottom</source> <target state="translated">Obter inferior</target> <note /> </trans-unit> <trans-unit id="Take_top"> <source>Take top</source> <target state="translated">Obter superior</target> <note /> </trans-unit> <trans-unit id="Remove_unused_variable"> <source>Remove unused variable</source> <target state="translated">Remover variável não usada</target> <note /> </trans-unit> <trans-unit id="Convert_to_binary"> <source>Convert to binary</source> <target state="translated">Converter em binário</target> <note /> </trans-unit> <trans-unit id="Convert_to_decimal"> <source>Convert to decimal</source> <target state="translated">Converter em decimal</target> <note /> </trans-unit> <trans-unit id="Convert_to_hex"> <source>Convert to hex</source> <target state="translated">Converter para hexa</target> <note /> </trans-unit> <trans-unit id="Separate_thousands"> <source>Separate thousands</source> <target state="translated">Separar milhares</target> <note /> </trans-unit> <trans-unit id="Separate_words"> <source>Separate words</source> <target state="translated">Separar palavras</target> <note /> </trans-unit> <trans-unit id="Separate_nibbles"> <source>Separate nibbles</source> <target state="translated">Separar nibbles</target> <note /> </trans-unit> <trans-unit id="Remove_separators"> <source>Remove separators</source> <target state="translated">Remover separadores</target> <note /> </trans-unit> <trans-unit id="Add_parameter_to_0"> <source>Add parameter to '{0}'</source> <target state="translated">Adicionar parâmetro ao '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_constructor"> <source>Generate constructor...</source> <target state="translated">Gerar construtor...</target> <note /> </trans-unit> <trans-unit id="Pick_members_to_be_used_as_constructor_parameters"> <source>Pick members to be used as constructor parameters</source> <target state="translated">Escolher membros para que sejam usados como parâmetros do construtor</target> <note /> </trans-unit> <trans-unit id="Pick_members_to_be_used_in_Equals_GetHashCode"> <source>Pick members to be used in Equals/GetHashCode</source> <target state="translated">Escolher membros para que sejam usados em Equals/GetHashCode</target> <note /> </trans-unit> <trans-unit id="Generate_overrides"> <source>Generate overrides...</source> <target state="translated">Gerar substituições...</target> <note /> </trans-unit> <trans-unit id="Pick_members_to_override"> <source>Pick members to override</source> <target state="translated">Escolher membros para substituir</target> <note /> </trans-unit> <trans-unit id="Add_null_check"> <source>Add null check</source> <target state="translated">Adicionar verificação nula</target> <note /> </trans-unit> <trans-unit id="Add_string_IsNullOrEmpty_check"> <source>Add 'string.IsNullOrEmpty' check</source> <target state="translated">Adicionar a verificação 'string.IsNullOrEmpty'</target> <note /> </trans-unit> <trans-unit id="Add_string_IsNullOrWhiteSpace_check"> <source>Add 'string.IsNullOrWhiteSpace' check</source> <target state="translated">Adicionar a verificação 'string.IsNullOrWhiteSpace'</target> <note /> </trans-unit> <trans-unit id="Initialize_field_0"> <source>Initialize field '{0}'</source> <target state="translated">Inicializar campo '{0}'</target> <note /> </trans-unit> <trans-unit id="Initialize_property_0"> <source>Initialize property '{0}'</source> <target state="translated">Inicializar propriedade '{0}'</target> <note /> </trans-unit> <trans-unit id="Add_null_checks"> <source>Add null checks</source> <target state="translated">Adicionar verificações nulas</target> <note /> </trans-unit> <trans-unit id="Generate_operators"> <source>Generate operators</source> <target state="translated">Gerar operadores</target> <note /> </trans-unit> <trans-unit id="Implement_0"> <source>Implement {0}</source> <target state="translated">Implementar {0}</target> <note /> </trans-unit> <trans-unit id="Reported_diagnostic_0_has_a_source_location_in_file_1_which_is_not_part_of_the_compilation_being_analyzed"> <source>Reported diagnostic '{0}' has a source location in file '{1}', which is not part of the compilation being analyzed.</source> <target state="translated">O diagnóstico relatado '{0}' tem um local de origem no arquivo '{1}', que não faz parte da compilação sendo analisada.</target> <note /> </trans-unit> <trans-unit id="Reported_diagnostic_0_has_a_source_location_1_in_file_2_which_is_outside_of_the_given_file"> <source>Reported diagnostic '{0}' has a source location '{1}' in file '{2}', which is outside of the given file.</source> <target state="translated">O diagnóstico relatado '{0}' tem um local de origem '{1}' no arquivo '{2}', que está fora do arquivo fornecido.</target> <note /> </trans-unit> <trans-unit id="in_0_project_1"> <source>in {0} (project {1})</source> <target state="translated">em {0} (projeto {1})</target> <note /> </trans-unit> <trans-unit id="Add_accessibility_modifiers"> <source>Add accessibility modifiers</source> <target state="translated">Adicionar modificadores de acessibilidade</target> <note /> </trans-unit> <trans-unit id="Move_declaration_near_reference"> <source>Move declaration near reference</source> <target state="translated">Mover declaração para próximo da referência</target> <note /> </trans-unit> <trans-unit id="Convert_to_full_property"> <source>Convert to full property</source> <target state="translated">Converter em propriedade completa</target> <note /> </trans-unit> <trans-unit id="Warning_Method_overrides_symbol_from_metadata"> <source>Warning: Method overrides symbol from metadata</source> <target state="translated">Aviso: o método substitui o símbolo de metadados</target> <note /> </trans-unit> <trans-unit id="Use_0"> <source>Use {0}</source> <target state="translated">Usar {0}</target> <note /> </trans-unit> <trans-unit id="Add_argument_name_0_including_trailing_arguments"> <source>Add argument name '{0}' (including trailing arguments)</source> <target state="translated">Adicionar nome de argumento '{0}' (incluindo argumentos à direita)</target> <note /> </trans-unit> <trans-unit id="local_function"> <source>local function</source> <target state="translated">função local</target> <note /> </trans-unit> <trans-unit id="indexer_"> <source>indexer</source> <target state="translated">indexador</target> <note /> </trans-unit> <trans-unit id="Alias_ambiguous_type_0"> <source>Alias ambiguous type '{0}'</source> <target state="translated">Tipo de alias ambíguo '{0}'</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Collection_was_modified_during_iteration"> <source>Warning: Collection was modified during iteration.</source> <target state="translated">Aviso: a coleção foi modificada durante a iteração.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Iteration_variable_crossed_function_boundary"> <source>Warning: Iteration variable crossed function boundary.</source> <target state="translated">Aviso: a variável de iteração passou o limite da função.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Collection_may_be_modified_during_iteration"> <source>Warning: Collection may be modified during iteration.</source> <target state="translated">Aviso: a coleção pode ser modificada durante a iteração.</target> <note /> </trans-unit> <trans-unit id="universal_full_date_time"> <source>universal full date/time</source> <target state="translated">data/hora universal por extenso</target> <note /> </trans-unit> <trans-unit id="universal_full_date_time_description"> <source>The "U" standard format specifier represents a custom date and time format string that is defined by a specified culture's DateTimeFormatInfo.FullDateTimePattern property. The pattern is the same as the "F" pattern. However, the DateTime value is automatically converted to UTC before it is formatted.</source> <target state="translated">O especificador de formato padrão "U" representa uma cadeia de caracteres de formato personalizado de data e hora que é definida pela propriedade DateTimeFormatInfo.FullDateTimePattern de uma cultura especificada. O padrão é o mesmo que o padrão "F". No entanto, o valor DateTime é convertido automaticamente para UTC antes de ser formatado.</target> <note /> </trans-unit> <trans-unit id="universal_sortable_date_time"> <source>universal sortable date/time</source> <target state="translated">data/hora universal classificável</target> <note /> </trans-unit> <trans-unit id="universal_sortable_date_time_description"> <source>The "u" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.UniversalSortableDateTimePattern property. The pattern reflects a defined standard, and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd HH':'mm':'ss'Z'". When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture. Although the result string should express a time as Coordinated Universal Time (UTC), no conversion of the original DateTime value is performed during the formatting operation. Therefore, you must convert a DateTime value to UTC by calling the DateTime.ToUniversalTime method before formatting it.</source> <target state="translated">O especificador de formato padrão "u" representa uma cadeia de caracteres de formato personalizado de data e hora que é definida pela propriedade DateTimeFormatInfo.UniversalSortableDateTimePattern. O padrão reflete um padrão definido e a propriedade é somente leitura. Portanto, é sempre o mesmo, independentemente da cultura usada ou do provedor de formato fornecido. A cadeia de caracteres de formato personalizado é "yyyy'-'MM'-'dd HH':'mm':'ss'Z'". Quando esse especificador de formato padrão é usado, a operação de análise ou formatação sempre usa a cultura invariável. Embora a cadeia de caracteres de resultado deva expressar um horário como UTC (Tempo Universal Coordenado), nenhuma conversão do valor original DateTime é executada durante a operação de formatação. Portanto, você precisa converter um valor DateTime para UTC chamando o método DateTime.ToUniversalTime antes de formatá-lo.</target> <note /> </trans-unit> <trans-unit id="updating_usages_in_containing_member"> <source>updating usages in containing member</source> <target state="translated">atualizando os usos em contém membros</target> <note /> </trans-unit> <trans-unit id="updating_usages_in_containing_project"> <source>updating usages in containing project</source> <target state="translated">usos em que contém o projeto de atualização</target> <note /> </trans-unit> <trans-unit id="updating_usages_in_containing_type"> <source>updating usages in containing type</source> <target state="translated">usos em que contém o tipo de atualização</target> <note /> </trans-unit> <trans-unit id="updating_usages_in_dependent_projects"> <source>updating usages in dependent projects</source> <target state="translated">atualizar usos em projetos dependentes</target> <note /> </trans-unit> <trans-unit id="utc_hour_and_minute_offset"> <source>utc hour and minute offset</source> <target state="translated">diferença de hora e minuto UTC</target> <note /> </trans-unit> <trans-unit id="utc_hour_and_minute_offset_description"> <source>With DateTime values, the "zzz" custom format specifier represents the signed offset of the local operating system's time zone from UTC, measured in hours and minutes. It doesn't reflect the value of an instance's DateTime.Kind property. For this reason, the "zzz" format specifier is not recommended for use with DateTime values. With DateTimeOffset values, this format specifier represents the DateTimeOffset value's offset from UTC in hours and minutes. The offset is always displayed with a leading sign. A plus sign (+) indicates hours ahead of UTC, and a minus sign (-) indicates hours behind UTC. A single-digit offset is formatted with a leading zero.</source> <target state="translated">Com os valores DateTime, o especificador de formato personalizado "ZZZ" representa o deslocamento assinado do fuso horário do sistema operacional local do UTC, medido em horas e minutos. Ele não reflete o valor da propriedade DateTime.Kind de uma instância. Por esse motivo, o especificador de formato "ZZZ" não é recomendado para uso com valores DateTime. Com os valores de DateTimeOffset, este especificador de formato representa o deslocamento do valor de DateTimeOffset do UTC em horas e minutos. O deslocamento é sempre exibido com um sinal à esquerda. Um sinal de adição (+) indica horas à frente do UTC e um sinal de subtração (-) indica horas atrás do UTC. Um deslocamento de dígito único é formatado com um zero à esquerda.</target> <note /> </trans-unit> <trans-unit id="utc_hour_offset_1_2_digits"> <source>utc hour offset (1-2 digits)</source> <target state="translated">diferença horária UTC (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="utc_hour_offset_1_2_digits_description"> <source>With DateTime values, the "z" custom format specifier represents the signed offset of the local operating system's time zone from Coordinated Universal Time (UTC), measured in hours. It doesn't reflect the value of an instance's DateTime.Kind property. For this reason, the "z" format specifier is not recommended for use with DateTime values. With DateTimeOffset values, this format specifier represents the DateTimeOffset value's offset from UTC in hours. The offset is always displayed with a leading sign. A plus sign (+) indicates hours ahead of UTC, and a minus sign (-) indicates hours behind UTC. A single-digit offset is formatted without a leading zero. If the "z" format specifier is used without other custom format specifiers, it's interpreted as a standard date and time format specifier and throws a FormatException.</source> <target state="translated">Com valores DateTime, o especificador de formato personalizado "z" representa o deslocamento assinado do fuso horário do sistema operacional local do UTC (Tempo Universal Coordenado), medido em horas. Ele não reflete o valor da propriedade DateTime.Kind de uma instância. Por esse motivo, o especificador de formato "z" não é recomendado para uso com valores DateTime. Com os valores de DateTimeOffset, este especificador de formato representa o deslocamento do valor de DateTimeOffset do UTC em horas. O deslocamento é sempre exibido com um sinal à esquerda. Um sinal de adição (+) indica horas à frente do UTC e um sinal de subtração (-) indica horas atrás do UTC. Um deslocamento de dígito único é formatado sem um zero à esquerda. Se o especificador de formato "z" for usado sem outros especificadores de formato personalizado, ele será interpretado como um especificador de formato padrão de data e hora e gerará uma FormatException.</target> <note /> </trans-unit> <trans-unit id="utc_hour_offset_2_digits"> <source>utc hour offset (2 digits)</source> <target state="translated">diferença horária UTC (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="utc_hour_offset_2_digits_description"> <source>With DateTime values, the "zz" custom format specifier represents the signed offset of the local operating system's time zone from UTC, measured in hours. It doesn't reflect the value of an instance's DateTime.Kind property. For this reason, the "zz" format specifier is not recommended for use with DateTime values. With DateTimeOffset values, this format specifier represents the DateTimeOffset value's offset from UTC in hours. The offset is always displayed with a leading sign. A plus sign (+) indicates hours ahead of UTC, and a minus sign (-) indicates hours behind UTC. A single-digit offset is formatted with a leading zero.</source> <target state="translated">Com valores DateTime, o especificador de formato personalizado "zz" representa o deslocamento assinado do fuso horário do sistema operacional local do UTC, medido em horas. Ele não reflete o valor da propriedade DateTime.Kind de uma instância. Por esse motivo, o especificador de formato "zz" não é recomendado para uso com valores DateTime. Com os valores de DateTimeOffset, este especificador de formato representa o deslocamento do valor de DateTimeOffset do UTC em horas. O deslocamento é sempre exibido com um sinal à esquerda. Um sinal de adição (+) indica horas à frente do UTC e um sinal de subtração (-) indica horas atrás do UTC. Um deslocamento de dígito único é formatado com um zero à esquerda.</target> <note /> </trans-unit> <trans-unit id="x_y_range_in_reverse_order"> <source>[x-y] range in reverse order</source> <target state="translated">intervalo [x-y] em ordem inversa</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: [b-a]</note> </trans-unit> <trans-unit id="year_1_2_digits"> <source>year (1-2 digits)</source> <target state="translated">ano (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="year_1_2_digits_description"> <source>The "y" custom format specifier represents the year as a one-digit or two-digit number. If the year has more than two digits, only the two low-order digits appear in the result. If the first digit of a two-digit year begins with a zero (for example, 2008), the number is formatted without a leading zero. If the "y" format specifier is used without other custom format specifiers, it's interpreted as the "y" standard date and time format specifier.</source> <target state="translated">O especificador de formato personalizado "y" representa o ano como um número de um ou dois dígitos. Se o ano tiver mais de dois dígitos, somente os dois dígitos de ordem baixa aparecerão no resultado. Se o primeiro dígito de um ano de dois dígitos começar com zero (por exemplo, 2008), o número será formatado sem um zero à esquerda. Se o especificador de formato "y" for usado sem outros especificadores de formato personalizado, ele será interpretado como o especificador de formato padrão de data e hora "y".</target> <note /> </trans-unit> <trans-unit id="year_2_digits"> <source>year (2 digits)</source> <target state="translated">ano (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="year_2_digits_description"> <source>The "yy" custom format specifier represents the year as a two-digit number. If the year has more than two digits, only the two low-order digits appear in the result. If the two-digit year has fewer than two significant digits, the number is padded with leading zeros to produce two digits. In a parsing operation, a two-digit year that is parsed using the "yy" custom format specifier is interpreted based on the Calendar.TwoDigitYearMax property of the format provider's current calendar. The following example parses the string representation of a date that has a two-digit year by using the default Gregorian calendar of the en-US culture, which, in this case, is the current culture. It then changes the current culture's CultureInfo object to use a GregorianCalendar object whose TwoDigitYearMax property has been modified.</source> <target state="translated">O especificador de formato personalizado "yy" representa o ano como um número de dois dígitos. Se o ano tiver mais de dois dígitos, somente os dois dígitos de ordem baixa aparecerão no resultado. Se o ano de dois dígitos tiver menos de dois dígitos significativos, o número será preenchido com zeros à esquerda para produzir dois dígitos. Em uma operação de análise, um ano de dois dígitos analisado usando o especificador de formato personalizado "yy" é interpretado com base na Propriedade Calendar.TwoDigitYearMax do calendário atual do provedor de formato. O exemplo a seguir analisa a representação de cadeia de caracteres de uma data que tem um ano de dois dígitos usando o calendário gregoriano padrão da cultura en-US, que, neste caso, é a cultura atual. Em seguida, altera o objeto CultureInfo da cultura atual para usar um objeto GregorianCalendar cuja propriedade TwoDigitYearMax foi modificada.</target> <note /> </trans-unit> <trans-unit id="year_3_4_digits"> <source>year (3-4 digits)</source> <target state="translated">ano (3-4 dígitos)</target> <note /> </trans-unit> <trans-unit id="year_3_4_digits_description"> <source>The "yyy" custom format specifier represents the year with a minimum of three digits. If the year has more than three significant digits, they are included in the result string. If the year has fewer than three digits, the number is padded with leading zeros to produce three digits.</source> <target state="translated">O especificador de formato personalizado "yyy" representa o ano com um mínimo de três dígitos. Se o ano tiver mais de três dígitos significativos, eles serão incluídos na cadeia de caracteres de resultado. Se o ano tiver menos de três dígitos, o número será preenchido com zeros à esquerda para produzir três dígitos.</target> <note /> </trans-unit> <trans-unit id="year_4_digits"> <source>year (4 digits)</source> <target state="translated">ano (4 dígitos)</target> <note /> </trans-unit> <trans-unit id="year_4_digits_description"> <source>The "yyyy" custom format specifier represents the year with a minimum of four digits. If the year has more than four significant digits, they are included in the result string. If the year has fewer than four digits, the number is padded with leading zeros to produce four digits.</source> <target state="translated">O especificador de formato personalizado "yyyy" representa o ano com um mínimo de quatro dígitos. Se o ano tiver mais de quatro dígitos significativos, eles serão incluídos na cadeia de caracteres de resultado. Se o ano tiver menos de quatro dígitos, o número será preenchido com zeros à esquerda para produzir quatro dígitos.</target> <note /> </trans-unit> <trans-unit id="year_5_digits"> <source>year (5 digits)</source> <target state="translated">ano (5 dígitos)</target> <note /> </trans-unit> <trans-unit id="year_5_digits_description"> <source>The "yyyyy" custom format specifier (plus any number of additional "y" specifiers) represents the year with a minimum of five digits. If the year has more than five significant digits, they are included in the result string. If the year has fewer than five digits, the number is padded with leading zeros to produce five digits. If there are additional "y" specifiers, the number is padded with as many leading zeros as necessary to produce the number of "y" specifiers.</source> <target state="translated">O especificador de formato personalizado "yyyyy" (mais qualquer número de especificadores "y" adicionais) representa o ano com um mínimo de cinco dígitos. Se o ano tiver mais de cinco dígitos significativos, eles serão incluídos na cadeia de caracteres de resultado. Se o ano tiver menos de cinco dígitos, o número será preenchido com zeros à esquerda para produzir cinco dígitos. Se houver especificadores "y" adicionais, o número será preenchido com quantos zeros à esquerda forem necessários para produzir o número de especificadores "y".</target> <note /> </trans-unit> <trans-unit id="year_month"> <source>year month</source> <target state="translated">mês do ano</target> <note /> </trans-unit> <trans-unit id="year_month_description"> <source>The "Y" or "y" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.YearMonthPattern property of a specified culture. For example, the custom format string for the invariant culture is "yyyy MMMM".</source> <target state="translated">O especificador de formato padrão "Y" ou "y" representa uma cadeia de caracteres de formato de data e hora personalizado definida pela propriedade DateTimeFormatInfo.YearMonthPattern de uma cultura especificada. Por exemplo, a cadeia de caracteres de formato personalizado para a cultura invariável é "yyyy MMMM".</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pt-BR" original="../FeaturesResources.resx"> <body> <trans-unit id="0_directive"> <source>#{0} directive</source> <target state="new">#{0} directive</target> <note /> </trans-unit> <trans-unit id="AM_PM_abbreviated"> <source>AM/PM (abbreviated)</source> <target state="translated">AM/PM (abreviado)</target> <note /> </trans-unit> <trans-unit id="AM_PM_abbreviated_description"> <source>The "t" custom format specifier represents the first character of the AM/PM designator. The appropriate localized designator is retrieved from the DateTimeFormatInfo.AMDesignator or DateTimeFormatInfo.PMDesignator property of the current or specific culture. The AM designator is used for all times from 0:00:00 (midnight) to 11:59:59.999. The PM designator is used for all times from 12:00:00 (noon) to 23:59:59.999. If the "t" format specifier is used without other custom format specifiers, it's interpreted as the "t" standard date and time format specifier.</source> <target state="translated">O especificador de formato personalizado "t" representa o primeiro caractere do designador AM/PM. O designador localizado apropriado é recuperado da propriedade DateTimeFormatInfo.AMDesignator ou DateTimeFormatInfo.PMDesignator da cultura atual ou específica. O designador AM é usado para todos os horários de 0:00:00 (meia-noite) até 11:59:59.999. O designador PM é usado para todos os horários de 12:00:00 (meio-dia) para 23:59:59.999. Se o especificador de formato "t" for usado sem outros especificadores de formato personalizado, ele será interpretado como o especificador de formato padrão de data e hora "t".</target> <note /> </trans-unit> <trans-unit id="AM_PM_full"> <source>AM/PM (full)</source> <target state="translated">AM/PM (completo)</target> <note /> </trans-unit> <trans-unit id="AM_PM_full_description"> <source>The "tt" custom format specifier (plus any number of additional "t" specifiers) represents the entire AM/PM designator. The appropriate localized designator is retrieved from the DateTimeFormatInfo.AMDesignator or DateTimeFormatInfo.PMDesignator property of the current or specific culture. The AM designator is used for all times from 0:00:00 (midnight) to 11:59:59.999. The PM designator is used for all times from 12:00:00 (noon) to 23:59:59.999. Make sure to use the "tt" specifier for languages for which it's necessary to maintain the distinction between AM and PM. An example is Japanese, for which the AM and PM designators differ in the second character instead of the first character.</source> <target state="translated">O especificador de formato personalizado "tt" (mais qualquer número de especificadores "t" adicionais) representa todo o designador AM/PM. O designador localizado apropriado é recuperado da propriedade DateTimeFormatInfo.AMDesignator ou DateTimeFormatInfo.PMDesignator da cultura atual ou específica. O designador AM é usado para todos os horários de 0:00:00 (meia-noite) até 11:59:59.999. O designador PM é usado para todos os horários de 12:00:00 (meio-dia) até 23:59:59.999. Verifique se o especificador "tt" foi usado para idiomas para os quais é necessário manter a distinção entre AM e PM. Um exemplo é o japonês, para o qual os designadores AM e PM diferem no segundo caractere, em vez de no primeiro caractere.</target> <note /> </trans-unit> <trans-unit id="A_subtraction_must_be_the_last_element_in_a_character_class"> <source>A subtraction must be the last element in a character class</source> <target state="translated">Uma subtração deve ser o último elemento em uma classe de caracteres</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: [a-[b]-c]</note> </trans-unit> <trans-unit id="Accessing_captured_variable_0_that_hasn_t_been_accessed_before_in_1_requires_restarting_the_application"> <source>Accessing captured variable '{0}' that hasn't been accessed before in {1} requires restarting the application.</source> <target state="new">Accessing captured variable '{0}' that hasn't been accessed before in {1} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Add_DebuggerDisplay_attribute"> <source>Add 'DebuggerDisplay' attribute</source> <target state="translated">Adicionar atributo 'DebuggerDisplay'</target> <note>{Locked="DebuggerDisplay"} "DebuggerDisplay" is a BCL class and should not be localized.</note> </trans-unit> <trans-unit id="Add_explicit_cast"> <source>Add explicit cast</source> <target state="translated">Adicionar conversão explícita</target> <note /> </trans-unit> <trans-unit id="Add_member_name"> <source>Add member name</source> <target state="translated">Adicionar o nome do membro</target> <note /> </trans-unit> <trans-unit id="Add_null_checks_for_all_parameters"> <source>Add null checks for all parameters</source> <target state="translated">Adicionar verificações nulas para todos os parâmetros</target> <note /> </trans-unit> <trans-unit id="Add_optional_parameter_to_constructor"> <source>Add optional parameter to constructor</source> <target state="translated">Adicionar parâmetro opcional ao construtor</target> <note /> </trans-unit> <trans-unit id="Add_parameter_to_0_and_overrides_implementations"> <source>Add parameter to '{0}' (and overrides/implementations)</source> <target state="translated">Adicionar parâmetro ao '{0}' (e substituições/implementações)</target> <note /> </trans-unit> <trans-unit id="Add_parameter_to_constructor"> <source>Add parameter to constructor</source> <target state="translated">Adicionar parâmetro ao construtor</target> <note /> </trans-unit> <trans-unit id="Add_project_reference_to_0"> <source>Add project reference to '{0}'.</source> <target state="translated">Adicione referência de projeto a "{0}".</target> <note /> </trans-unit> <trans-unit id="Add_reference_to_0"> <source>Add reference to '{0}'.</source> <target state="translated">Adicione referência a "{0}".</target> <note /> </trans-unit> <trans-unit id="Actions_can_not_be_empty"> <source>Actions can not be empty.</source> <target state="translated">Ações não podem ficar vazias.</target> <note /> </trans-unit> <trans-unit id="Add_tuple_element_name_0"> <source>Add tuple element name '{0}'</source> <target state="translated">Adicionar o nome do elemento de tupla '{0}'</target> <note /> </trans-unit> <trans-unit id="Adding_0_around_an_active_statement_requires_restarting_the_application"> <source>Adding {0} around an active statement requires restarting the application.</source> <target state="new">Adding {0} around an active statement requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_into_a_1_requires_restarting_the_application"> <source>Adding {0} into a {1} requires restarting the application.</source> <target state="new">Adding {0} into a {1} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_into_a_class_with_explicit_or_sequential_layout_requires_restarting_the_application"> <source>Adding {0} into a class with explicit or sequential layout requires restarting the application.</source> <target state="new">Adding {0} into a class with explicit or sequential layout requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_into_a_generic_type_requires_restarting_the_application"> <source>Adding {0} into a generic type requires restarting the application.</source> <target state="new">Adding {0} into a generic type requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_into_an_interface_method_requires_restarting_the_application"> <source>Adding {0} into an interface method requires restarting the application.</source> <target state="new">Adding {0} into an interface method requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_into_an_interface_requires_restarting_the_application"> <source>Adding {0} into an interface requires restarting the application.</source> <target state="new">Adding {0} into an interface requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_requires_restarting_the_application"> <source>Adding {0} requires restarting the application.</source> <target state="new">Adding {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_that_accesses_captured_variables_1_and_2_declared_in_different_scopes_requires_restarting_the_application"> <source>Adding {0} that accesses captured variables '{1}' and '{2}' declared in different scopes requires restarting the application.</source> <target state="new">Adding {0} that accesses captured variables '{1}' and '{2}' declared in different scopes requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_0_with_the_Handles_clause_requires_restarting_the_application"> <source>Adding {0} with the Handles clause requires restarting the application.</source> <target state="new">Adding {0} with the Handles clause requires restarting the application.</target> <note>{Locked="Handles"} "Handles" is VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Adding_a_MustOverride_0_or_overriding_an_inherited_0_requires_restarting_the_application"> <source>Adding a MustOverride {0} or overriding an inherited {0} requires restarting the application.</source> <target state="new">Adding a MustOverride {0} or overriding an inherited {0} requires restarting the application.</target> <note>{Locked="MustOverride"} "MustOverride" is VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Adding_a_constructor_to_a_type_with_a_field_or_property_initializer_that_contains_an_anonymous_function_requires_restarting_the_application"> <source>Adding a constructor to a type with a field or property initializer that contains an anonymous function requires restarting the application.</source> <target state="new">Adding a constructor to a type with a field or property initializer that contains an anonymous function requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_a_generic_0_requires_restarting_the_application"> <source>Adding a generic {0} requires restarting the application.</source> <target state="new">Adding a generic {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_a_method_with_an_explicit_interface_specifier_requires_restarting_the_application"> <source>Adding a method with an explicit interface specifier requires restarting the application.</source> <target state="new">Adding a method with an explicit interface specifier requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_a_new_file_requires_restarting_the_application"> <source>Adding a new file requires restarting the application.</source> <target state="new">Adding a new file requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_a_user_defined_0_requires_restarting_the_application"> <source>Adding a user defined {0} requires restarting the application.</source> <target state="new">Adding a user defined {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application"> <source>Adding an abstract {0} or overriding an inherited {0} requires restarting the application.</source> <target state="new">Adding an abstract {0} or overriding an inherited {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Adding_an_extern_0_requires_restarting_the_application"> <source>Adding an extern {0} requires restarting the application.</source> <target state="new">Adding an extern {0} requires restarting the application.</target> <note>{Locked="extern"} "extern" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Adding_an_imported_method_requires_restarting_the_application"> <source>Adding an imported method requires restarting the application.</source> <target state="new">Adding an imported method requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Align_wrapped_arguments"> <source>Align wrapped arguments</source> <target state="translated">Alinhar argumentos encapsulados</target> <note /> </trans-unit> <trans-unit id="Align_wrapped_parameters"> <source>Align wrapped parameters</source> <target state="translated">Alinhar os parâmetros encapsulados</target> <note /> </trans-unit> <trans-unit id="Alternation_conditions_cannot_be_comments"> <source>Alternation conditions cannot be comments</source> <target state="translated">Condições de alternância não podem ser comentários</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: a|(?#b)</note> </trans-unit> <trans-unit id="Alternation_conditions_do_not_capture_and_cannot_be_named"> <source>Alternation conditions do not capture and cannot be named</source> <target state="translated">Condições de alternância não capturam e não podem ser nomeadas</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?(?'x'))</note> </trans-unit> <trans-unit id="An_update_that_causes_the_return_type_of_implicit_main_to_change_requires_restarting_the_application"> <source>An update that causes the return type of the implicit Main method to change requires restarting the application.</source> <target state="new">An update that causes the return type of the implicit Main method to change requires restarting the application.</target> <note>{Locked="Main"} is C# keywords and should not be localized.</note> </trans-unit> <trans-unit id="Apply_file_header_preferences"> <source>Apply file header preferences</source> <target state="translated">Aplicar as preferências de cabeçalho de arquivo</target> <note /> </trans-unit> <trans-unit id="Apply_object_collection_initialization_preferences"> <source>Apply object/collection initialization preferences</source> <target state="translated">Aplicar as preferências de inicialização de objeto/coleção</target> <note /> </trans-unit> <trans-unit id="Attribute_0_is_missing_Updating_an_async_method_or_an_iterator_requires_restarting_the_application"> <source>Attribute '{0}' is missing. Updating an async method or an iterator requires restarting the application.</source> <target state="new">Attribute '{0}' is missing. Updating an async method or an iterator requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Asynchronously_waits_for_the_task_to_finish"> <source>Asynchronously waits for the task to finish.</source> <target state="new">Asynchronously waits for the task to finish.</target> <note /> </trans-unit> <trans-unit id="Awaited_task_returns_0"> <source>Awaited task returns '{0}'</source> <target state="translated">A tarefa esperada retorna '{0}'</target> <note /> </trans-unit> <trans-unit id="Awaited_task_returns_no_value"> <source>Awaited task returns no value</source> <target state="translated">A tarefa esperada não retorna nenhum valor</target> <note /> </trans-unit> <trans-unit id="Base_classes_contain_inaccessible_unimplemented_members"> <source>Base classes contain inaccessible unimplemented members</source> <target state="translated">As classes base contêm membros não implementados inacessíveis</target> <note /> </trans-unit> <trans-unit id="CannotApplyChangesUnexpectedError"> <source>Cannot apply changes -- unexpected error: '{0}'</source> <target state="translated">Não é possível aplicar as alterações – erro inesperado: '{0}'</target> <note /> </trans-unit> <trans-unit id="Cannot_include_class_0_in_character_range"> <source>Cannot include class \{0} in character range</source> <target state="translated">Não é possível incluir a classe \{0} no intervalo de caracteres</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: [a-\w]. {0} is the invalid class (\w here)</note> </trans-unit> <trans-unit id="Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue"> <source>Capture group numbers must be less than or equal to Int32.MaxValue</source> <target state="translated">Os números do grupo de captura devem ser menores ou iguais a Int32.MaxValue</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: a{2147483648}</note> </trans-unit> <trans-unit id="Capture_number_cannot_be_zero"> <source>Capture number cannot be zero</source> <target state="translated">O número da captura não pode ser zero</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?&lt;0&gt;a)</note> </trans-unit> <trans-unit id="Capturing_variable_0_that_hasn_t_been_captured_before_requires_restarting_the_application"> <source>Capturing variable '{0}' that hasn't been captured before requires restarting the application.</source> <target state="new">Capturing variable '{0}' that hasn't been captured before requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Ceasing_to_access_captured_variable_0_in_1_requires_restarting_the_application"> <source>Ceasing to access captured variable '{0}' in {1} requires restarting the application.</source> <target state="new">Ceasing to access captured variable '{0}' in {1} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Ceasing_to_capture_variable_0_requires_restarting_the_application"> <source>Ceasing to capture variable '{0}' requires restarting the application.</source> <target state="new">Ceasing to capture variable '{0}' requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="ChangeSignature_NewParameterInferValue"> <source>&lt;infer&gt;</source> <target state="translated">&lt;inferir&gt;</target> <note /> </trans-unit> <trans-unit id="ChangeSignature_NewParameterIntroduceTODOVariable"> <source>TODO</source> <target state="new">TODO</target> <note>"TODO" is an indication that there is work still to be done.</note> </trans-unit> <trans-unit id="ChangeSignature_NewParameterOmitValue"> <source>&lt;omit&gt;</source> <target state="translated">&lt;omitir&gt;</target> <note /> </trans-unit> <trans-unit id="Change_namespace_to_0"> <source>Change namespace to '{0}'</source> <target state="translated">Alterar o namespace para '{0}'</target> <note /> </trans-unit> <trans-unit id="Change_to_global_namespace"> <source>Change to global namespace</source> <target state="translated">Alterar para o namespace global</target> <note /> </trans-unit> <trans-unit id="ChangesDisallowedWhileStoppedAtException"> <source>Changes are not allowed while stopped at exception</source> <target state="translated">Não são permitidas alterações durante uma interrupção em exceção</target> <note /> </trans-unit> <trans-unit id="ChangesNotAppliedWhileRunning"> <source>Changes made in project '{0}' will not be applied while the application is running</source> <target state="translated">As alterações feitas no projeto '{0}' não serão aplicadas enquanto o aplicativo estiver em execução</target> <note /> </trans-unit> <trans-unit id="ChangesRequiredSynthesizedType"> <source>One or more changes result in a new type being created by the compiler, which requires restarting the application because it is not supported by the runtime</source> <target state="new">One or more changes result in a new type being created by the compiler, which requires restarting the application because it is not supported by the runtime</target> <note /> </trans-unit> <trans-unit id="Changing_0_from_asynchronous_to_synchronous_requires_restarting_the_application"> <source>Changing {0} from asynchronous to synchronous requires restarting the application.</source> <target state="new">Changing {0} from asynchronous to synchronous requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_0_to_1_requires_restarting_the_application_because_it_changes_the_shape_of_the_state_machine"> <source>Changing '{0}' to '{1}' requires restarting the application because it changes the shape of the state machine.</source> <target state="new">Changing '{0}' to '{1}' requires restarting the application because it changes the shape of the state machine.</target> <note /> </trans-unit> <trans-unit id="Changing_a_field_to_an_event_or_vice_versa_requires_restarting_the_application"> <source>Changing a field to an event or vice versa requires restarting the application.</source> <target state="new">Changing a field to an event or vice versa requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_constraints_of_0_requires_restarting_the_application"> <source>Changing constraints of {0} requires restarting the application.</source> <target state="new">Changing constraints of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_parameter_types_of_0_requires_restarting_the_application"> <source>Changing parameter types of {0} requires restarting the application.</source> <target state="new">Changing parameter types of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_the_declaration_scope_of_a_captured_variable_0_requires_restarting_the_application"> <source>Changing the declaration scope of a captured variable '{0}' requires restarting the application.</source> <target state="new">Changing the declaration scope of a captured variable '{0}' requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_the_parameters_of_0_requires_restarting_the_application"> <source>Changing the parameters of {0} requires restarting the application.</source> <target state="new">Changing the parameters of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_the_return_type_of_0_requires_restarting_the_application"> <source>Changing the return type of {0} requires restarting the application.</source> <target state="new">Changing the return type of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_the_type_of_0_requires_restarting_the_application"> <source>Changing the type of {0} requires restarting the application.</source> <target state="new">Changing the type of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_the_type_of_a_captured_variable_0_previously_of_type_1_requires_restarting_the_application"> <source>Changing the type of a captured variable '{0}' previously of type '{1}' requires restarting the application.</source> <target state="new">Changing the type of a captured variable '{0}' previously of type '{1}' requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_type_parameters_of_0_requires_restarting_the_application"> <source>Changing type parameters of {0} requires restarting the application.</source> <target state="new">Changing type parameters of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Changing_visibility_of_0_requires_restarting_the_application"> <source>Changing visibility of {0} requires restarting the application.</source> <target state="new">Changing visibility of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Configure_0_code_style"> <source>Configure {0} code style</source> <target state="translated">Configurar estilo de código de {0}</target> <note /> </trans-unit> <trans-unit id="Configure_0_severity"> <source>Configure {0} severity</source> <target state="translated">Configurar severidade de {0}</target> <note /> </trans-unit> <trans-unit id="Configure_severity_for_all_0_analyzers"> <source>Configure severity for all '{0}' analyzers</source> <target state="translated">Configurar gravidade para todos os analisadores '{0}'</target> <note /> </trans-unit> <trans-unit id="Configure_severity_for_all_analyzers"> <source>Configure severity for all analyzers</source> <target state="translated">Configurar gravidade para todos os analisadores</target> <note /> </trans-unit> <trans-unit id="Convert_to_linq"> <source>Convert to LINQ</source> <target state="translated">Converter para LINQ</target> <note /> </trans-unit> <trans-unit id="Add_to_0"> <source>Add to '{0}'</source> <target state="translated">Adicionar para '{0}'</target> <note /> </trans-unit> <trans-unit id="Convert_to_class"> <source>Convert to class</source> <target state="translated">Converter em classe</target> <note /> </trans-unit> <trans-unit id="Convert_to_linq_call_form"> <source>Convert to LINQ (call form)</source> <target state="translated">Converter para LINQ (formulário de chamada)</target> <note /> </trans-unit> <trans-unit id="Convert_to_record"> <source>Convert to record</source> <target state="translated">Converter em Registro</target> <note /> </trans-unit> <trans-unit id="Convert_to_record_struct"> <source>Convert to record struct</source> <target state="translated">Converter em registro de struct</target> <note /> </trans-unit> <trans-unit id="Convert_to_struct"> <source>Convert to struct</source> <target state="translated">Converter para struct</target> <note /> </trans-unit> <trans-unit id="Convert_type_to_0"> <source>Convert type to '{0}'</source> <target state="translated">Converter o tipo em '{0}'</target> <note /> </trans-unit> <trans-unit id="Create_and_assign_field_0"> <source>Create and assign field '{0}'</source> <target state="translated">Criar e atribuir o campo '{0}'</target> <note /> </trans-unit> <trans-unit id="Create_and_assign_property_0"> <source>Create and assign property '{0}'</source> <target state="translated">Criar e atribuir a propriedade '{0}'</target> <note /> </trans-unit> <trans-unit id="Create_and_assign_remaining_as_fields"> <source>Create and assign remaining as fields</source> <target state="translated">Criar e atribuir os restantes como campos</target> <note /> </trans-unit> <trans-unit id="Create_and_assign_remaining_as_properties"> <source>Create and assign remaining as properties</source> <target state="translated">Criar e atribuir os restantes como propriedades</target> <note /> </trans-unit> <trans-unit id="Deleting_0_around_an_active_statement_requires_restarting_the_application"> <source>Deleting {0} around an active statement requires restarting the application.</source> <target state="new">Deleting {0} around an active statement requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Deleting_0_requires_restarting_the_application"> <source>Deleting {0} requires restarting the application.</source> <target state="new">Deleting {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Deleting_captured_variable_0_requires_restarting_the_application"> <source>Deleting captured variable '{0}' requires restarting the application.</source> <target state="new">Deleting captured variable '{0}' requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Do_not_change_this_code_Put_cleanup_code_in_0_method"> <source>Do not change this code. Put cleanup code in '{0}' method</source> <target state="translated">Não altere este código. Coloque o código de limpeza no método '{0}'</target> <note /> </trans-unit> <trans-unit id="DocumentIsOutOfSyncWithDebuggee"> <source>The current content of source file '{0}' does not match the built source. Any changes made to this file while debugging won't be applied until its content matches the built source.</source> <target state="translated">O conteúdo atual do arquivo de origem '{0}' não corresponde à origem criada. Todas as alterações feitas neste arquivo durante a depuração não serão aplicadas até que o conteúdo corresponda à origem criada.</target> <note /> </trans-unit> <trans-unit id="Document_must_be_contained_in_the_workspace_that_created_this_service"> <source>Document must be contained in the workspace that created this service</source> <target state="translated">O Documento deve estar contido no workspace que criou este serviço</target> <note /> </trans-unit> <trans-unit id="EditAndContinue"> <source>Edit and Continue</source> <target state="translated">Editar e Continuar</target> <note /> </trans-unit> <trans-unit id="EditAndContinueDisallowedByModule"> <source>Edit and Continue disallowed by module</source> <target state="translated">Pelo módulo, não é permitido Editar e Continuar</target> <note /> </trans-unit> <trans-unit id="EditAndContinueDisallowedByProject"> <source>Changes made in project '{0}' require restarting the application: {1}</source> <target state="needs-review-translation">As alterações feitas no projeto '{0}' impedirão que a sessão de depuração continue: {1}</target> <note /> </trans-unit> <trans-unit id="Edit_and_continue_is_not_supported_by_the_runtime"> <source>Edit and continue is not supported by the runtime.</source> <target state="translated">Editar e continuar não é suportado pelo tempo de execução.</target> <note /> </trans-unit> <trans-unit id="ErrorReadingFile"> <source>Error while reading file '{0}': {1}</source> <target state="translated">Erro ao ler o arquivo '{0}': {1}</target> <note /> </trans-unit> <trans-unit id="Error_creating_instance_of_CodeFixProvider"> <source>Error creating instance of CodeFixProvider</source> <target state="translated">Erro ao criar a instância de CodeFixProvider</target> <note /> </trans-unit> <trans-unit id="Error_creating_instance_of_CodeFixProvider_0"> <source>Error creating instance of CodeFixProvider '{0}'</source> <target state="translated">Erro ao criar instância de CodeFixProvider '{0}'</target> <note /> </trans-unit> <trans-unit id="Example"> <source>Example:</source> <target state="translated">Exemplo:</target> <note>Singular form when we want to show an example, but only have one to show.</note> </trans-unit> <trans-unit id="Examples"> <source>Examples:</source> <target state="translated">Exemplos:</target> <note>Plural form when we have multiple examples to show.</note> </trans-unit> <trans-unit id="Explicitly_implemented_methods_of_records_must_have_parameter_names_that_match_the_compiler_generated_equivalent_0"> <source>Explicitly implemented methods of records must have parameter names that match the compiler generated equivalent '{0}'</source> <target state="translated">Métodos explicitamente implementados de registros devem ter nomes de parâmetro que correspondem ao compilador gerado '{0}' equivalente</target> <note /> </trans-unit> <trans-unit id="Extract_base_class"> <source>Extract base class...</source> <target state="translated">Extrair a classe base...</target> <note /> </trans-unit> <trans-unit id="Extract_interface"> <source>Extract interface...</source> <target state="translated">Extrair a interface...</target> <note /> </trans-unit> <trans-unit id="Extract_local_function"> <source>Extract local function</source> <target state="translated">Extrair a função local</target> <note /> </trans-unit> <trans-unit id="Extract_method"> <source>Extract method</source> <target state="translated">Extrair método</target> <note /> </trans-unit> <trans-unit id="Failed_to_analyze_data_flow_for_0"> <source>Failed to analyze data-flow for: {0}</source> <target state="translated">Falha ao analisar o fluxo de dados para: {0}</target> <note /> </trans-unit> <trans-unit id="Fix_formatting"> <source>Fix formatting</source> <target state="translated">Corrigir a formatação</target> <note /> </trans-unit> <trans-unit id="Fix_typo_0"> <source>Fix typo '{0}'</source> <target state="translated">Corrigir erro de digitação '{0}'</target> <note /> </trans-unit> <trans-unit id="Format_document"> <source>Format document</source> <target state="translated">Formatar o documento</target> <note /> </trans-unit> <trans-unit id="Formatting_document"> <source>Formatting document</source> <target state="translated">Formatando documento</target> <note /> </trans-unit> <trans-unit id="Generate_comparison_operators"> <source>Generate comparison operators</source> <target state="translated">Gerar operadores de comparação</target> <note /> </trans-unit> <trans-unit id="Generate_constructor_in_0_with_fields"> <source>Generate constructor in '{0}' (with fields)</source> <target state="translated">Gerar o construtor em '{0}' (com campos)</target> <note /> </trans-unit> <trans-unit id="Generate_constructor_in_0_with_properties"> <source>Generate constructor in '{0}' (with properties)</source> <target state="translated">Gerar o construtor em '{0}' (com propriedades)</target> <note /> </trans-unit> <trans-unit id="Generate_for_0"> <source>Generate for '{0}'</source> <target state="translated">Gerar para '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_parameter_0"> <source>Generate parameter '{0}'</source> <target state="translated">Gerar o parâmetro '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_parameter_0_and_overrides_implementations"> <source>Generate parameter '{0}' (and overrides/implementations)</source> <target state="translated">Gerar o parâmetro '{0}' (e as substituições/implementações)</target> <note /> </trans-unit> <trans-unit id="Illegal_backslash_at_end_of_pattern"> <source>Illegal \ at end of pattern</source> <target state="translated">\ ilegal no final do padrão</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \</note> </trans-unit> <trans-unit id="Illegal_x_y_with_x_less_than_y"> <source>Illegal {x,y} with x &gt; y</source> <target state="translated">{x,y} ilegal com x&gt; y</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: a{1,0}</note> </trans-unit> <trans-unit id="Implement_0_explicitly"> <source>Implement '{0}' explicitly</source> <target state="translated">Implementar '{0}' explicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_0_implicitly"> <source>Implement '{0}' implicitly</source> <target state="translated">Implementar '{0}' implicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_abstract_class"> <source>Implement abstract class</source> <target state="translated">Implementar classe abstrata</target> <note /> </trans-unit> <trans-unit id="Implement_all_interfaces_explicitly"> <source>Implement all interfaces explicitly</source> <target state="translated">Implementar todas as interfaces explicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_all_interfaces_implicitly"> <source>Implement all interfaces implicitly</source> <target state="translated">Implementar todas as interfaces implicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_all_members_explicitly"> <source>Implement all members explicitly</source> <target state="translated">Implementar todos os membros explicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_explicitly"> <source>Implement explicitly</source> <target state="translated">Implementar explicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_implicitly"> <source>Implement implicitly</source> <target state="translated">Implementar implicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_remaining_members_explicitly"> <source>Implement remaining members explicitly</source> <target state="translated">Implementar os membros restantes explicitamente</target> <note /> </trans-unit> <trans-unit id="Implement_through_0"> <source>Implement through '{0}'</source> <target state="translated">Implementar por meio de '{0}'</target> <note /> </trans-unit> <trans-unit id="Implementing_a_record_positional_parameter_0_as_read_only_requires_restarting_the_application"> <source>Implementing a record positional parameter '{0}' as read only requires restarting the application,</source> <target state="new">Implementing a record positional parameter '{0}' as read only requires restarting the application,</target> <note /> </trans-unit> <trans-unit id="Implementing_a_record_positional_parameter_0_with_a_set_accessor_requires_restarting_the_application"> <source>Implementing a record positional parameter '{0}' with a set accessor requires restarting the application.</source> <target state="new">Implementing a record positional parameter '{0}' with a set accessor requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Incomplete_character_escape"> <source>Incomplete \p{X} character escape</source> <target state="translated">Escape de caractere incompleto \p{X}</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \p{ Cc }</note> </trans-unit> <trans-unit id="Indent_all_arguments"> <source>Indent all arguments</source> <target state="translated">Recuar todos os argumentos</target> <note /> </trans-unit> <trans-unit id="Indent_all_parameters"> <source>Indent all parameters</source> <target state="translated">Recuar todos os parâmetros</target> <note /> </trans-unit> <trans-unit id="Indent_wrapped_arguments"> <source>Indent wrapped arguments</source> <target state="translated">Recuar argumentos encapsulados</target> <note /> </trans-unit> <trans-unit id="Indent_wrapped_parameters"> <source>Indent wrapped parameters</source> <target state="translated">Recuar parâmetros encapsulados</target> <note /> </trans-unit> <trans-unit id="Inline_0"> <source>Inline '{0}'</source> <target state="translated">Embutir '{0}'</target> <note /> </trans-unit> <trans-unit id="Inline_and_keep_0"> <source>Inline and keep '{0}'</source> <target state="translated">Embutir e manter '{0}'</target> <note /> </trans-unit> <trans-unit id="Insufficient_hexadecimal_digits"> <source>Insufficient hexadecimal digits</source> <target state="translated">Dígitos hexadecimais insuficientes</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \x</note> </trans-unit> <trans-unit id="Introduce_constant"> <source>Introduce constant</source> <target state="translated">Introduzir a constante</target> <note /> </trans-unit> <trans-unit id="Introduce_field"> <source>Introduce field</source> <target state="translated">Introduzir campo</target> <note /> </trans-unit> <trans-unit id="Introduce_local"> <source>Introduce local</source> <target state="translated">Introduzir o local</target> <note /> </trans-unit> <trans-unit id="Introduce_parameter"> <source>Introduce parameter</source> <target state="new">Introduce parameter</target> <note /> </trans-unit> <trans-unit id="Introduce_parameter_for_0"> <source>Introduce parameter for '{0}'</source> <target state="new">Introduce parameter for '{0}'</target> <note /> </trans-unit> <trans-unit id="Introduce_parameter_for_all_occurrences_of_0"> <source>Introduce parameter for all occurrences of '{0}'</source> <target state="new">Introduce parameter for all occurrences of '{0}'</target> <note /> </trans-unit> <trans-unit id="Introduce_query_variable"> <source>Introduce query variable</source> <target state="translated">Introduzir a variável de consulta</target> <note /> </trans-unit> <trans-unit id="Invalid_group_name_Group_names_must_begin_with_a_word_character"> <source>Invalid group name: Group names must begin with a word character</source> <target state="translated">Nome de grupo inválido: nomes de grupos devem começar com um caractere de palavra</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?&lt;a &gt;a)</note> </trans-unit> <trans-unit id="Invalid_selection"> <source>Invalid selection.</source> <target state="new">Invalid selection.</target> <note /> </trans-unit> <trans-unit id="Make_class_abstract"> <source>Make class 'abstract'</source> <target state="translated">Tornar a classe 'abstract'</target> <note /> </trans-unit> <trans-unit id="Make_member_static"> <source>Make static</source> <target state="translated">Tornar estático</target> <note /> </trans-unit> <trans-unit id="Invert_conditional"> <source>Invert conditional</source> <target state="translated">Inverter condicional</target> <note /> </trans-unit> <trans-unit id="Making_a_method_an_iterator_requires_restarting_the_application"> <source>Making a method an iterator requires restarting the application.</source> <target state="new">Making a method an iterator requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Making_a_method_asynchronous_requires_restarting_the_application"> <source>Making a method asynchronous requires restarting the application.</source> <target state="new">Making a method asynchronous requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Malformed"> <source>malformed</source> <target state="translated">malformado</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?(0</note> </trans-unit> <trans-unit id="Malformed_character_escape"> <source>Malformed \p{X} character escape</source> <target state="translated">Escape de caractere malformado \p{X}</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \p {Cc}</note> </trans-unit> <trans-unit id="Malformed_named_back_reference"> <source>Malformed \k&lt;...&gt; named back reference</source> <target state="translated">Referência inversa \k&lt;...&gt; mal formada</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \k'</note> </trans-unit> <trans-unit id="Merge_with_nested_0_statement"> <source>Merge with nested '{0}' statement</source> <target state="translated">Mesclar com a instrução '{0}' aninhada</target> <note /> </trans-unit> <trans-unit id="Merge_with_next_0_statement"> <source>Merge with next '{0}' statement</source> <target state="translated">Mesclar com a próxima instrução '{0}'</target> <note /> </trans-unit> <trans-unit id="Merge_with_outer_0_statement"> <source>Merge with outer '{0}' statement</source> <target state="translated">Mesclar com a instrução '{0}' externa</target> <note /> </trans-unit> <trans-unit id="Merge_with_previous_0_statement"> <source>Merge with previous '{0}' statement</source> <target state="translated">Mesclar com a instrução '{0}' anterior</target> <note /> </trans-unit> <trans-unit id="MethodMustReturnStreamThatSupportsReadAndSeek"> <source>{0} must return a stream that supports read and seek operations.</source> <target state="translated">{0} precisa retornar um fluxo compatível com as operações de leitura e busca.</target> <note /> </trans-unit> <trans-unit id="Missing_control_character"> <source>Missing control character</source> <target state="translated">Caractere de controle ausente</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \c</note> </trans-unit> <trans-unit id="Modifying_0_which_contains_a_static_variable_requires_restarting_the_application"> <source>Modifying {0} which contains a static variable requires restarting the application.</source> <target state="new">Modifying {0} which contains a static variable requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_0_which_contains_an_Aggregate_Group_By_or_Join_query_clauses_requires_restarting_the_application"> <source>Modifying {0} which contains an Aggregate, Group By, or Join query clauses requires restarting the application.</source> <target state="new">Modifying {0} which contains an Aggregate, Group By, or Join query clauses requires restarting the application.</target> <note>{Locked="Aggregate"}{Locked="Group By"}{Locked="Join"} are VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Modifying_0_which_contains_the_stackalloc_operator_requires_restarting_the_application"> <source>Modifying {0} which contains the stackalloc operator requires restarting the application.</source> <target state="new">Modifying {0} which contains the stackalloc operator requires restarting the application.</target> <note>{Locked="stackalloc"} "stackalloc" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Modifying_a_catch_finally_handler_with_an_active_statement_in_the_try_block_requires_restarting_the_application"> <source>Modifying a catch/finally handler with an active statement in the try block requires restarting the application.</source> <target state="new">Modifying a catch/finally handler with an active statement in the try block requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_a_catch_handler_around_an_active_statement_requires_restarting_the_application"> <source>Modifying a catch handler around an active statement requires restarting the application.</source> <target state="new">Modifying a catch handler around an active statement requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_a_generic_method_requires_restarting_the_application"> <source>Modifying a generic method requires restarting the application.</source> <target state="new">Modifying a generic method requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_a_method_inside_the_context_of_a_generic_type_requires_restarting_the_application"> <source>Modifying a method inside the context of a generic type requires restarting the application.</source> <target state="new">Modifying a method inside the context of a generic type requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_a_try_catch_finally_statement_when_the_finally_block_is_active_requires_restarting_the_application"> <source>Modifying a try/catch/finally statement when the finally block is active requires restarting the application.</source> <target state="new">Modifying a try/catch/finally statement when the finally block is active requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_an_active_0_which_contains_On_Error_or_Resume_statements_requires_restarting_the_application"> <source>Modifying an active {0} which contains On Error or Resume statements requires restarting the application.</source> <target state="new">Modifying an active {0} which contains On Error or Resume statements requires restarting the application.</target> <note>{Locked="On Error"}{Locked="Resume"} is VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Modifying_body_of_0_requires_restarting_the_application_because_the_body_has_too_many_statements"> <source>Modifying the body of {0} requires restarting the application because the body has too many statements.</source> <target state="new">Modifying the body of {0} requires restarting the application because the body has too many statements.</target> <note /> </trans-unit> <trans-unit id="Modifying_body_of_0_requires_restarting_the_application_due_to_internal_error_1"> <source>Modifying the body of {0} requires restarting the application due to internal error: {1}</source> <target state="new">Modifying the body of {0} requires restarting the application due to internal error: {1}</target> <note>{1} is a multi-line exception message including a stacktrace. Place it at the end of the message and don't add any punctation after or around {1}</note> </trans-unit> <trans-unit id="Modifying_source_file_0_requires_restarting_the_application_because_the_file_is_too_big"> <source>Modifying source file '{0}' requires restarting the application because the file is too big.</source> <target state="new">Modifying source file '{0}' requires restarting the application because the file is too big.</target> <note /> </trans-unit> <trans-unit id="Modifying_source_file_0_requires_restarting_the_application_due_to_internal_error_1"> <source>Modifying source file '{0}' requires restarting the application due to internal error: {1}</source> <target state="new">Modifying source file '{0}' requires restarting the application due to internal error: {1}</target> <note>{2} is a multi-line exception message including a stacktrace. Place it at the end of the message and don't add any punctation after or around {1}</note> </trans-unit> <trans-unit id="Modifying_source_with_experimental_language_features_enabled_requires_restarting_the_application"> <source>Modifying source with experimental language features enabled requires restarting the application.</source> <target state="new">Modifying source with experimental language features enabled requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_the_initializer_of_0_in_a_generic_type_requires_restarting_the_application"> <source>Modifying the initializer of {0} in a generic type requires restarting the application.</source> <target state="new">Modifying the initializer of {0} in a generic type requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_whitespace_or_comments_in_0_inside_the_context_of_a_generic_type_requires_restarting_the_application"> <source>Modifying whitespace or comments in {0} inside the context of a generic type requires restarting the application.</source> <target state="new">Modifying whitespace or comments in {0} inside the context of a generic type requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Modifying_whitespace_or_comments_in_a_generic_0_requires_restarting_the_application"> <source>Modifying whitespace or comments in a generic {0} requires restarting the application.</source> <target state="new">Modifying whitespace or comments in a generic {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Move_contents_to_namespace"> <source>Move contents to namespace...</source> <target state="translated">Mover conteúdo para o namespace...</target> <note /> </trans-unit> <trans-unit id="Move_file_to_0"> <source>Move file to '{0}'</source> <target state="translated">Mover o arquivo para '{0}'</target> <note /> </trans-unit> <trans-unit id="Move_file_to_project_root_folder"> <source>Move file to project root folder</source> <target state="translated">Mover o arquivo para a pasta raiz do projeto</target> <note /> </trans-unit> <trans-unit id="Move_to_namespace"> <source>Move to namespace...</source> <target state="translated">Mover para o namespace...</target> <note /> </trans-unit> <trans-unit id="Moving_0_requires_restarting_the_application"> <source>Moving {0} requires restarting the application.</source> <target state="new">Moving {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Nested_quantifier_0"> <source>Nested quantifier {0}</source> <target state="translated">Quantificador aninhado {0}</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: a**. In this case {0} will be '*', the extra unnecessary quantifier.</note> </trans-unit> <trans-unit id="No_common_root_node_for_extraction"> <source>No common root node for extraction.</source> <target state="new">No common root node for extraction.</target> <note /> </trans-unit> <trans-unit id="No_valid_location_to_insert_method_call"> <source>No valid location to insert method call.</source> <target state="translated">Não há nenhum local válido para inserir a chamada de método.</target> <note /> </trans-unit> <trans-unit id="No_valid_selection_to_perform_extraction"> <source>No valid selection to perform extraction.</source> <target state="new">No valid selection to perform extraction.</target> <note /> </trans-unit> <trans-unit id="Not_enough_close_parens"> <source>Not enough )'s</source> <target state="translated">Não há )'s suficientes</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (a</note> </trans-unit> <trans-unit id="Operators"> <source>Operators</source> <target state="translated">Operadores</target> <note /> </trans-unit> <trans-unit id="Property_reference_cannot_be_updated"> <source>Property reference cannot be updated</source> <target state="translated">A referência de propriedade não pode ser atualizada</target> <note /> </trans-unit> <trans-unit id="Pull_0_up"> <source>Pull '{0}' up</source> <target state="translated">Efetuar pull de '{0}'</target> <note /> </trans-unit> <trans-unit id="Pull_0_up_to_1"> <source>Pull '{0}' up to '{1}'</source> <target state="translated">Efetue pull de '{0}' até '{1}'</target> <note /> </trans-unit> <trans-unit id="Pull_members_up_to_base_type"> <source>Pull members up to base type...</source> <target state="translated">Efetuar pull de membros até o tipo base...</target> <note /> </trans-unit> <trans-unit id="Pull_members_up_to_new_base_class"> <source>Pull member(s) up to new base class...</source> <target state="translated">Efetuar pull de membros até a nova classe base...</target> <note /> </trans-unit> <trans-unit id="Quantifier_x_y_following_nothing"> <source>Quantifier {x,y} following nothing</source> <target state="translated">Nada precede o quantificador {x,y}</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: *</note> </trans-unit> <trans-unit id="Reference_to_undefined_group"> <source>reference to undefined group</source> <target state="translated">referência a grupo indefinido</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?(1))</note> </trans-unit> <trans-unit id="Reference_to_undefined_group_name_0"> <source>Reference to undefined group name {0}</source> <target state="translated">Referência ao nome do grupo indefinido {0}</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \k&lt;a&gt;. Here, {0} will be the name of the undefined group ('a')</note> </trans-unit> <trans-unit id="Reference_to_undefined_group_number_0"> <source>Reference to undefined group number {0}</source> <target state="translated">Referência ao grupo número {0} indefinido</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?&lt;-1&gt;). Here, {0} will be the number of the undefined group ('1')</note> </trans-unit> <trans-unit id="Regex_all_control_characters_long"> <source>All control characters. This includes the Cc, Cf, Cs, Co, and Cn categories.</source> <target state="translated">Todos os caracteres de controle. Isso inclui as categorias Cc, Cf, Cs, Co e Cn.</target> <note /> </trans-unit> <trans-unit id="Regex_all_control_characters_short"> <source>all control characters</source> <target state="translated">todos os caracteres de controle</target> <note /> </trans-unit> <trans-unit id="Regex_all_diacritic_marks_long"> <source>All diacritic marks. This includes the Mn, Mc, and Me categories.</source> <target state="translated">Todas as marcas diacríticas. Isso inclui as categorias Mn, Mc e Me.</target> <note /> </trans-unit> <trans-unit id="Regex_all_diacritic_marks_short"> <source>all diacritic marks</source> <target state="translated">todas as marcas diacríticas</target> <note /> </trans-unit> <trans-unit id="Regex_all_letter_characters_long"> <source>All letter characters. This includes the Lu, Ll, Lt, Lm, and Lo characters.</source> <target state="translated">Todos os caracteres de letra. Isso inclui os caracteres Lu, Ll, Lt, Lm e Lo.</target> <note /> </trans-unit> <trans-unit id="Regex_all_letter_characters_short"> <source>all letter characters</source> <target state="translated">todos os caracteres de letra</target> <note /> </trans-unit> <trans-unit id="Regex_all_numbers_long"> <source>All numbers. This includes the Nd, Nl, and No categories.</source> <target state="translated">Todos os números. Isso inclui as categorias Nd, Nl e No.</target> <note /> </trans-unit> <trans-unit id="Regex_all_numbers_short"> <source>all numbers</source> <target state="translated">todos os números</target> <note /> </trans-unit> <trans-unit id="Regex_all_punctuation_characters_long"> <source>All punctuation characters. This includes the Pc, Pd, Ps, Pe, Pi, Pf, and Po categories.</source> <target state="translated">Todos os caracteres de pontuação. Isso inclui as categorias Pc, Pd, Ps, Pe, Pi, Pf e Po.</target> <note /> </trans-unit> <trans-unit id="Regex_all_punctuation_characters_short"> <source>all punctuation characters</source> <target state="translated">todos os caracteres de pontuação</target> <note /> </trans-unit> <trans-unit id="Regex_all_separator_characters_long"> <source>All separator characters. This includes the Zs, Zl, and Zp categories.</source> <target state="translated">Todos os caracteres separadores. Isso inclui as categorias Zs, Zl e Zp.</target> <note /> </trans-unit> <trans-unit id="Regex_all_separator_characters_short"> <source>all separator characters</source> <target state="translated">todos os caracteres separadores</target> <note /> </trans-unit> <trans-unit id="Regex_all_symbols_long"> <source>All symbols. This includes the Sm, Sc, Sk, and So categories.</source> <target state="translated">Todos os símbolos. Isso inclui as categorias Sm, Sc, Sk e So.</target> <note /> </trans-unit> <trans-unit id="Regex_all_symbols_short"> <source>all symbols</source> <target state="translated">todos os símbolos</target> <note /> </trans-unit> <trans-unit id="Regex_alternation_long"> <source>You can use the vertical bar (|) character to match any one of a series of patterns, where the | character separates each pattern.</source> <target state="translated">Você pode usar o caractere de barra vertical (|) para corresponder a qualquer uma das séries de padrões, em que o caractere | separa cada padrão.</target> <note /> </trans-unit> <trans-unit id="Regex_alternation_short"> <source>alternation</source> <target state="translated">alternação</target> <note /> </trans-unit> <trans-unit id="Regex_any_character_group_long"> <source>The period character (.) matches any character except \n (the newline character, \u000A). If a regular expression pattern is modified by the RegexOptions.Singleline option, or if the portion of the pattern that contains the . character class is modified by the 's' option, . matches any character.</source> <target state="translated">O caractere de ponto (.) corresponde a qualquer caractere, exceto \n (o caractere de nova linha, \u000A). Se um padrão de expressão regular for modificado pela opção RegexOptions.Singleline ou se a parte do padrão que contém a classe de caractere . for modificada pela opção 's', . corresponderá a qualquer caractere.</target> <note /> </trans-unit> <trans-unit id="Regex_any_character_group_short"> <source>any character</source> <target state="translated">qualquer caractere</target> <note /> </trans-unit> <trans-unit id="Regex_atomic_group_long"> <source>Atomic groups (known in some other regular expression engines as a nonbacktracking subexpression, an atomic subexpression, or a once-only subexpression) disable backtracking. The regular expression engine will match as many characters in the input string as it can. When no further match is possible, it will not backtrack to attempt alternate pattern matches. (That is, the subexpression matches only strings that would be matched by the subexpression alone; it does not attempt to match a string based on the subexpression and any subexpressions that follow it.) This option is recommended if you know that backtracking will not succeed. Preventing the regular expression engine from performing unnecessary searching improves performance.</source> <target state="translated">Grupos atômicos (conhecidos em alguns outros mecanismos de expressão regulares como uma subexpressão sem rastreamento inverso, uma subexpressão atômica ou uma subexpressão de apenas uma vez) desabilita o rastreamento inverso. O mecanismo de expressão regular corresponderá o máximo possível de caracteres em uma cadeia de caracteres de entrada possível. Quando não for mais possível corresponder, ele não fará o rastreamento inverso para tentar alternar as correspondências de padrão. (Ou seja, a subexpressão corresponderá somente às cadeias de caracteres que seriam correspondidas pela subexpressão sozinha. Ela não tentará corresponder a uma cadeia de caracteres com base na subexpressão e nas subexpressões seguintes.) Essa opção é recomendada quando você sabe que o rastreamento inverso não será bem-sucedido. Impedir o mecanismo de expressão regular de executar pesquisas desnecessárias melhora o desempenho.</target> <note /> </trans-unit> <trans-unit id="Regex_atomic_group_short"> <source>atomic group</source> <target state="translated">grupo atômico</target> <note /> </trans-unit> <trans-unit id="Regex_backspace_character_long"> <source>Matches a backspace character, \u0008</source> <target state="translated">Corresponde a um caractere de backspace, \u0008</target> <note /> </trans-unit> <trans-unit id="Regex_backspace_character_short"> <source>backspace character</source> <target state="translated">caractere de backspace</target> <note /> </trans-unit> <trans-unit id="Regex_balancing_group_long"> <source>A balancing group definition deletes the definition of a previously defined group and stores, in the current group, the interval between the previously defined group and the current group. 'name1' is the current group (optional), 'name2' is a previously defined group, and 'subexpression' is any valid regular expression pattern. The balancing group definition deletes the definition of name2 and stores the interval between name2 and name1 in name1. If no name2 group is defined, the match backtracks. Because deleting the last definition of name2 reveals the previous definition of name2, this construct lets you use the stack of captures for group name2 as a counter for keeping track of nested constructs such as parentheses or opening and closing brackets. The balancing group definition uses 'name2' as a stack. The beginning character of each nested construct is placed in the group and in its Group.Captures collection. When the closing character is matched, its corresponding opening character is removed from the group, and the Captures collection is decreased by one. After the opening and closing characters of all nested constructs have been matched, 'name1' is empty.</source> <target state="translated">Uma definição de grupo de balanceamento exclui a definição de um grupo definido anteriormente e armazena, no grupo atual, o intervalo entre o grupo definido anteriormente e o grupo atual. 'name1' é o grupo atual (opcional), 'name2' é um grupo definido anteriormente e 'subexpression' é qualquer padrão de expressão regular válido. A definição de grupo de balanceamento exclui a definição de name2 e armazena o intervalo entre name2 e name1 no name1. Se não for definido nenhum name2, a correspondência retrocederá. Como a exclusão da última definição de name2 revela a definição anterior de name2, esse constructo permite o uso da pilha de capturas para o grupo name2 como um contador para manter o controle de constructos aninhados, como parênteses ou colchetes de abertura e fechamento. A definição de grupo de balanceamento usa 'name2' como uma pilha. O caractere inicial de cada constructo aninhado é colocado no grupo e em sua coleção Group.Captures. Quando o caractere de fechamento é correspondido, seu caractere de abertura correspondente é removido do grupo e a coleção Captures é reduzida em um. Após a correspondência dos caracteres de abertura e fechamento de todas as construções aninhadas, 'name1' ficará vazio.</target> <note /> </trans-unit> <trans-unit id="Regex_balancing_group_short"> <source>balancing group</source> <target state="translated">grupo de balanceamento</target> <note /> </trans-unit> <trans-unit id="Regex_base_group"> <source>base-group</source> <target state="translated">grupo base</target> <note /> </trans-unit> <trans-unit id="Regex_bell_character_long"> <source>Matches a bell (alarm) character, \u0007</source> <target state="translated">Corresponde a um caractere de sino (alarme), \u0007</target> <note /> </trans-unit> <trans-unit id="Regex_bell_character_short"> <source>bell character</source> <target state="translated">caractere de sino</target> <note /> </trans-unit> <trans-unit id="Regex_carriage_return_character_long"> <source>Matches a carriage-return character, \u000D. Note that \r is not equivalent to the newline character, \n.</source> <target state="translated">Corresponde a um caractere de retorno de carro, \u000D. Observe que \r não é equivalente ao caractere de nova linha, \n.</target> <note /> </trans-unit> <trans-unit id="Regex_carriage_return_character_short"> <source>carriage-return character</source> <target state="translated">caractere de retorno de carro</target> <note /> </trans-unit> <trans-unit id="Regex_character_class_subtraction_long"> <source>Character class subtraction yields a set of characters that is the result of excluding the characters in one character class from another character class. 'base_group' is a positive or negative character group or range. The 'excluded_group' component is another positive or negative character group, or another character class subtraction expression (that is, you can nest character class subtraction expressions).</source> <target state="translated">A subtração de classe de caracteres produz um conjunto de caracteres que é o resultado da exclusão de caracteres em uma classe de caracteres de outra classe de caracteres. 'base_group' é um grupo ou intervalo de caracteres positivos ou negativos. O componente 'excluded_group' é outro grupo de caracteres positivos ou negativos ou outra expressão de subtração de classe de caracteres (ou seja, você pode aninhar expressões de subtração de classes de caracteres).</target> <note /> </trans-unit> <trans-unit id="Regex_character_class_subtraction_short"> <source>character class subtraction</source> <target state="translated">subtração de classe de caracteres</target> <note /> </trans-unit> <trans-unit id="Regex_character_group"> <source>character-group</source> <target state="translated">grupo de caracteres</target> <note /> </trans-unit> <trans-unit id="Regex_comment"> <source>comment</source> <target state="translated">comentário</target> <note /> </trans-unit> <trans-unit id="Regex_conditional_expression_match_long"> <source>This language element attempts to match one of two patterns depending on whether it can match an initial pattern. 'expression' is the initial pattern to match, 'yes' is the pattern to match if expression is matched, and 'no' is the optional pattern to match if expression is not matched.</source> <target state="translated">Este elemento de linguagem tenta corresponder a um de dois padrões, dependendo da possibilidade de correspondência com um padrão inicial. 'expression' é o padrão inicial, 'yes' é o padrão quando a expressão é correspondida e 'no' é o padrão opcional quando a expressão não é correspondida.</target> <note /> </trans-unit> <trans-unit id="Regex_conditional_expression_match_short"> <source>conditional expression match</source> <target state="translated">correspondência de expressão condicional</target> <note /> </trans-unit> <trans-unit id="Regex_conditional_group_match_long"> <source>This language element attempts to match one of two patterns depending on whether it has matched a specified capturing group. 'name' is the name (or number) of a capturing group, 'yes' is the expression to match if 'name' (or 'number') has a match, and 'no' is the optional expression to match if it does not.</source> <target state="translated">Este elemento de linguagem tenta corresponder a um de dois padrões, dependendo da correspondência a um grupo de captura especificado. 'name' é o nome (ou número) de um grupo de captura, 'yes' é a expressão a ser correspondida quando 'name' (ou 'number') é correspondido e 'no' é a expressão opcional a ser correspondida caso contrário.</target> <note /> </trans-unit> <trans-unit id="Regex_conditional_group_match_short"> <source>conditional group match</source> <target state="translated">correspondência de grupo condicional</target> <note /> </trans-unit> <trans-unit id="Regex_contiguous_matches_long"> <source>The \G anchor specifies that a match must occur at the point where the previous match ended. When you use this anchor with the Regex.Matches or Match.NextMatch method, it ensures that all matches are contiguous.</source> <target state="translated">A âncora \G especifica que uma correspondência precisa ocorrer no ponto em que a correspondência anterior foi finalizada. Quando você usa essa âncora com o método Regex.Matchs ou Match.NextMatch, ela garante que todas as correspondências sejam contíguas.</target> <note /> </trans-unit> <trans-unit id="Regex_contiguous_matches_short"> <source>contiguous matches</source> <target state="translated">correspondências contíguas</target> <note /> </trans-unit> <trans-unit id="Regex_control_character_long"> <source>Matches an ASCII control character, where X is the letter of the control character. For example, \cC is CTRL-C.</source> <target state="translated">Corresponde a um caractere de controle ASCII, em que X é a letra do caractere de controle. Por exemplo, \cC é CTRL-C.</target> <note /> </trans-unit> <trans-unit id="Regex_control_character_short"> <source>control character</source> <target state="translated">caractere de controle</target> <note /> </trans-unit> <trans-unit id="Regex_decimal_digit_character_long"> <source>\d matches any decimal digit. It is equivalent to the \p{Nd} regular expression pattern, which includes the standard decimal digits 0-9 as well as the decimal digits of a number of other character sets. If ECMAScript-compliant behavior is specified, \d is equivalent to [0-9]</source> <target state="translated">\d corresponde a qualquer dígito decimal. Equivale ao padrão de expressão regular \p{Nd}, que inclui os dígitos decimais padrão 0 a 9, bem como os dígitos decimais de vários outros conjuntos de caracteres. Se o comportamento em conformidade com o ECMAScript for especificado, \d será equivalente a [0-9]</target> <note /> </trans-unit> <trans-unit id="Regex_decimal_digit_character_short"> <source>decimal-digit character</source> <target state="translated">caractere de dígito decimal</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_line_comment_long"> <source>A number sign (#) marks an x-mode comment, which starts at the unescaped # character at the end of the regular expression pattern and continues until the end of the line. To use this construct, you must either enable the x option (through inline options) or supply the RegexOptions.IgnorePatternWhitespace value to the option parameter when instantiating the Regex object or calling a static Regex method.</source> <target state="translated">Um sinal de número (#) marca um comentário de modo x, que começa no caractere # sem escape no final do padrão de expressão regular e continua até o fim da linha. Para usar esse constructo, habilite a opção x (por meio de opções embutidas) ou forneça o valor de RegexOptions.IgnorePatternWhitespace para o parâmetro de opção ao criar a instância do objeto Regex ou chamar um método Regex estático.</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_line_comment_short"> <source>end-of-line comment</source> <target state="translated">comentário de fim da linha</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_string_only_long"> <source>The \z anchor specifies that a match must occur at the end of the input string. Like the $ language element, \z ignores the RegexOptions.Multiline option. Unlike the \Z language element, \z does not match a \n character at the end of a string. Therefore, it can only match the last line of the input string.</source> <target state="translated">A âncora \z especifica que uma correspondência precisa ocorrer no final da cadeia de caracteres de entrada. Como o elemento de linguagem $, \z ignora a opção RegexOptions.Multiline. Ao contrário do elemento de linguagem \Z, \z não corresponde a um caractere \n no final de uma cadeia de caracteres. Portanto, ele só pode corresponder à última linha da cadeia de caracteres de entrada.</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_string_only_short"> <source>end of string only</source> <target state="translated">fim da cadeia de caracteres somente</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_string_or_before_ending_newline_long"> <source>The \Z anchor specifies that a match must occur at the end of the input string, or before \n at the end of the input string. It is identical to the $ anchor, except that \Z ignores the RegexOptions.Multiline option. Therefore, in a multiline string, it can only match the end of the last line, or the last line before \n. The \Z anchor matches \n but does not match \r\n (the CR/LF character combination). To match CR/LF, include \r?\Z in the regular expression pattern.</source> <target state="translated">A âncora \Z especifica que uma correspondência precisa ocorrer no final da cadeia de caracteres de entrada ou antes de \n no final da cadeia de caracteres de entrada. Ela é idêntica à âncora $, exceto que \Z ignora a opção RegexOptions.Multiline. Portanto, em uma cadeia de caracteres multilinha, ela pode corresponder somente ao final da última linha ou à última linha antes de \n. A âncora \Z corresponde a \n, mas não corresponde à \r\n (à combinação de caracteres CR/LF). Para corresponder a CR/LF, inclua \r?\Z no padrão de expressão regular.</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_string_or_before_ending_newline_short"> <source>end of string or before ending newline</source> <target state="translated">fim da cadeia de caracteres ou antes do fim da nova linha</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_string_or_line_long"> <source>The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions.Multiline option, the match can also occur at the end of a line. The $ anchor matches \n but does not match \r\n (the combination of carriage return and newline characters, or CR/LF). To match the CR/LF character combination, include \r?$ in the regular expression pattern.</source> <target state="translated">A âncora $ especifica que o padrão anterior precisa ocorrer no final da cadeia de caracteres de entrada ou antes de \n no final da cadeia de caracteres de entrada. Se você usar $ com a opção RegexOptions.Multiline, a correspondência também poderá ocorrer no final de uma linha. A âncora $ corresponde a \n, mas não corresponde a \r\n (a combinação dos caracteres de retorno de carro e de nova linha ou CR/LF). Para a âncora corresponder à combinação de caracteres CR/LF, inclua \r?$ no padrão de expressão regular.</target> <note /> </trans-unit> <trans-unit id="Regex_end_of_string_or_line_short"> <source>end of string or line</source> <target state="translated">fim da cadeia de caracteres ou da linha</target> <note /> </trans-unit> <trans-unit id="Regex_escape_character_long"> <source>Matches an escape character, \u001B</source> <target state="translated">Corresponde a um caractere de escape, \u001B</target> <note /> </trans-unit> <trans-unit id="Regex_escape_character_short"> <source>escape character</source> <target state="translated">caractere de escape</target> <note /> </trans-unit> <trans-unit id="Regex_excluded_group"> <source>excluded-group</source> <target state="translated">grupo excluído</target> <note /> </trans-unit> <trans-unit id="Regex_expression"> <source>expression</source> <target state="translated">expressão</target> <note /> </trans-unit> <trans-unit id="Regex_form_feed_character_long"> <source>Matches a form-feed character, \u000C</source> <target state="translated">Corresponde ao caractere de avanço de página, \u000C</target> <note /> </trans-unit> <trans-unit id="Regex_form_feed_character_short"> <source>form-feed character</source> <target state="translated">caractere de avanço de página</target> <note /> </trans-unit> <trans-unit id="Regex_group_options_long"> <source>This grouping construct applies or disables the specified options within a subexpression. The options to enable are specified after the question mark, and the options to disable after the minus sign. The allowed options are: i Use case-insensitive matching. m Use multiline mode, where ^ and $ match the beginning and end of each line (instead of the beginning and end of the input string). s Use single-line mode, where the period (.) matches every character (instead of every character except \n). n Do not capture unnamed groups. The only valid captures are explicitly named or numbered groups of the form (?&lt;name&gt; subexpression). x Exclude unescaped white space from the pattern, and enable comments after a number sign (#).</source> <target state="translated">Este constructo de agrupamento aplica ou desabilita as opções especificadas dentro de uma subexpressão. As opções a serem habilitadas são especificadas após o ponto de interrogação e as opções a serem desabilitadas, após o sinal de menos. As opções permitidas são: i Usar a correspondência que não diferencia maiúsculas de minúsculas. m Usar o modo multilinha, em que ^ e $ correspondem ao início e ao fim de cada linha (em vez de ao início e ao fim da cadeia de caracteres de entrada). s Usar o modo de linha única, no qual o ponto (.) corresponde a cada caractere (em vez de a cada caractere exceto \n). n Não capturar os grupos sem nome. As únicas capturas válidas são os grupos nomeados ou numerados no formato (?&lt;name&gt; subexpressão). x Excluir o espaço em branco sem escape do padrão e habilitar os comentários após um sinal de número (#).</target> <note /> </trans-unit> <trans-unit id="Regex_group_options_short"> <source>group options</source> <target state="translated">opções de grupo</target> <note /> </trans-unit> <trans-unit id="Regex_hexadecimal_escape_long"> <source>Matches an ASCII character, where ## is a two-digit hexadecimal character code.</source> <target state="translated">Corresponde a um caractere ASCII, em que ## é um código de caractere hexadecimal de dois dígitos.</target> <note /> </trans-unit> <trans-unit id="Regex_hexadecimal_escape_short"> <source>hexadecimal escape</source> <target state="translated">escape hexadecimal</target> <note /> </trans-unit> <trans-unit id="Regex_inline_comment_long"> <source>The (?# comment) construct lets you include an inline comment in a regular expression. The regular expression engine does not use any part of the comment in pattern matching, although the comment is included in the string that is returned by the Regex.ToString method. The comment ends at the first closing parenthesis.</source> <target state="translated">O constructo (?# comentário) permite incluir um comentário embutido em uma expressão regular. O mecanismo de expressão regular não usa nenhuma parte do comentário na correspondência de padrões, embora o comentário seja incluído na cadeia de caracteres retornada pelo método Regex.ToString. O comentário termina no primeiro parêntese de fechamento.</target> <note /> </trans-unit> <trans-unit id="Regex_inline_comment_short"> <source>inline comment</source> <target state="translated">comentário embutido</target> <note /> </trans-unit> <trans-unit id="Regex_inline_options_long"> <source>Enables or disables specific pattern matching options for the remainder of a regular expression. The options to enable are specified after the question mark, and the options to disable after the minus sign. The allowed options are: i Use case-insensitive matching. m Use multiline mode, where ^ and $ match the beginning and end of each line (instead of the beginning and end of the input string). s Use single-line mode, where the period (.) matches every character (instead of every character except \n). n Do not capture unnamed groups. The only valid captures are explicitly named or numbered groups of the form (?&lt;name&gt; subexpression). x Exclude unescaped white space from the pattern, and enable comments after a number sign (#).</source> <target state="translated">Habilita ou desabilita as opções de correspondência de padrões específicas para o restante de uma expressão regular. As opções a serem habilitadas são especificadas após o ponto de interrogação e as opções a serem desabilitadas, após o sinal de menos. As opções permitidas são: i Usar a correspondência que não diferencia maiúsculas de minúsculas. m Usar o modo multilinha, no qual ^ e $ correspondem ao início e ao fim de cada linha (em vez do início e do fim da cadeia de caracteres de entrada). s Usar o modo de linha única, no qual o ponto (.) corresponde a cada caractere (em vez de cada caractere exceto \n). n Não capturar grupos sem nome. As únicas capturas válidas são os grupos nomeados ou numerados explicitamente do formato (?&lt;name&gt; subexpressão). x Excluir o espaço em branco sem escape do padrão e habilitar os comentários após um sinal de número (#).</target> <note /> </trans-unit> <trans-unit id="Regex_inline_options_short"> <source>inline options</source> <target state="translated">opções embutidas</target> <note /> </trans-unit> <trans-unit id="Regex_issue_0"> <source>Regex issue: {0}</source> <target state="translated">Problema do Regex: {0}</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. {0} will be the actual text of one of the above Regular Expression errors.</note> </trans-unit> <trans-unit id="Regex_letter_lowercase"> <source>letter, lowercase</source> <target state="translated">letra, minúscula</target> <note /> </trans-unit> <trans-unit id="Regex_letter_modifier"> <source>letter, modifier</source> <target state="translated">letra, modificador</target> <note /> </trans-unit> <trans-unit id="Regex_letter_other"> <source>letter, other</source> <target state="translated">letra, outro</target> <note /> </trans-unit> <trans-unit id="Regex_letter_titlecase"> <source>letter, titlecase</source> <target state="translated">letra, inicial maiúscula</target> <note /> </trans-unit> <trans-unit id="Regex_letter_uppercase"> <source>letter, uppercase</source> <target state="translated">letra, maiúscula</target> <note /> </trans-unit> <trans-unit id="Regex_mark_enclosing"> <source>mark, enclosing</source> <target state="translated">marca, delimitação</target> <note /> </trans-unit> <trans-unit id="Regex_mark_nonspacing"> <source>mark, nonspacing</source> <target state="translated">marca, não espaçamento</target> <note /> </trans-unit> <trans-unit id="Regex_mark_spacing_combining"> <source>mark, spacing combining</source> <target state="translated">marca, combinação de espaçamento</target> <note /> </trans-unit> <trans-unit id="Regex_match_at_least_n_times_lazy_long"> <source>The {n,}? quantifier matches the preceding element at least n times, where n is any integer, but as few times as possible. It is the lazy counterpart of the greedy quantifier {n,}</source> <target state="translated">O quantificador {n,}? corresponde ao elemento precedente pelo menos n vezes, em que n é qualquer inteiro, mas o menor número de vezes possível. Ele é a contraparte lenta do quantificador greedy {n,}</target> <note /> </trans-unit> <trans-unit id="Regex_match_at_least_n_times_lazy_short"> <source>match at least 'n' times (lazy)</source> <target state="translated">corresponder pelo menos 'n' vezes (lento)</target> <note /> </trans-unit> <trans-unit id="Regex_match_at_least_n_times_long"> <source>The {n,} quantifier matches the preceding element at least n times, where n is any integer. {n,} is a greedy quantifier whose lazy equivalent is {n,}?</source> <target state="translated">O quantificador {n,} corresponde ao elemento precedente pelo menos n vezes, em que n é qualquer número inteiro. {n,} é um quantificador greedy cujo equivalente lento é {n,}?</target> <note /> </trans-unit> <trans-unit id="Regex_match_at_least_n_times_short"> <source>match at least 'n' times</source> <target state="translated">corresponder a pelo menos 'n' vezes</target> <note /> </trans-unit> <trans-unit id="Regex_match_between_m_and_n_times_lazy_long"> <source>The {n,m}? quantifier matches the preceding element between n and m times, where n and m are integers, but as few times as possible. It is the lazy counterpart of the greedy quantifier {n,m}</source> <target state="translated">O quantificador {n,m}? corresponde ao elemento precedente entre n e m vezes, em que n e m são inteiros, mas o menor número de vezes possível. Ele é a contraparte lenta do quantificador greedy {n,m}</target> <note /> </trans-unit> <trans-unit id="Regex_match_between_m_and_n_times_lazy_short"> <source>match at least 'n' times (lazy)</source> <target state="translated">corresponder pelo menos 'n' vezes (lento)</target> <note /> </trans-unit> <trans-unit id="Regex_match_between_m_and_n_times_long"> <source>The {n,m} quantifier matches the preceding element at least n times, but no more than m times, where n and m are integers. {n,m} is a greedy quantifier whose lazy equivalent is {n,m}?</source> <target state="translated">O quantificador {n,m} corresponde ao elemento precedente pelo menos n vezes, mas no máximo m vezes, em que n e m são inteiros. {n,m} é um quantificador greedy cujo equivalente lento é {n,m}?</target> <note /> </trans-unit> <trans-unit id="Regex_match_between_m_and_n_times_short"> <source>match between 'm' and 'n' times</source> <target state="translated">corresponder entre 'm' e 'n' vezes</target> <note /> </trans-unit> <trans-unit id="Regex_match_exactly_n_times_lazy_long"> <source>The {n}? quantifier matches the preceding element exactly n times, where n is any integer. It is the lazy counterpart of the greedy quantifier {n}+</source> <target state="translated">O quantificador {n}? corresponde ao elemento precedente exatamente n vezes, em que n é qualquer inteiro. Ele é a contraparte lenta do quantificador greedy {n}+</target> <note /> </trans-unit> <trans-unit id="Regex_match_exactly_n_times_lazy_short"> <source>match exactly 'n' times (lazy)</source> <target state="translated">corresponder exatamente 'n' vezes (lento)</target> <note /> </trans-unit> <trans-unit id="Regex_match_exactly_n_times_long"> <source>The {n} quantifier matches the preceding element exactly n times, where n is any integer. {n} is a greedy quantifier whose lazy equivalent is {n}?</source> <target state="translated">O quantificador {n} corresponde ao elemento precedente exatamente n vezes, em que n é qualquer número inteiro. {n} é um quantificador greedy cujo equivalente lento é {n}?</target> <note /> </trans-unit> <trans-unit id="Regex_match_exactly_n_times_short"> <source>match exactly 'n' times</source> <target state="translated">corresponder exatamente 'n' vezes</target> <note /> </trans-unit> <trans-unit id="Regex_match_one_or_more_times_lazy_long"> <source>The +? quantifier matches the preceding element one or more times, but as few times as possible. It is the lazy counterpart of the greedy quantifier +</source> <target state="translated">O quantificador +? corresponde ao elemento precedente uma ou mais vezes, mas o menor número de vezes possível. Ele é a contraparte lenta do quantificador greedy +</target> <note /> </trans-unit> <trans-unit id="Regex_match_one_or_more_times_lazy_short"> <source>match one or more times (lazy)</source> <target state="translated">corresponder uma ou mais vezes (lento)</target> <note /> </trans-unit> <trans-unit id="Regex_match_one_or_more_times_long"> <source>The + quantifier matches the preceding element one or more times. It is equivalent to the {1,} quantifier. + is a greedy quantifier whose lazy equivalent is +?.</source> <target state="translated">O quantificador + corresponde ao elemento precedente uma ou mais vezes. Ele equivale ao quantificador {1,}. + é um quantificador greedy cujo equivalente lento é +?.</target> <note /> </trans-unit> <trans-unit id="Regex_match_one_or_more_times_short"> <source>match one or more times</source> <target state="translated">corresponder uma ou mais vezes</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_more_times_lazy_long"> <source>The *? quantifier matches the preceding element zero or more times, but as few times as possible. It is the lazy counterpart of the greedy quantifier *</source> <target state="translated">O quantificador *? corresponde ao elemento precedente zero ou mais vezes, mas o menor número de vezes possível. Ele é a contraparte lenta do quantificador greedy *</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_more_times_lazy_short"> <source>match zero or more times (lazy)</source> <target state="translated">corresponder zero ou mais vezes (lento)</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_more_times_long"> <source>The * quantifier matches the preceding element zero or more times. It is equivalent to the {0,} quantifier. * is a greedy quantifier whose lazy equivalent is *?.</source> <target state="translated">O quantificador * corresponde ao elemento precedente zero ou mais vezes. Ele equivale ao quantificador {0,}. * é um quantificador greedy cujo equivalente lento é *?.</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_more_times_short"> <source>match zero or more times</source> <target state="translated">corresponder zero ou mais vezes</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_one_time_lazy_long"> <source>The ?? quantifier matches the preceding element zero or one time, but as few times as possible. It is the lazy counterpart of the greedy quantifier ?</source> <target state="translated">O quantificador ?? corresponde ao elemento precedente zero ou uma vez, mas o menor número de vezes possível. Ele é a contraparte lenta do quantificador greedy ?</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_one_time_lazy_short"> <source>match zero or one time (lazy)</source> <target state="translated">corresponder nenhuma ou uma vez (lento)</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_one_time_long"> <source>The ? quantifier matches the preceding element zero or one time. It is equivalent to the {0,1} quantifier. ? is a greedy quantifier whose lazy equivalent is ??.</source> <target state="translated">O quantificador ? corresponde ao elemento precedente zero ou uma vez. Ele equivale ao quantificador {0,1}. ? é um quantificador greedy cujo equivalente lento é ??.</target> <note /> </trans-unit> <trans-unit id="Regex_match_zero_or_one_time_short"> <source>match zero or one time</source> <target state="translated">corresponder nenhuma ou uma vez</target> <note /> </trans-unit> <trans-unit id="Regex_matched_subexpression_long"> <source>This grouping construct captures a matched 'subexpression', where 'subexpression' is any valid regular expression pattern. Captures that use parentheses are numbered automatically from left to right based on the order of the opening parentheses in the regular expression, starting from one. The capture that is numbered zero is the text matched by the entire regular expression pattern.</source> <target state="translated">Este constructo de agrupamento captura uma 'subexpression' correspondente, em que 'subexpression' é qualquer padrão de expressão regular válido. As capturas que usam parênteses são numeradas automaticamente da esquerda para a direita com base na ordem dos parênteses de abertura na expressão regular, começando com um. A captura numerada como zero é o texto correspondente ao padrão de expressão regular inteiro.</target> <note /> </trans-unit> <trans-unit id="Regex_matched_subexpression_short"> <source>matched subexpression</source> <target state="translated">subexpressão correspondente</target> <note /> </trans-unit> <trans-unit id="Regex_name"> <source>name</source> <target state="translated">nome</target> <note /> </trans-unit> <trans-unit id="Regex_name1"> <source>name1</source> <target state="translated">name1</target> <note /> </trans-unit> <trans-unit id="Regex_name2"> <source>name2</source> <target state="translated">name2</target> <note /> </trans-unit> <trans-unit id="Regex_name_or_number"> <source>name-or-number</source> <target state="translated">nome ou número</target> <note /> </trans-unit> <trans-unit id="Regex_named_backreference_long"> <source>A named or numbered backreference. 'name' is the name of a capturing group defined in the regular expression pattern.</source> <target state="translated">Uma referência inversa nomeada ou numerada. 'name' é o nome de um grupo de captura definido no padrão de expressão regular.</target> <note /> </trans-unit> <trans-unit id="Regex_named_backreference_short"> <source>named backreference</source> <target state="translated">referência inversa nomeada</target> <note /> </trans-unit> <trans-unit id="Regex_named_matched_subexpression_long"> <source>Captures a matched subexpression and lets you access it by name or by number. 'name' is a valid group name, and 'subexpression' is any valid regular expression pattern. 'name' must not contain any punctuation characters and cannot begin with a number. If the RegexOptions parameter of a regular expression pattern matching method includes the RegexOptions.ExplicitCapture flag, or if the n option is applied to this subexpression, the only way to capture a subexpression is to explicitly name capturing groups.</source> <target state="translated">Captura uma subexpressão correspondida e permite que você a acesse por nome ou número. 'name' é um nome de grupo válido e 'subexpression' é qualquer padrão de expressão regular válido. 'name' não pode conter nenhum caractere de pontuação e não pode começar com um número. Se o parâmetro RegexOptions de um método de correspondência de padrões de expressão regular incluir o sinalizador RegexOptions.ExplicitCapture ou se a opção n for aplicada a essa subexpressão, a única maneira de capturar uma subexpressão será nomear explicitamente os grupos de captura.</target> <note /> </trans-unit> <trans-unit id="Regex_named_matched_subexpression_short"> <source>named matched subexpression</source> <target state="translated">subexpressão de correspondência nomeada</target> <note /> </trans-unit> <trans-unit id="Regex_negative_character_group_long"> <source>A negative character group specifies a list of characters that must not appear in an input string for a match to occur. The list of characters are specified individually. Two or more character ranges can be concatenated. For example, to specify the range of decimal digits from "0" through "9", the range of lowercase letters from "a" through "f", and the range of uppercase letters from "A" through "F", use [0-9a-fA-F].</source> <target state="translated">Um grupo de caracteres negativos especifica uma lista de caracteres que não podem aparecer em uma cadeia de caracteres de entrada para que uma correspondência ocorra. A lista de caracteres é especificada individualmente. Dois ou mais intervalos de caracteres podem ser concatenados. Por exemplo, para especificar o intervalo de dígitos decimais de "0" a "9", o intervalo de letras minúsculas de "a" até "f" e o intervalo de letras maiúsculas de "A" até "F", use [0-9a-fA-F].</target> <note /> </trans-unit> <trans-unit id="Regex_negative_character_group_short"> <source>negative character group</source> <target state="translated">grupo de caracteres negativos</target> <note /> </trans-unit> <trans-unit id="Regex_negative_character_range_long"> <source>A negative character range specifies a list of characters that must not appear in an input string for a match to occur. 'firstCharacter' is the character that begins the range, and 'lastCharacter' is the character that ends the range. Two or more character ranges can be concatenated. For example, to specify the range of decimal digits from "0" through "9", the range of lowercase letters from "a" through "f", and the range of uppercase letters from "A" through "F", use [0-9a-fA-F].</source> <target state="translated">Um intervalo de caracteres negativos especifica uma lista de caracteres que não podem aparecer em uma cadeia de caracteres de entrada para que uma correspondência ocorra. 'firstCharacter' é o caractere que inicia o intervalo e 'lastCharacter' é o caractere que termina o intervalo. Dois ou mais intervalos de caracteres podem ser concatenados. Por exemplo, para especificar o intervalo de dígitos decimais de "0" a "9", o intervalo de letras minúsculas de "a" até "f" e o intervalo de letras maiúsculas de "A" até "F", use [0-9a-fA-F].</target> <note /> </trans-unit> <trans-unit id="Regex_negative_character_range_short"> <source>negative character range</source> <target state="translated">intervalo de caracteres negativos</target> <note /> </trans-unit> <trans-unit id="Regex_negative_unicode_category_long"> <source>The regular expression construct \P{ name } matches any character that does not belong to a Unicode general category or named block, where name is the category abbreviation or named block name.</source> <target state="translated">O constructo de expressão regular \P{ name } corresponde a qualquer caractere que não pertença a uma categoria Unicode genérica nem a um bloco nomeado, em que o nome seja a abreviação da categoria ou o nome do bloco nomeado.</target> <note /> </trans-unit> <trans-unit id="Regex_negative_unicode_category_short"> <source>negative unicode category</source> <target state="translated">categoria unicode negativa</target> <note /> </trans-unit> <trans-unit id="Regex_new_line_character_long"> <source>Matches a new-line character, \u000A</source> <target state="translated">Corresponde a um caractere de nova linha, \u000A</target> <note /> </trans-unit> <trans-unit id="Regex_new_line_character_short"> <source>new-line character</source> <target state="translated">caractere de nova linha</target> <note /> </trans-unit> <trans-unit id="Regex_no"> <source>no</source> <target state="translated">não</target> <note /> </trans-unit> <trans-unit id="Regex_non_digit_character_long"> <source>\D matches any non-digit character. It is equivalent to the \P{Nd} regular expression pattern. If ECMAScript-compliant behavior is specified, \D is equivalent to [^0-9]</source> <target state="translated">\D corresponde a qualquer caractere que não seja um dígito. Ele equivale ao padrão de expressão regular \p{Nd}. Se o comportamento em conformidade com o ECMAScript for especificado, \D será equivalente a [^0-9]</target> <note /> </trans-unit> <trans-unit id="Regex_non_digit_character_short"> <source>non-digit character</source> <target state="translated">caractere que não é dígito</target> <note /> </trans-unit> <trans-unit id="Regex_non_white_space_character_long"> <source>\S matches any non-white-space character. It is equivalent to the [^\f\n\r\t\v\x85\p{Z}] regular expression pattern, or the opposite of the regular expression pattern that is equivalent to \s, which matches white-space characters. If ECMAScript-compliant behavior is specified, \S is equivalent to [^ \f\n\r\t\v]</source> <target state="translated">\S corresponde a qualquer caractere que não seja um espaço em branco. Ele equivale ao padrão de expressão regular [^\f\n\r\t\v\x85\p{Z}] ou ao oposto do padrão de expressão regular equivalente a \s, que corresponde a caracteres de espaço em branco. Se o comportamento em conformidade com o ECMAScript for especificado, \S será equivalente a [^ \f\n\r\t\v]</target> <note /> </trans-unit> <trans-unit id="Regex_non_white_space_character_short"> <source>non-white-space character</source> <target state="translated">caractere que não é de espaço em branco</target> <note /> </trans-unit> <trans-unit id="Regex_non_word_boundary_long"> <source>The \B anchor specifies that the match must not occur on a word boundary. It is the opposite of the \b anchor.</source> <target state="translated">A âncora \B especifica que a correspondência não pode ocorrer em um limite de palavra. Ela é o oposto da âncora \b.</target> <note /> </trans-unit> <trans-unit id="Regex_non_word_boundary_short"> <source>non-word boundary</source> <target state="translated">limite que não é de palavra</target> <note /> </trans-unit> <trans-unit id="Regex_non_word_character_long"> <source>\W matches any non-word character. It matches any character except for those in the following Unicode categories: Ll Letter, Lowercase Lu Letter, Uppercase Lt Letter, Titlecase Lo Letter, Other Lm Letter, Modifier Mn Mark, Nonspacing Nd Number, Decimal Digit Pc Punctuation, Connector If ECMAScript-compliant behavior is specified, \W is equivalent to [^a-zA-Z_0-9]</source> <target state="translated">\W corresponde a qualquer caractere que não seja uma palavra. Ele corresponde a qualquer caractere, exceto os das categorias Unicode a seguir: Ll Letra, Minúscula Lu Letra, Maiúscula Lt Letra, Inicial Maiúscula Lo Letra, Outro Lm Letra, Modificador Mn Marca, Não Espaçamento Nd Número, Dígito Decimal Pc Pontuação, Conector Se o comportamento em conformidade com o ECMAScript for especificado, \W será equivalente a [^a-zA-Z_0-9]</target> <note>Note: Ll, Lu, Lt, Lo, Lm, Mn, Nd, and Pc are all things that should not be localized. </note> </trans-unit> <trans-unit id="Regex_non_word_character_short"> <source>non-word character</source> <target state="translated">caractere que não é palavra</target> <note /> </trans-unit> <trans-unit id="Regex_noncapturing_group_long"> <source>This construct does not capture the substring that is matched by a subexpression: The noncapturing group construct is typically used when a quantifier is applied to a group, but the substrings captured by the group are of no interest. If a regular expression includes nested grouping constructs, an outer noncapturing group construct does not apply to the inner nested group constructs.</source> <target state="translated">Este constructo não captura a substring correspondida por uma subexpressão: O constructo do grupo que não é de captura geralmente é usado quando um quantificador é aplicado a um grupo, mas as substrings capturadas pelo grupo não são de interesse. Se uma expressão regular inclui constructos de agrupamento aninhado, um constructo externo de grupo de não captura não se aplica aos constructos internos de grupo aninhado.</target> <note /> </trans-unit> <trans-unit id="Regex_noncapturing_group_short"> <source>noncapturing group</source> <target state="translated">grupo que não é de captura</target> <note /> </trans-unit> <trans-unit id="Regex_number_decimal_digit"> <source>number, decimal digit</source> <target state="translated">número, dígito decimal</target> <note /> </trans-unit> <trans-unit id="Regex_number_letter"> <source>number, letter</source> <target state="translated">número, letra</target> <note /> </trans-unit> <trans-unit id="Regex_number_other"> <source>number, other</source> <target state="translated">número, outro</target> <note /> </trans-unit> <trans-unit id="Regex_numbered_backreference_long"> <source>A numbered backreference, where 'number' is the ordinal position of the capturing group in the regular expression. For example, \4 matches the contents of the fourth capturing group. There is an ambiguity between octal escape codes (such as \16) and \number backreferences that use the same notation. If the ambiguity is a problem, you can use the \k&lt;name&gt; notation, which is unambiguous and cannot be confused with octal character codes. Similarly, hexadecimal codes such as \xdd are unambiguous and cannot be confused with backreferences.</source> <target state="translated">Uma referência inversa numerada, em que 'number' é a posição ordinal do grupo de captura na expressão regular. Por exemplo, \4 corresponde ao conteúdo do quarto grupo de captura. Há uma ambiguidade entre os códigos de escape octais (como \16) e as referências inversas \number que usam a mesma notação. Se a ambiguidade causar algum problema, use a notação \k&lt;name&gt;, que não é ambígua e não pode ser confundida com códigos de caracteres octais. Da mesma forma, os códigos hexadecimais como \xdd não são ambíguos e não podem ser confundidos com referências inversas.</target> <note /> </trans-unit> <trans-unit id="Regex_numbered_backreference_short"> <source>numbered backreference</source> <target state="translated">referência inversa numerada</target> <note /> </trans-unit> <trans-unit id="Regex_other_control"> <source>other, control</source> <target state="translated">outro, controle</target> <note /> </trans-unit> <trans-unit id="Regex_other_format"> <source>other, format</source> <target state="translated">outro, formato</target> <note /> </trans-unit> <trans-unit id="Regex_other_not_assigned"> <source>other, not assigned</source> <target state="translated">outro, não atribuído</target> <note /> </trans-unit> <trans-unit id="Regex_other_private_use"> <source>other, private use</source> <target state="translated">outro, uso privado</target> <note /> </trans-unit> <trans-unit id="Regex_other_surrogate"> <source>other, surrogate</source> <target state="translated">outro, alternativo</target> <note /> </trans-unit> <trans-unit id="Regex_positive_character_group_long"> <source>A positive character group specifies a list of characters, any one of which may appear in an input string for a match to occur.</source> <target state="translated">Um grupo de caracteres positivos especifica uma lista de caracteres, em que qualquer um deles pode aparecer em uma cadeia de caracteres de entrada para que uma correspondência ocorra.</target> <note /> </trans-unit> <trans-unit id="Regex_positive_character_group_short"> <source>positive character group</source> <target state="translated">grupo de caracteres positivos</target> <note /> </trans-unit> <trans-unit id="Regex_positive_character_range_long"> <source>A positive character range specifies a range of characters, any one of which may appear in an input string for a match to occur. 'firstCharacter' is the character that begins the range and 'lastCharacter' is the character that ends the range. </source> <target state="translated">Um intervalo de caracteres positivos especifica um intervalo de caracteres, em que qualquer um deles pode aparecer em uma cadeia de caracteres de entrada para que uma correspondência ocorra. 'firstCharacter' é o caractere que inicia o intervalo e 'lastCharacter' é o caractere que termina o intervalo. </target> <note /> </trans-unit> <trans-unit id="Regex_positive_character_range_short"> <source>positive character range</source> <target state="translated">intervalo de caracteres positivos</target> <note /> </trans-unit> <trans-unit id="Regex_punctuation_close"> <source>punctuation, close</source> <target state="translated">pontuação, fechar</target> <note /> </trans-unit> <trans-unit id="Regex_punctuation_connector"> <source>punctuation, connector</source> <target state="translated">pontuação, conector</target> <note /> </trans-unit> <trans-unit id="Regex_punctuation_dash"> <source>punctuation, dash</source> <target state="translated">pontuação, traço</target> <note /> </trans-unit> <trans-unit id="Regex_punctuation_final_quote"> <source>punctuation, final quote</source> <target state="translated">pontuação, aspa final</target> <note /> </trans-unit> <trans-unit id="Regex_punctuation_initial_quote"> <source>punctuation, initial quote</source> <target state="translated">pontuação, aspa inicial</target> <note /> </trans-unit> <trans-unit id="Regex_punctuation_open"> <source>punctuation, open</source> <target state="translated">pontuação, abrir</target> <note /> </trans-unit> <trans-unit id="Regex_punctuation_other"> <source>punctuation, other</source> <target state="translated">pontuação, outros</target> <note /> </trans-unit> <trans-unit id="Regex_separator_line"> <source>separator, line</source> <target state="translated">separador, linha</target> <note /> </trans-unit> <trans-unit id="Regex_separator_paragraph"> <source>separator, paragraph</source> <target state="translated">separador, parágrafo</target> <note /> </trans-unit> <trans-unit id="Regex_separator_space"> <source>separator, space</source> <target state="translated">separador, espaço</target> <note /> </trans-unit> <trans-unit id="Regex_start_of_string_only_long"> <source>The \A anchor specifies that a match must occur at the beginning of the input string. It is identical to the ^ anchor, except that \A ignores the RegexOptions.Multiline option. Therefore, it can only match the start of the first line in a multiline input string.</source> <target state="translated">A âncora \A especifica que uma correspondência precisa ocorrer no início da cadeia de caracteres de entrada. Ela é idêntica à âncora ^, exceto que \A ignora a opção RegexOptions.Multiline. Portanto, ela só pode corresponder ao início da primeira linha em uma cadeia de caracteres de entrada multilinha.</target> <note /> </trans-unit> <trans-unit id="Regex_start_of_string_only_short"> <source>start of string only</source> <target state="translated">somente início de cadeia de caracteres</target> <note /> </trans-unit> <trans-unit id="Regex_start_of_string_or_line_long"> <source>The ^ anchor specifies that the following pattern must begin at the first character position of the string. If you use ^ with the RegexOptions.Multiline option, the match must occur at the beginning of each line.</source> <target state="translated">A âncora ^ especifica que o padrão a seguir precisa começar na primeira posição de caractere da cadeia de caracteres. Se você usar ^ com a opção RegexOptions.Multiline, a correspondência deverá ocorrer no início de cada linha.</target> <note /> </trans-unit> <trans-unit id="Regex_start_of_string_or_line_short"> <source>start of string or line</source> <target state="translated">início de cadeia de caracteres ou de linha</target> <note /> </trans-unit> <trans-unit id="Regex_subexpression"> <source>subexpression</source> <target state="translated">subexpressão</target> <note /> </trans-unit> <trans-unit id="Regex_symbol_currency"> <source>symbol, currency</source> <target state="translated">símbolo, moeda</target> <note /> </trans-unit> <trans-unit id="Regex_symbol_math"> <source>symbol, math</source> <target state="translated">símbolo, matemática</target> <note /> </trans-unit> <trans-unit id="Regex_symbol_modifier"> <source>symbol, modifier</source> <target state="translated">símbolo, modificador</target> <note /> </trans-unit> <trans-unit id="Regex_symbol_other"> <source>symbol, other</source> <target state="translated">símbolo, outro</target> <note /> </trans-unit> <trans-unit id="Regex_tab_character_long"> <source>Matches a tab character, \u0009</source> <target state="translated">Corresponde a um caractere de tabulação, \u0009</target> <note /> </trans-unit> <trans-unit id="Regex_tab_character_short"> <source>tab character</source> <target state="translated">caractere de tabulação</target> <note /> </trans-unit> <trans-unit id="Regex_unicode_category_long"> <source>The regular expression construct \p{ name } matches any character that belongs to a Unicode general category or named block, where name is the category abbreviation or named block name.</source> <target state="translated">O constructo de expressão regular \p{ name } corresponde a qualquer caractere que pertença a uma categoria genérica Unicode ou a um bloco nomeado, em que o nome seja a abreviação da categoria ou o nome do bloco nomeado.</target> <note /> </trans-unit> <trans-unit id="Regex_unicode_category_short"> <source>unicode category</source> <target state="translated">categoria unicode</target> <note /> </trans-unit> <trans-unit id="Regex_unicode_escape_long"> <source>Matches a UTF-16 code unit whose value is #### hexadecimal.</source> <target state="translated">Corresponde a uma unidade de código UTF-16 cujo valor é o hexadecimal ####.</target> <note /> </trans-unit> <trans-unit id="Regex_unicode_escape_short"> <source>unicode escape</source> <target state="translated">escape unicode</target> <note /> </trans-unit> <trans-unit id="Regex_unicode_general_category_0"> <source>Unicode General Category: {0}</source> <target state="translated">Categoria Geral Unicode: {0}</target> <note /> </trans-unit> <trans-unit id="Regex_vertical_tab_character_long"> <source>Matches a vertical-tab character, \u000B</source> <target state="translated">Corresponde a um caractere de tabulação vertical, \u000B</target> <note /> </trans-unit> <trans-unit id="Regex_vertical_tab_character_short"> <source>vertical-tab character</source> <target state="translated">caractere de tabulação vertical</target> <note /> </trans-unit> <trans-unit id="Regex_white_space_character_long"> <source>\s matches any white-space character. It is equivalent to the following escape sequences and Unicode categories: \f The form feed character, \u000C \n The newline character, \u000A \r The carriage return character, \u000D \t The tab character, \u0009 \v The vertical tab character, \u000B \x85 The ellipsis or NEXT LINE (NEL) character (…), \u0085 \p{Z} Matches any separator character If ECMAScript-compliant behavior is specified, \s is equivalent to [ \f\n\r\t\v]</source> <target state="translated">\s corresponde a qualquer caractere de espaço em branco. Ele equivale às seguintes sequências de escape e categorias Unicode: \f O caractere de avanço de página, \u000C \n O caractere de nova linha, \u000A \r O caractere de retorno de carro, \u000D \t O caractere de tabulação, \u0009 \v O caractere de tabulação vertical, \u000B \x85 A elipse ou o caractere NEL (NOVA LINHA) (...), \u0085 \p{Z} Corresponde a qualquer caractere separador Se o comportamento em conformidade com o ECMAScript for especificado, \s será equivalente a [ \f\n\r\t\v]</target> <note /> </trans-unit> <trans-unit id="Regex_white_space_character_short"> <source>white-space character</source> <target state="translated">o caractere de espaço em branco</target> <note /> </trans-unit> <trans-unit id="Regex_word_boundary_long"> <source>The \b anchor specifies that the match must occur on a boundary between a word character (the \w language element) and a non-word character (the \W language element). Word characters consist of alphanumeric characters and underscores; a non-word character is any character that is not alphanumeric or an underscore. The match may also occur on a word boundary at the beginning or end of the string. The \b anchor is frequently used to ensure that a subexpression matches an entire word instead of just the beginning or end of a word.</source> <target state="translated">A âncora \b especifica que a correspondência precisa ocorrer em um limite entre um caractere de palavra (o elemento de linguagem \w) e um caractere que não seja de palavra (o elemento de linguagem \W). Os caracteres de palavra consistem em caracteres alfanuméricos e sublinhados; um caractere que não é de palavra é qualquer caractere que não é alfanumérico nem sublinhado. A correspondência também pode ocorrer em um limite de palavra no início ou no fim da cadeia de caracteres. A âncora \b é usada geralmente para garantir que uma subexpressão corresponda a uma palavra inteira em vez de apenas ao início ou ao fim de uma palavra.</target> <note /> </trans-unit> <trans-unit id="Regex_word_boundary_short"> <source>word boundary</source> <target state="translated">limite de palavra</target> <note /> </trans-unit> <trans-unit id="Regex_word_character_long"> <source>\w matches any word character. A word character is a member of any of the following Unicode categories: Ll Letter, Lowercase Lu Letter, Uppercase Lt Letter, Titlecase Lo Letter, Other Lm Letter, Modifier Mn Mark, Nonspacing Nd Number, Decimal Digit Pc Punctuation, Connector If ECMAScript-compliant behavior is specified, \w is equivalent to [a-zA-Z_0-9]</source> <target state="translated">\w corresponde a qualquer caractere de palavra. Um caractere de palavra é membro de qualquer uma das seguintes categorias Unicode: Ll Letra, Minúscula Lu Letra, Maiúscula Lt Letra, Inicial Maiúscula Lo Letra, Outro Lm Letra, Modificador Mn Marca, Não Espaçamento Nd Número, Dígito Decimal Pc Pontuação, Conector Se o comportamento em conformidade com o ECMAScript for especificado, \w será equivalente a [a-zA-Z_0-9]</target> <note>Note: Ll, Lu, Lt, Lo, Lm, Mn, Nd, and Pc are all things that should not be localized.</note> </trans-unit> <trans-unit id="Regex_word_character_short"> <source>word character</source> <target state="translated">caractere de palavra</target> <note /> </trans-unit> <trans-unit id="Regex_yes"> <source>yes</source> <target state="translated">sim</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_negative_lookahead_assertion_long"> <source>A zero-width negative lookahead assertion, where for the match to be successful, the input string must not match the regular expression pattern in subexpression. The matched string is not included in the match result. A zero-width negative lookahead assertion is typically used either at the beginning or at the end of a regular expression. At the beginning of a regular expression, it can define a specific pattern that should not be matched when the beginning of the regular expression defines a similar but more general pattern to be matched. In this case, it is often used to limit backtracking. At the end of a regular expression, it can define a subexpression that cannot occur at the end of a match.</source> <target state="translated">Uma asserção lookahead negativa de largura zero, em que, para que a correspondência seja bem-sucedida, a cadeia de caracteres de entrada não pode corresponder ao padrão de expressão regular na subexpressão. A cadeia de caracteres correspondente não está incluída no resultado correspondente. Uma asserção lookahead negativa de largura zero normalmente é usada no início ou no final de uma expressão regular. No início de uma expressão regular, ela pode definir um padrão específico que não deve ser correspondido quando o início da expressão regular define um padrão semelhante, mas mais geral, a ser correspondido. Nesse caso, ela geralmente é usada para limitar o rastreamento inverso. No final de uma expressão regular, ela pode definir uma subexpressão que não pode ocorrer no final de uma correspondência.</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_negative_lookahead_assertion_short"> <source>zero-width negative lookahead assertion</source> <target state="translated">asserção lookahead negativa de largura zero</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_negative_lookbehind_assertion_long"> <source>A zero-width negative lookbehind assertion, where for a match to be successful, 'subexpression' must not occur at the input string to the left of the current position. Any substring that does not match 'subexpression' is not included in the match result. Zero-width negative lookbehind assertions are typically used at the beginning of regular expressions. The pattern that they define precludes a match in the string that follows. They are also used to limit backtracking when the last character or characters in a captured group must not be one or more of the characters that match that group's regular expression pattern.</source> <target state="translated">Uma asserção lookbehind negativa de largura zero, em que, para que uma correspondência seja bem-sucedida, a 'subexpression' não pode ocorrer na cadeia de caracteres de entrada à esquerda da posição atual. As substrings que não corresponderem à 'subexpression' não serão incluídas no resultado correspondente. As declarações de lookbehind negativas de largura zero normalmente são usadas no início de expressões regulares. O padrão que elas definem impede uma correspondência na cadeia de caracteres seguinte. Elas também são usadas para limitar o rastreamento inverso quando o último caractere ou caracteres em um grupo capturado não pode ser um ou mais dos caracteres que correspondem ao padrão dessa expressão regular do grupo.</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_negative_lookbehind_assertion_short"> <source>zero-width negative lookbehind assertion</source> <target state="translated">asserção lookbehind negativa de largura zero</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_positive_lookahead_assertion_long"> <source>A zero-width positive lookahead assertion, where for a match to be successful, the input string must match the regular expression pattern in 'subexpression'. The matched substring is not included in the match result. A zero-width positive lookahead assertion does not backtrack. Typically, a zero-width positive lookahead assertion is found at the end of a regular expression pattern. It defines a substring that must be found at the end of a string for a match to occur but that should not be included in the match. It is also useful for preventing excessive backtracking. You can use a zero-width positive lookahead assertion to ensure that a particular captured group begins with text that matches a subset of the pattern defined for that captured group.</source> <target state="translated">Uma asserção lookahead positiva de largura zero, em que para que uma correspondência seja bem-sucedida, a cadeia de caracteres de entrada precisa corresponder ao padrão de expressão regular na 'subexpression'. A substring correspondente não é incluída no resultado correspondente. Uma asserção lookahead positiva de largura zero não retrocede. Normalmente, uma asserção lookahead positiva de largura zero é encontrada no final de um padrão de expressão regular. Ela define uma substring que precisa ser encontrada no final de uma cadeia de caracteres para que uma correspondência ocorra, mas que não deve ser incluída na correspondência. Ela também é útil para impedir o rastreamento inverso excessivo. Você pode usar uma asserção lookahead positiva de largura zero para garantir que um determinado grupo capturado comece com um texto que corresponda a um subconjunto do padrão definido para esse grupo capturado.</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_positive_lookahead_assertion_short"> <source>zero-width positive lookahead assertion</source> <target state="translated">asserção lookahead positiva de largura zero</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_positive_lookbehind_assertion_long"> <source>A zero-width positive lookbehind assertion, where for a match to be successful, 'subexpression' must occur at the input string to the left of the current position. 'subexpression' is not included in the match result. A zero-width positive lookbehind assertion does not backtrack. Zero-width positive lookbehind assertions are typically used at the beginning of regular expressions. The pattern that they define is a precondition for a match, although it is not a part of the match result.</source> <target state="translated">Uma asserção lookbehind positiva de largura zero, em que, para que uma correspondência seja bem-sucedida, a 'subexpression' precisa ocorrer na cadeia de caracteres de entrada à esquerda da posição atual. A 'subexpression' não é incluída no resultado correspondente. Uma asserção lookbehind positiva de largura zero não retrocede. As declarações de lookbehind positivas de largura zero normalmente são usadas no início de expressões regulares. O padrão que elas definem é uma pré-condição para uma correspondência, apesar de não fazer parte do resultado correspondente.</target> <note /> </trans-unit> <trans-unit id="Regex_zero_width_positive_lookbehind_assertion_short"> <source>zero-width positive lookbehind assertion</source> <target state="translated">asserção lookbehind positiva de largura zero</target> <note /> </trans-unit> <trans-unit id="Related_method_signatures_found_in_metadata_will_not_be_updated"> <source>Related method signatures found in metadata will not be updated.</source> <target state="translated">As assinaturas de método relacionadas encontradas nos metadados não serão atualizadas.</target> <note /> </trans-unit> <trans-unit id="Removal_of_document_not_supported"> <source>Removal of document not supported</source> <target state="translated">Não há suporte para a remoção do documento</target> <note /> </trans-unit> <trans-unit id="Remove_async_modifier"> <source>Remove 'async' modifier</source> <target state="translated">Remover o modificador 'async'</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_casts"> <source>Remove unnecessary casts</source> <target state="translated">Remover conversões desnecessárias</target> <note /> </trans-unit> <trans-unit id="Remove_unused_variables"> <source>Remove unused variables</source> <target state="translated">Remover variáveis não utilizadas</target> <note /> </trans-unit> <trans-unit id="Removing_0_that_accessed_captured_variables_1_and_2_declared_in_different_scopes_requires_restarting_the_application"> <source>Removing {0} that accessed captured variables '{1}' and '{2}' declared in different scopes requires restarting the application.</source> <target state="new">Removing {0} that accessed captured variables '{1}' and '{2}' declared in different scopes requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Removing_0_that_contains_an_active_statement_requires_restarting_the_application"> <source>Removing {0} that contains an active statement requires restarting the application.</source> <target state="new">Removing {0} that contains an active statement requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Renaming_0_requires_restarting_the_application"> <source>Renaming {0} requires restarting the application.</source> <target state="new">Renaming {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Renaming_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime"> <source>Renaming {0} requires restarting the application because it is not supported by the runtime.</source> <target state="new">Renaming {0} requires restarting the application because it is not supported by the runtime.</target> <note /> </trans-unit> <trans-unit id="Renaming_a_captured_variable_from_0_to_1_requires_restarting_the_application"> <source>Renaming a captured variable, from '{0}' to '{1}' requires restarting the application.</source> <target state="new">Renaming a captured variable, from '{0}' to '{1}' requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Replace_0_with_1"> <source>Replace '{0}' with '{1}' </source> <target state="translated">Substituir '{0}' por '{1}'</target> <note /> </trans-unit> <trans-unit id="Resolve_conflict_markers"> <source>Resolve conflict markers</source> <target state="translated">Resolver marcadores de conflitos</target> <note /> </trans-unit> <trans-unit id="RudeEdit"> <source>Rude edit</source> <target state="translated">Edição rudimentar</target> <note /> </trans-unit> <trans-unit id="Selection_does_not_contain_a_valid_token"> <source>Selection does not contain a valid token.</source> <target state="new">Selection does not contain a valid token.</target> <note /> </trans-unit> <trans-unit id="Selection_not_contained_inside_a_type"> <source>Selection not contained inside a type.</source> <target state="new">Selection not contained inside a type.</target> <note /> </trans-unit> <trans-unit id="Sort_accessibility_modifiers"> <source>Sort accessibility modifiers</source> <target state="translated">Classificar modificadores de acessibilidade</target> <note /> </trans-unit> <trans-unit id="Split_into_consecutive_0_statements"> <source>Split into consecutive '{0}' statements</source> <target state="translated">Dividir em instruções '{0}' consecutivas</target> <note /> </trans-unit> <trans-unit id="Split_into_nested_0_statements"> <source>Split into nested '{0}' statements</source> <target state="translated">Dividir em instruções '{0}' aninhadas</target> <note /> </trans-unit> <trans-unit id="StreamMustSupportReadAndSeek"> <source>Stream must support read and seek operations.</source> <target state="translated">O fluxo deve fornecer suporte a operações de leitura e busca.</target> <note /> </trans-unit> <trans-unit id="Suppress_0"> <source>Suppress {0}</source> <target state="translated">Suprimir {0}</target> <note /> </trans-unit> <trans-unit id="Switching_between_lambda_and_local_function_requires_restarting_the_application"> <source>Switching between a lambda and a local function requires restarting the application.</source> <target state="new">Switching between a lambda and a local function requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="TODO_colon_free_unmanaged_resources_unmanaged_objects_and_override_finalizer"> <source>TODO: free unmanaged resources (unmanaged objects) and override finalizer</source> <target state="new">TODO: free unmanaged resources (unmanaged objects) and override finalizer</target> <note /> </trans-unit> <trans-unit id="TODO_colon_override_finalizer_only_if_0_has_code_to_free_unmanaged_resources"> <source>TODO: override finalizer only if '{0}' has code to free unmanaged resources</source> <target state="new">TODO: override finalizer only if '{0}' has code to free unmanaged resources</target> <note /> </trans-unit> <trans-unit id="Target_type_matches"> <source>Target type matches</source> <target state="translated">Correspondências de tipos de destino</target> <note /> </trans-unit> <trans-unit id="The_assembly_0_containing_type_1_references_NET_Framework"> <source>The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported.</source> <target state="translated">O assembly '{0}' contendo o tipo '{1}' referencia o .NET Framework, mas não há suporte para isso.</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_a_local_function_call_without_its_declaration"> <source>The selection contains a local function call without its declaration.</source> <target state="translated">A seleção contém uma chamada de função local sem sua declaração.</target> <note /> </trans-unit> <trans-unit id="Too_many_bars_in_conditional_grouping"> <source>Too many | in (?()|)</source> <target state="translated">Muitos | em (?()|)</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?(0)a|b|)</note> </trans-unit> <trans-unit id="Too_many_close_parens"> <source>Too many )'s</source> <target state="translated">Muitos )'s</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: )</note> </trans-unit> <trans-unit id="UnableToReadSourceFileOrPdb"> <source>Unable to read source file '{0}' or the PDB built for the containing project. Any changes made to this file while debugging won't be applied until its content matches the built source.</source> <target state="translated">Não é possível ler o arquivo de origem '{0}' ou o PDB criado para o projeto que o contém. Todas as alterações feitas neste arquivo durante a depuração não serão aplicadas até que o conteúdo corresponda ao código-fonte compilado.</target> <note /> </trans-unit> <trans-unit id="Unknown_property"> <source>Unknown property</source> <target state="translated">Propriedade desconhecida</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \p{}</note> </trans-unit> <trans-unit id="Unknown_property_0"> <source>Unknown property '{0}'</source> <target state="translated">Propriedade desconhecida '{0}'</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \p{xxx}. Here, {0} will be the name of the unknown property ('xxx')</note> </trans-unit> <trans-unit id="Unrecognized_control_character"> <source>Unrecognized control character</source> <target state="translated">Caractere de controle não reconhecido</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: [\c]</note> </trans-unit> <trans-unit id="Unrecognized_escape_sequence_0"> <source>Unrecognized escape sequence \{0}</source> <target state="translated">Sequência de escape não reconhecida \{0}</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: \m. Here, {0} will be the unrecognized character ('m')</note> </trans-unit> <trans-unit id="Unrecognized_grouping_construct"> <source>Unrecognized grouping construct</source> <target state="translated">Constructo de agrupamento não reconhecida</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?&lt;</note> </trans-unit> <trans-unit id="Unterminated_character_class_set"> <source>Unterminated [] set</source> <target state="translated">Conjunto [] não finalizado</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: [</note> </trans-unit> <trans-unit id="Unterminated_regex_comment"> <source>Unterminated (?#...) comment</source> <target state="translated">Comentário (?#...) não finalizado</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: (?#</note> </trans-unit> <trans-unit id="Unwrap_all_arguments"> <source>Unwrap all arguments</source> <target state="translated">Desencapsular todos os argumentos</target> <note /> </trans-unit> <trans-unit id="Unwrap_all_parameters"> <source>Unwrap all parameters</source> <target state="translated">Desencapsular todos os parâmetros</target> <note /> </trans-unit> <trans-unit id="Unwrap_and_indent_all_arguments"> <source>Unwrap and indent all arguments</source> <target state="translated">Desencapsular e recuar todos os argumentos</target> <note /> </trans-unit> <trans-unit id="Unwrap_and_indent_all_parameters"> <source>Unwrap and indent all parameters</source> <target state="translated">Desencapsular e recuar todos os parâmetros</target> <note /> </trans-unit> <trans-unit id="Unwrap_argument_list"> <source>Unwrap argument list</source> <target state="translated">Desencapsular a lista de argumentos</target> <note /> </trans-unit> <trans-unit id="Unwrap_call_chain"> <source>Unwrap call chain</source> <target state="translated">Desencapsular cadeia de chamadas</target> <note /> </trans-unit> <trans-unit id="Unwrap_expression"> <source>Unwrap expression</source> <target state="translated">Desencapsular a expressão</target> <note /> </trans-unit> <trans-unit id="Unwrap_parameter_list"> <source>Unwrap parameter list</source> <target state="translated">Desencapsular a lista de parâmetros</target> <note /> </trans-unit> <trans-unit id="Updating_0_requires_restarting_the_application"> <source>Updating '{0}' requires restarting the application.</source> <target state="new">Updating '{0}' requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_a_0_around_an_active_statement_requires_restarting_the_application"> <source>Updating a {0} around an active statement requires restarting the application.</source> <target state="new">Updating a {0} around an active statement requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_a_complex_statement_containing_an_await_expression_requires_restarting_the_application"> <source>Updating a complex statement containing an await expression requires restarting the application.</source> <target state="new">Updating a complex statement containing an await expression requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_an_active_statement_requires_restarting_the_application"> <source>Updating an active statement requires restarting the application.</source> <target state="new">Updating an active statement requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_async_or_iterator_modifier_around_an_active_statement_requires_restarting_the_application"> <source>Updating async or iterator modifier around an active statement requires restarting the application.</source> <target state="new">Updating async or iterator modifier around an active statement requires restarting the application.</target> <note>{Locked="async"}{Locked="iterator"} "async" and "iterator" are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Updating_reloadable_type_marked_by_0_attribute_or_its_member_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime"> <source>Updating a reloadable type (marked by {0}) or its member requires restarting the application because is not supported by the runtime.</source> <target state="new">Updating a reloadable type (marked by {0}) or its member requires restarting the application because is not supported by the runtime.</target> <note /> </trans-unit> <trans-unit id="Updating_the_Handles_clause_of_0_requires_restarting_the_application"> <source>Updating the Handles clause of {0} requires restarting the application.</source> <target state="new">Updating the Handles clause of {0} requires restarting the application.</target> <note>{Locked="Handles"} "Handles" is VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Updating_the_Implements_clause_of_a_0_requires_restarting_the_application"> <source>Updating the Implements clause of a {0} requires restarting the application.</source> <target state="new">Updating the Implements clause of a {0} requires restarting the application.</target> <note>{Locked="Implements"} "Implements" is VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Updating_the_alias_of_Declare_statement_requires_restarting_the_application"> <source>Updating the alias of Declare statement requires restarting the application.</source> <target state="new">Updating the alias of Declare statement requires restarting the application.</target> <note>{Locked="Declare"} "Declare" is VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime"> <source>Updating the attributes of {0} requires restarting the application because it is not supported by the runtime.</source> <target state="new">Updating the attributes of {0} requires restarting the application because it is not supported by the runtime.</target> <note /> </trans-unit> <trans-unit id="Updating_the_base_class_and_or_base_interface_s_of_0_requires_restarting_the_application"> <source>Updating the base class and/or base interface(s) of {0} requires restarting the application.</source> <target state="new">Updating the base class and/or base interface(s) of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_initializer_of_0_requires_restarting_the_application"> <source>Updating the initializer of {0} requires restarting the application.</source> <target state="new">Updating the initializer of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_kind_of_a_property_event_accessor_requires_restarting_the_application"> <source>Updating the kind of a property/event accessor requires restarting the application.</source> <target state="new">Updating the kind of a property/event accessor requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_kind_of_a_type_requires_restarting_the_application"> <source>Updating the kind of a type requires restarting the application.</source> <target state="new">Updating the kind of a type requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_library_name_of_Declare_statement_requires_restarting_the_application"> <source>Updating the library name of Declare statement requires restarting the application.</source> <target state="new">Updating the library name of Declare statement requires restarting the application.</target> <note>{Locked="Declare"} "Declare" is VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Updating_the_modifiers_of_0_requires_restarting_the_application"> <source>Updating the modifiers of {0} requires restarting the application.</source> <target state="new">Updating the modifiers of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_size_of_a_0_requires_restarting_the_application"> <source>Updating the size of a {0} requires restarting the application.</source> <target state="new">Updating the size of a {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_type_of_0_requires_restarting_the_application"> <source>Updating the type of {0} requires restarting the application.</source> <target state="new">Updating the type of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_underlying_type_of_0_requires_restarting_the_application"> <source>Updating the underlying type of {0} requires restarting the application.</source> <target state="new">Updating the underlying type of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Updating_the_variance_of_0_requires_restarting_the_application"> <source>Updating the variance of {0} requires restarting the application.</source> <target state="new">Updating the variance of {0} requires restarting the application.</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_lambda_expressions"> <source>Use block body for lambda expressions</source> <target state="translated">Usar o corpo do bloco para expressões lambda</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambda_expressions"> <source>Use expression body for lambda expressions</source> <target state="translated">Usar corpo da expressão para expressões lambda</target> <note /> </trans-unit> <trans-unit id="Use_interpolated_verbatim_string"> <source>Use interpolated verbatim string</source> <target state="translated">Usar cadeia de caracteres verbatim interpolada</target> <note /> </trans-unit> <trans-unit id="Value_colon"> <source>Value:</source> <target state="translated">Valor:</target> <note /> </trans-unit> <trans-unit id="Warning_colon_changing_namespace_may_produce_invalid_code_and_change_code_meaning"> <source>Warning: Changing namespace may produce invalid code and change code meaning.</source> <target state="translated">Aviso: a alteração do namespace pode produzir código inválido e mudar o significado do código.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_semantics_may_change_when_converting_statement"> <source>Warning: Semantics may change when converting statement.</source> <target state="translated">Aviso: a semântica pode ser alterada ao converter a instrução.</target> <note /> </trans-unit> <trans-unit id="Wrap_and_align_call_chain"> <source>Wrap and align call chain</source> <target state="translated">Encapsular e alinhar cadeia de chamadas</target> <note /> </trans-unit> <trans-unit id="Wrap_and_align_expression"> <source>Wrap and align expression</source> <target state="translated">Quebrar e alinhar expressão</target> <note /> </trans-unit> <trans-unit id="Wrap_and_align_long_call_chain"> <source>Wrap and align long call chain</source> <target state="translated">Encapsular e alinhar cadeia longa de chamadas</target> <note /> </trans-unit> <trans-unit id="Wrap_call_chain"> <source>Wrap call chain</source> <target state="translated">Encapsular cadeia de chamadas</target> <note /> </trans-unit> <trans-unit id="Wrap_every_argument"> <source>Wrap every argument</source> <target state="translated">Encapsular cada argumento</target> <note /> </trans-unit> <trans-unit id="Wrap_every_parameter"> <source>Wrap every parameter</source> <target state="translated">Encapsular cada parâmetro</target> <note /> </trans-unit> <trans-unit id="Wrap_expression"> <source>Wrap expression</source> <target state="translated">Encapsular a expressão</target> <note /> </trans-unit> <trans-unit id="Wrap_long_argument_list"> <source>Wrap long argument list</source> <target state="translated">Encapsular a lista de argumentos longa</target> <note /> </trans-unit> <trans-unit id="Wrap_long_call_chain"> <source>Wrap long call chain</source> <target state="translated">Encapsular cadeia longa de chamadas</target> <note /> </trans-unit> <trans-unit id="Wrap_long_parameter_list"> <source>Wrap long parameter list</source> <target state="translated">Encapsular a lista de parâmetros longa</target> <note /> </trans-unit> <trans-unit id="Wrapping"> <source>Wrapping</source> <target state="translated">Quebra de linha</target> <note /> </trans-unit> <trans-unit id="You_can_use_the_navigation_bar_to_switch_contexts"> <source>You can use the navigation bar to switch contexts.</source> <target state="translated">Você pode usar a barra de navegação para mudar de contexto.</target> <note /> </trans-unit> <trans-unit id="_0_cannot_be_null_or_empty"> <source>'{0}' cannot be null or empty.</source> <target state="translated">'{0}' não pode ser nulo nem vazio.</target> <note /> </trans-unit> <trans-unit id="_0_cannot_be_null_or_whitespace"> <source>'{0}' cannot be null or whitespace.</source> <target state="translated">'{0}' não pode ser nulo nem espaço em branco.</target> <note /> </trans-unit> <trans-unit id="_0_dash_1"> <source>{0} - {1}</source> <target state="translated">{0} - {1}</target> <note /> </trans-unit> <trans-unit id="_0_is_not_null_here"> <source>'{0}' is not null here.</source> <target state="translated">'{0}' não é nulo aqui.</target> <note /> </trans-unit> <trans-unit id="_0_may_be_null_here"> <source>'{0}' may be null here.</source> <target state="translated">'{0}' pode ser nulo aqui.</target> <note /> </trans-unit> <trans-unit id="_10000000ths_of_a_second"> <source>10,000,000ths of a second</source> <target state="translated">Dez milionésimos de um segundo</target> <note /> </trans-unit> <trans-unit id="_10000000ths_of_a_second_description"> <source>The "fffffff" custom format specifier represents the seven most significant digits of the seconds fraction; that is, it represents the ten millionths of a second in a date and time value. Although it's possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "fffffff" representa os sete dígitos mais significativos da fração de segundos. Ou seja, representa os dez milionésimos de segundo em um valor de data e hora. Embora seja possível exibir os dez milionésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT 3.5 (e posteriores) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_10000000ths_of_a_second_non_zero"> <source>10,000,000ths of a second (non-zero)</source> <target state="translated">Dez milionésimos de um segundo (diferente de zero)</target> <note /> </trans-unit> <trans-unit id="_10000000ths_of_a_second_non_zero_description"> <source>The "FFFFFFF" custom format specifier represents the seven most significant digits of the seconds fraction; that is, it represents the ten millionths of a second in a date and time value. However, trailing zeros or seven zero digits aren't displayed. Although it's possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "FFFFFFF" representa os sete dígitos mais significativos da fração de segundos. Ou seja, representa os dez milionésimos de segundo em um valor de data e hora. No entanto, zeros à direita ou sete dígitos de zero não são exibidos. Embora seja possível exibir os dez milionésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT 3.5 (e posteriores) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_1000000ths_of_a_second"> <source>1,000,000ths of a second</source> <target state="translated">Milionésimos de um segundo</target> <note /> </trans-unit> <trans-unit id="_1000000ths_of_a_second_description"> <source>The "ffffff" custom format specifier represents the six most significant digits of the seconds fraction; that is, it represents the millionths of a second in a date and time value. Although it's possible to display the millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "FFFFFF" representa os seis dígitos mais significativos da fração de segundos. Ou seja, ele representa os milionésimos de segundo em um valor de data e hora. Embora seja possível exibir os milionésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT 3.5 (e posteriores) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_1000000ths_of_a_second_non_zero"> <source>1,000,000ths of a second (non-zero)</source> <target state="translated">Milionésimos de um segundo (diferente de zero)</target> <note /> </trans-unit> <trans-unit id="_1000000ths_of_a_second_non_zero_description"> <source>The "FFFFFF" custom format specifier represents the six most significant digits of the seconds fraction; that is, it represents the millionths of a second in a date and time value. However, trailing zeros or six zero digits aren't displayed. Although it's possible to display the millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "FFFFFF" representa os seis dígitos mais significativos da fração de segundos. Ou seja, ele representa os milionésimos de segundo em um valor de data e hora. No entanto, zeros à direita ou seis dígitos de zero não são exibidos. Embora seja possível exibir os milionésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT 3.5 (e posteriores) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_100000ths_of_a_second"> <source>100,000ths of a second</source> <target state="translated">Cem milésimos de um segundo</target> <note /> </trans-unit> <trans-unit id="_100000ths_of_a_second_description"> <source>The "fffff" custom format specifier represents the five most significant digits of the seconds fraction; that is, it represents the hundred thousandths of a second in a date and time value. Although it's possible to display the hundred thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "fffff" representa os cinco dígitos mais significativos da fração de segundos. Ou seja, representa as centenas de milésimos de segundo em um valor de data e hora. Embora seja possível exibir as centenas de milésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT 3.5 (e posteriores) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_100000ths_of_a_second_non_zero"> <source>100,000ths of a second (non-zero)</source> <target state="translated">Cem milésimos de um segundo (diferente de zero)</target> <note /> </trans-unit> <trans-unit id="_100000ths_of_a_second_non_zero_description"> <source>The "FFFFF" custom format specifier represents the five most significant digits of the seconds fraction; that is, it represents the hundred thousandths of a second in a date and time value. However, trailing zeros or five zero digits aren't displayed. Although it's possible to display the hundred thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "FFFFF" representa os cinco dígitos mais significativos da fração de segundos. Ou seja, representa as centenas de milésimos de segundo em um valor de data e hora. No entanto, zeros à direita ou cinco dígitos de zero não são exibidos. Embora seja possível exibir as centenas de milésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT 3.5 (e posteriores) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_10000ths_of_a_second"> <source>10,000ths of a second</source> <target state="translated">Dez milésimos de um segundo</target> <note /> </trans-unit> <trans-unit id="_10000ths_of_a_second_description"> <source>The "ffff" custom format specifier represents the four most significant digits of the seconds fraction; that is, it represents the ten thousandths of a second in a date and time value. Although it's possible to display the ten thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT version 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "ffff" representa os quatro dígitos mais significativos da fração de segundos. Ou seja, representa os dez milésimos de segundo em um valor de data e hora. Embora seja possível exibir os dez milésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT versão 3.5 (e posterior) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_10000ths_of_a_second_non_zero"> <source>10,000ths of a second (non-zero)</source> <target state="translated">Dez milésimos de um segundo (diferente de zero)</target> <note /> </trans-unit> <trans-unit id="_10000ths_of_a_second_non_zero_description"> <source>The "FFFF" custom format specifier represents the four most significant digits of the seconds fraction; that is, it represents the ten thousandths of a second in a date and time value. However, trailing zeros or four zero digits aren't displayed. Although it's possible to display the ten thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.</source> <target state="translated">O especificador de formato personalizado "FFFF" representa os quatro dígitos mais significativos da fração de segundos. Ou seja, representa os dez milésimos de segundo em um valor de data e hora. No entanto, zeros à direita ou quatro dígitos de zero não são exibidos. Embora seja possível exibir os dez milésimos de um componente de segundo de um valor temporal, esse valor pode não ser significativo. A precisão dos valores de data e hora depende da resolução do relógio do sistema. Nos sistemas operacionais Windows NT 3.5 (e posteriores) e Windows Vista, a resolução do relógio é de aproximadamente 10-15 milissegundos.</target> <note /> </trans-unit> <trans-unit id="_1000ths_of_a_second"> <source>1,000ths of a second</source> <target state="translated">Milésimos de um segundo</target> <note /> </trans-unit> <trans-unit id="_1000ths_of_a_second_description"> <source>The "fff" custom format specifier represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.</source> <target state="translated">O especificador de formato personalizado "fff" representa os três dígitos mais significativos da fração de segundos. Ou seja, ele representa os milissegundos em um valor de data e hora.</target> <note /> </trans-unit> <trans-unit id="_1000ths_of_a_second_non_zero"> <source>1,000ths of a second (non-zero)</source> <target state="translated">Milésimos de um segundo (diferente de zero)</target> <note /> </trans-unit> <trans-unit id="_1000ths_of_a_second_non_zero_description"> <source>The "FFF" custom format specifier represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value. However, trailing zeros or three zero digits aren't displayed.</source> <target state="translated">O especificador de formato personalizado "FFF" representa os três dígitos mais significativos da fração de segundos. Ou seja, ele representa os milissegundos em um valor de data e hora. No entanto, zeros à direita ou três dígitos de zero não são exibidos.</target> <note /> </trans-unit> <trans-unit id="_100ths_of_a_second"> <source>100ths of a second</source> <target state="translated">Centésimos de um segundo</target> <note /> </trans-unit> <trans-unit id="_100ths_of_a_second_description"> <source>The "ff" custom format specifier represents the two most significant digits of the seconds fraction; that is, it represents the hundredths of a second in a date and time value.</source> <target state="translated">O especificador de formato personalizado "ff" representa os dois dígitos mais significativos da fração de segundos. Ou seja, ele representa os centésimos de segundo em um valor de data e hora.</target> <note /> </trans-unit> <trans-unit id="_100ths_of_a_second_non_zero"> <source>100ths of a second (non-zero)</source> <target state="translated">Centésimos de segundo (diferente de zero)</target> <note /> </trans-unit> <trans-unit id="_100ths_of_a_second_non_zero_description"> <source>The "FF" custom format specifier represents the two most significant digits of the seconds fraction; that is, it represents the hundredths of a second in a date and time value. However, trailing zeros or two zero digits aren't displayed.</source> <target state="translated">O especificador de formato personalizado "FF" representa os dois dígitos mais significativos da fração de segundos. Ou seja, ele representa os centésimos de segundo em um valor de data e hora. No entanto, zeros à direita ou dois dígitos de zero não são exibidos.</target> <note /> </trans-unit> <trans-unit id="_10ths_of_a_second"> <source>10ths of a second</source> <target state="translated">Décimos de segundo</target> <note /> </trans-unit> <trans-unit id="_10ths_of_a_second_description"> <source>The "f" custom format specifier represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. If the "f" format specifier is used without other format specifiers, it's interpreted as the "f" standard date and time format specifier. When you use "f" format specifiers as part of a format string supplied to the ParseExact or TryParseExact method, the number of "f" format specifiers indicates the number of most significant digits of the seconds fraction that must be present to successfully parse the string.</source> <target state="new">The "f" custom format specifier represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. If the "f" format specifier is used without other format specifiers, it's interpreted as the "f" standard date and time format specifier. When you use "f" format specifiers as part of a format string supplied to the ParseExact or TryParseExact method, the number of "f" format specifiers indicates the number of most significant digits of the seconds fraction that must be present to successfully parse the string.</target> <note>{Locked="ParseExact"}{Locked="TryParseExact"}{Locked=""f""}</note> </trans-unit> <trans-unit id="_10ths_of_a_second_non_zero"> <source>10ths of a second (non-zero)</source> <target state="translated">Décimos de segundo (diferente de zero)</target> <note /> </trans-unit> <trans-unit id="_10ths_of_a_second_non_zero_description"> <source>The "F" custom format specifier represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. Nothing is displayed if the digit is zero. If the "F" format specifier is used without other format specifiers, it's interpreted as the "F" standard date and time format specifier. The number of "F" format specifiers used with the ParseExact, TryParseExact, ParseExact, or TryParseExact method indicates the maximum number of most significant digits of the seconds fraction that can be present to successfully parse the string.</source> <target state="translated">O especificador de formato personalizado "F" representa o dígito mais significativo da fração de segundos; ou seja, ele representa os décimos de segundo em um valor de data e hora. Nada será exibido se o dígito for zero. Se o especificador de formato "F" for usado sem outros especificadores de formato, ele será interpretado como o especificador de formato padrão de data e hora "F". O número de especificadores de formato "F" usados com o método ParseExact, TryParseExact, ParseExact ou TryParseExact indica o número máximo de dígitos significativos da fração de segundos que podem estar presentes para analisar a cadeia de caracteres com êxito.</target> <note /> </trans-unit> <trans-unit id="_12_hour_clock_1_2_digits"> <source>12 hour clock (1-2 digits)</source> <target state="translated">Relógio de 12 horas (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="_12_hour_clock_1_2_digits_description"> <source>The "h" custom format specifier represents the hour as a number from 1 through 12; that is, the hour is represented by a 12-hour clock that counts the whole hours since midnight or noon. A particular hour after midnight is indistinguishable from the same hour after noon. The hour is not rounded, and a single-digit hour is formatted without a leading zero. For example, given a time of 5:43 in the morning or afternoon, this custom format specifier displays "5". If the "h" format specifier is used without other custom format specifiers, it's interpreted as a standard date and time format specifier and throws a FormatException.</source> <target state="translated">O especificador de formato personalizado "h" representa a hora como um número de 1 a 12. Ou seja, a hora é representada por um relógio de 12 horas que conta todas as horas desde a meia-noite ou o meio-dia. Uma determinada hora após a meia-noite é indistinguível da mesma hora após o meio-dia. A hora não é arredondada e uma hora de dígito único é formatada sem um zero à esquerda. Por exemplo, dado um horário de 5:43 na manhã ou à tarde, este especificador de formato personalizado exibe "5". Se o especificador de formato "h" for usado sem outros especificadores de formato personalizado, ele será interpretado como um especificador de formato padrão de data e hora e gerará uma FormatException.</target> <note /> </trans-unit> <trans-unit id="_12_hour_clock_2_digits"> <source>12 hour clock (2 digits)</source> <target state="translated">Relógio de 12 horas (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="_12_hour_clock_2_digits_description"> <source>The "hh" custom format specifier (plus any number of additional "h" specifiers) represents the hour as a number from 01 through 12; that is, the hour is represented by a 12-hour clock that counts the whole hours since midnight or noon. A particular hour after midnight is indistinguishable from the same hour after noon. The hour is not rounded, and a single-digit hour is formatted with a leading zero. For example, given a time of 5:43 in the morning or afternoon, this format specifier displays "05".</source> <target state="translated">O especificador de formato personalizado "hh" (mais qualquer número de especificadores "h" adicionais) representa a hora como um número de 01 a 12. Ou seja, a hora é representada por um relógio de 12 horas que conta todas as horas desde a meia-noite ou o meio-dia. Uma determinada hora após a meia-noite é indistinguível da mesma hora após o meio-dia. A hora não é arredondada e uma hora de dígito único é formatada com um zero à esquerda. Por exemplo, dado um horário de 5:43 na manhã ou à tarde, esse especificador de formato exibe "05".</target> <note /> </trans-unit> <trans-unit id="_24_hour_clock_1_2_digits"> <source>24 hour clock (1-2 digits)</source> <target state="translated">Relógio de 24 horas (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="_24_hour_clock_1_2_digits_description"> <source>The "H" custom format specifier represents the hour as a number from 0 through 23; that is, the hour is represented by a zero-based 24-hour clock that counts the hours since midnight. A single-digit hour is formatted without a leading zero. If the "H" format specifier is used without other custom format specifiers, it's interpreted as a standard date and time format specifier and throws a FormatException.</source> <target state="translated">O especificador de formato personalizado "H" representa a hora como um número de 0 a 23. Ou seja, a hora é representada por um relógio de 24 horas com base em zero que conta as horas desde a meia-noite. Uma hora de dígito único é formatada sem um zero à esquerda. Se o especificador de formato "H" for usado sem outros especificadores de formato personalizado, ele será interpretado como um especificador de formato padrão de data e hora e gerará uma FormatException.</target> <note /> </trans-unit> <trans-unit id="_24_hour_clock_2_digits"> <source>24 hour clock (2 digits)</source> <target state="translated">Relógio de 24 horas (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="_24_hour_clock_2_digits_description"> <source>The "HH" custom format specifier (plus any number of additional "H" specifiers) represents the hour as a number from 00 through 23; that is, the hour is represented by a zero-based 24-hour clock that counts the hours since midnight. A single-digit hour is formatted with a leading zero.</source> <target state="translated">O especificador de formato personalizado "HH" (mais qualquer número de especificadores "H" adicionais) representa a hora como um número de 00 a 23. Ou seja, a hora é representada por um relógio de 24 horas com base em zero que conta as horas desde a meia-noite. Uma hora de dígito único é formatada com um zero à esquerda.</target> <note /> </trans-unit> <trans-unit id="and_update_call_sites_directly"> <source>and update call sites directly</source> <target state="new">and update call sites directly</target> <note /> </trans-unit> <trans-unit id="code"> <source>code</source> <target state="translated">código</target> <note /> </trans-unit> <trans-unit id="date_separator"> <source>date separator</source> <target state="translated">separador de data</target> <note /> </trans-unit> <trans-unit id="date_separator_description"> <source>The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture. Note: To change the date separator for a particular date and time string, specify the separator character within a literal string delimiter. For example, the custom format string mm'/'dd'/'yyyy produces a result string in which "/" is always used as the date separator. To change the date separator for all dates for a culture, either change the value of the DateTimeFormatInfo.DateSeparator property of the current culture, or instantiate a DateTimeFormatInfo object, assign the character to its DateSeparator property, and call an overload of the formatting method that includes an IFormatProvider parameter. If the "/" format specifier is used without other custom format specifiers, it's interpreted as a standard date and time format specifier and throws a FormatException.</source> <target state="translated">O especificador de formato personalizado "/" representa o separador de data, que é usado para diferenciar anos, meses e dias. O separador de data localizado apropriado é recuperado da propriedade DateTimeFormatInfo.DateSeparator da cultura atual ou especificada. Observação: para alterar o separador de data de uma determinada cadeia de caracteres de data e hora, especifique o caractere separador em um delimitador de cadeia de caracteres literal. Por exemplo, a cadeia de caracteres de formato personalizado mm'/'dd'/'yyyy produz uma cadeia de resultado na qual "/" é sempre usado como separador de data. Para alterar o separador de data para todas as datas para uma cultura, altere o valor da propriedade DateTimeFormatInfo.DateSeparator da cultura atual ou crie uma instância de um objeto DateTimeFormatInfo, atribua o caractere à sua propriedade DateSeparator e chame uma sobrecarga do método de formatação que inclui um parâmetro IFormatProvider. Se o especificador de formato "/" for usado sem outros especificadores de formato personalizado, ele será interpretado como um especificador de formato padrão de data e hora e gerará uma FormatException.</target> <note /> </trans-unit> <trans-unit id="day_of_the_month_1_2_digits"> <source>day of the month (1-2 digits)</source> <target state="translated">dia do mês (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="day_of_the_month_1_2_digits_description"> <source>The "d" custom format specifier represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero. If the "d" format specifier is used without other custom format specifiers, it's interpreted as the "d" standard date and time format specifier.</source> <target state="translated">O especificador de formato personalizado "d" representa o dia do mês como um número de 1 a 31. Um dia de dígito único é formatado sem um zero à esquerda. Se o especificador de formato "d" for usado sem outros especificadores de formato personalizado, ele será interpretado como o especificador de formato padrão de data e hora "d".</target> <note /> </trans-unit> <trans-unit id="day_of_the_month_2_digits"> <source>day of the month (2 digits)</source> <target state="translated">dia do mês (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="day_of_the_month_2_digits_description"> <source>The "dd" custom format string represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero.</source> <target state="translated">A cadeia de caracteres de formato personalizado "dd" representa o dia do mês como um número de 01 a 31. Um dia de dígito único é formatado com um zero à esquerda.</target> <note /> </trans-unit> <trans-unit id="day_of_the_week_abbreviated"> <source>day of the week (abbreviated)</source> <target state="translated">dia da semana (abreviado)</target> <note /> </trans-unit> <trans-unit id="day_of_the_week_abbreviated_description"> <source>The "ddd" custom format specifier represents the abbreviated name of the day of the week. The localized abbreviated name of the day of the week is retrieved from the DateTimeFormatInfo.AbbreviatedDayNames property of the current or specified culture.</source> <target state="translated">O especificador de formato personalizado "ddd" representa o nome abreviado do dia da semana. O nome abreviado localizado do dia da semana é recuperado da propriedade DateTimeFormatInfo.AbbreviatedDayNames da cultura atual ou especificada.</target> <note /> </trans-unit> <trans-unit id="day_of_the_week_full"> <source>day of the week (full)</source> <target state="translated">dia da semana (completo)</target> <note /> </trans-unit> <trans-unit id="day_of_the_week_full_description"> <source>The "dddd" custom format specifier (plus any number of additional "d" specifiers) represents the full name of the day of the week. The localized name of the day of the week is retrieved from the DateTimeFormatInfo.DayNames property of the current or specified culture.</source> <target state="translated">O especificador de formato personalizado "dddd" (mais qualquer número de especificadores "d" adicionais) representa o nome completo do dia da semana. O nome localizado do dia da semana é recuperado da propriedade DateTimeFormatInfo.DayNames da cultura atual ou especificada.</target> <note /> </trans-unit> <trans-unit id="discard"> <source>discard</source> <target state="translated">discard</target> <note /> </trans-unit> <trans-unit id="from_metadata"> <source>from metadata</source> <target state="translated">de metadados</target> <note /> </trans-unit> <trans-unit id="full_long_date_time"> <source>full long date/time</source> <target state="translated">data/hora completa por extenso</target> <note /> </trans-unit> <trans-unit id="full_long_date_time_description"> <source>The "F" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.FullDateTimePattern property. For example, the custom format string for the invariant culture is "dddd, dd MMMM yyyy HH:mm:ss".</source> <target state="translated">O especificador de formato padrão "F" representa uma cadeia de caracteres de formato de data e hora personalizada que é definida pela propriedade DateTimeFormatInfo. FullDateTimePattern atual. Por exemplo, a cadeia de caracteres de formato personalizado para a cultura invariável é "dddd, dd MMMM yyyy HH:mm:ss".</target> <note /> </trans-unit> <trans-unit id="full_short_date_time"> <source>full short date/time</source> <target state="translated">data/hora abreviada por extenso</target> <note /> </trans-unit> <trans-unit id="full_short_date_time_description"> <source>The Full Date Short Time ("f") Format Specifier The "f" standard format specifier represents a combination of the long date ("D") and short time ("t") patterns, separated by a space.</source> <target state="translated">O Especificador de Formato de Data por Extenso Hora Abreviada ("f") O especificador de formato padrão "f" representa uma combinação de padrões de data por extenso ("D") e tempo abreviado ("t"), separados por um espaço.</target> <note /> </trans-unit> <trans-unit id="general_long_date_time"> <source>general long date/time</source> <target state="translated">data/hora geral por extenso</target> <note /> </trans-unit> <trans-unit id="general_long_date_time_description"> <source>The "G" standard format specifier represents a combination of the short date ("d") and long time ("T") patterns, separated by a space.</source> <target state="translated">O especificador de formato padrão "G" representa uma combinação dos padrões de data abreviada ("d") e hora por extenso ("T"), separados por um espaço.</target> <note /> </trans-unit> <trans-unit id="general_short_date_time"> <source>general short date/time</source> <target state="translated">data/hora abreviada geral</target> <note /> </trans-unit> <trans-unit id="general_short_date_time_description"> <source>The "g" standard format specifier represents a combination of the short date ("d") and short time ("t") patterns, separated by a space.</source> <target state="translated">O especificador de formato padrão "g" representa uma combinação dos padrões de data abreviada ("d") e hora abreviada ("t"), separados por um espaço.</target> <note /> </trans-unit> <trans-unit id="generic_overload"> <source>generic overload</source> <target state="translated">sobrecarga genérica</target> <note /> </trans-unit> <trans-unit id="generic_overloads"> <source>generic overloads</source> <target state="translated">sobrecargas genéricas</target> <note /> </trans-unit> <trans-unit id="in_0_1_2"> <source>in {0} ({1} - {2})</source> <target state="translated">em {0} ({1} – {2})</target> <note /> </trans-unit> <trans-unit id="in_Source_attribute"> <source>in Source (attribute)</source> <target state="translated">na Origem (atributo)</target> <note /> </trans-unit> <trans-unit id="into_extracted_method_to_invoke_at_call_sites"> <source>into extracted method to invoke at call sites</source> <target state="new">into extracted method to invoke at call sites</target> <note /> </trans-unit> <trans-unit id="into_new_overload"> <source>into new overload</source> <target state="new">into new overload</target> <note /> </trans-unit> <trans-unit id="long_date"> <source>long date</source> <target state="translated">data completa</target> <note /> </trans-unit> <trans-unit id="long_date_description"> <source>The "D" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.LongDatePattern property. For example, the custom format string for the invariant culture is "dddd, dd MMMM yyyy".</source> <target state="translated">O especificador de formato padrão "D" representa uma cadeia de caracteres de formato de data e hora personalizada que é definida pela propriedade DateTimeFormatInfo.LongDatePattern atual. Por exemplo, a cadeia de caracteres de formato personalizado para a cultura invariável é "dddd, dd MMMM yyyy".</target> <note /> </trans-unit> <trans-unit id="long_time"> <source>long time</source> <target state="translated">hora completa</target> <note /> </trans-unit> <trans-unit id="long_time_description"> <source>The "T" standard format specifier represents a custom date and time format string that is defined by a specific culture's DateTimeFormatInfo.LongTimePattern property. For example, the custom format string for the invariant culture is "HH:mm:ss".</source> <target state="translated">O especificador de formato padrão "T" representa uma cadeia de caracteres de formato personalizado de data e hora que é definida pela propriedade DateTimeFormatInfo.LongTimePattern de uma cultura específica. Por exemplo, a cadeia de caracteres de formato personalizado para a cultura invariável é "HH:mm:ss".</target> <note /> </trans-unit> <trans-unit id="member_kind_and_name"> <source>{0} '{1}'</source> <target state="translated">{0} '{1}'</target> <note>e.g. "method 'M'"</note> </trans-unit> <trans-unit id="minute_1_2_digits"> <source>minute (1-2 digits)</source> <target state="translated">minuto (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="minute_1_2_digits_description"> <source>The "m" custom format specifier represents the minute as a number from 0 through 59. The minute represents whole minutes that have passed since the last hour. A single-digit minute is formatted without a leading zero. If the "m" format specifier is used without other custom format specifiers, it's interpreted as the "m" standard date and time format specifier.</source> <target state="translated">O especificador de formato personalizado "m" representa o minuto como um número de 0 a 59. O minuto representa minutos inteiros que passaram desde a última hora. Um minuto de dígito único é formatado sem um zero à esquerda. Se o especificador de formato "m" for usado sem outros especificadores de formato personalizado, ele será interpretado como o especificador de formato padrão de data e hora "m".</target> <note /> </trans-unit> <trans-unit id="minute_2_digits"> <source>minute (2 digits)</source> <target state="translated">minuto (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="minute_2_digits_description"> <source>The "mm" custom format specifier (plus any number of additional "m" specifiers) represents the minute as a number from 00 through 59. The minute represents whole minutes that have passed since the last hour. A single-digit minute is formatted with a leading zero.</source> <target state="translated">O especificador de formato personalizado "mm" (mais qualquer número de especificadores "m" adicionais) representa o minuto como um número de 00 a 59. O minuto representa minutos inteiros que passaram desde a última hora. Um minuto de dígito único é formatado com um zero à esquerda.</target> <note /> </trans-unit> <trans-unit id="month_1_2_digits"> <source>month (1-2 digits)</source> <target state="translated">mês (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="month_1_2_digits_description"> <source>The "M" custom format specifier represents the month as a number from 1 through 12 (or from 1 through 13 for calendars that have 13 months). A single-digit month is formatted without a leading zero. If the "M" format specifier is used without other custom format specifiers, it's interpreted as the "M" standard date and time format specifier.</source> <target state="translated">O especificador de formato personalizado "M" representa o mês como um número de 1 a 12 (ou de 1 a 13 para calendários com 13 meses). Um mês de dígito único é formatado sem um zero à esquerda. Se o especificador de formato "M" for usado sem outros especificadores de formato personalizado, ele será interpretado como o especificador de formato padrão de data e hora "M".</target> <note /> </trans-unit> <trans-unit id="month_2_digits"> <source>month (2 digits)</source> <target state="translated">mês (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="month_2_digits_description"> <source>The "MM" custom format specifier represents the month as a number from 01 through 12 (or from 1 through 13 for calendars that have 13 months). A single-digit month is formatted with a leading zero.</source> <target state="translated">O especificador de formato personalizado "MM" representa o mês como um número de 01 a 12 (ou de 1 a 13 para calendários com 13 meses). Um mês de dígito único é formatado com um zero à esquerda.</target> <note /> </trans-unit> <trans-unit id="month_abbreviated"> <source>month (abbreviated)</source> <target state="translated">mês (abreviado)</target> <note /> </trans-unit> <trans-unit id="month_abbreviated_description"> <source>The "MMM" custom format specifier represents the abbreviated name of the month. The localized abbreviated name of the month is retrieved from the DateTimeFormatInfo.AbbreviatedMonthNames property of the current or specified culture.</source> <target state="translated">O especificador de formato personalizado "MMM" representa o nome abreviado do mês. O nome abreviado localizado do mês é recuperado da propriedade DateTimeFormatInfo.AbbreviatedMonthNames da cultura atual ou especificada.</target> <note /> </trans-unit> <trans-unit id="month_day"> <source>month day</source> <target state="translated">dia do mês</target> <note /> </trans-unit> <trans-unit id="month_day_description"> <source>The "M" or "m" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.MonthDayPattern property. For example, the custom format string for the invariant culture is "MMMM dd".</source> <target state="translated">O especificador de formato padrão "M" ou "m" representa uma cadeia de caracteres de formato personalizado de data e hora definida pela propriedade DateTimeFormatInfo.MonthDayPattern atual. Por exemplo, a cadeia de caracteres de formato personalizado para a cultura invariável é "MMMM dd".</target> <note /> </trans-unit> <trans-unit id="month_full"> <source>month (full)</source> <target state="translated">mês (completo)</target> <note /> </trans-unit> <trans-unit id="month_full_description"> <source>The "MMMM" custom format specifier represents the full name of the month. The localized name of the month is retrieved from the DateTimeFormatInfo.MonthNames property of the current or specified culture.</source> <target state="translated">O especificador de formato personalizado "MMMM" representa o nome completo do mês. O nome localizado do mês é recuperado da propriedade DateTimeFormatInfo.MonthNames da cultura atual ou especificada.</target> <note /> </trans-unit> <trans-unit id="overload"> <source>overload</source> <target state="translated">sobrecarga</target> <note /> </trans-unit> <trans-unit id="overloads_"> <source>overloads</source> <target state="translated">sobrecargas</target> <note /> </trans-unit> <trans-unit id="_0_Keyword"> <source>{0} Keyword</source> <target state="translated">{0} Palavra-chave</target> <note /> </trans-unit> <trans-unit id="Encapsulate_field_colon_0_and_use_property"> <source>Encapsulate field: '{0}' (and use property)</source> <target state="translated">Encapsular campo: "{0}" (e usar propriedade)</target> <note /> </trans-unit> <trans-unit id="Encapsulate_field_colon_0_but_still_use_field"> <source>Encapsulate field: '{0}' (but still use field)</source> <target state="translated">Encapsular campo: "{0}" (mas ainda usar o campo)</target> <note /> </trans-unit> <trans-unit id="Encapsulate_fields_and_use_property"> <source>Encapsulate fields (and use property)</source> <target state="translated">Encapsular campos (e usar propriedade)</target> <note /> </trans-unit> <trans-unit id="Encapsulate_fields_but_still_use_field"> <source>Encapsulate fields (but still use field)</source> <target state="translated">Encapsular campos (mas ainda usá-los)</target> <note /> </trans-unit> <trans-unit id="Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct"> <source>Could not extract interface: The selection is not inside a class/interface/struct.</source> <target state="translated">Não foi possível extrair interface: a seleção não está dentro de uma classe/interface/struct.</target> <note /> </trans-unit> <trans-unit id="Could_not_extract_interface_colon_The_type_does_not_contain_any_member_that_can_be_extracted_to_an_interface"> <source>Could not extract interface: The type does not contain any member that can be extracted to an interface.</source> <target state="translated">Não foi possível extrair interface: O tipo não contém membros que podem ser extraídos para uma interface.</target> <note /> </trans-unit> <trans-unit id="can_t_not_construct_final_tree"> <source>can't not construct final tree</source> <target state="translated">não é possível construir a árvore final</target> <note /> </trans-unit> <trans-unit id="Parameters_type_or_return_type_cannot_be_an_anonymous_type_colon_bracket_0_bracket"> <source>Parameters' type or return type cannot be an anonymous type : [{0}]</source> <target state="translated">Tipo dos parâmetros ou tipo de retorno não pode ser um tipo anônimo: [{0}]</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_no_active_statement"> <source>The selection contains no active statement.</source> <target state="translated">A seleção não contém instrução ativa.</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_an_error_or_unknown_type"> <source>The selection contains an error or unknown type.</source> <target state="translated">A seleção contém um erro ou tipo desconhecido.</target> <note /> </trans-unit> <trans-unit id="Type_parameter_0_is_hidden_by_another_type_parameter_1"> <source>Type parameter '{0}' is hidden by another type parameter '{1}'.</source> <target state="translated">Parâmetro de tipo "{0}" está oculto por outro parâmetro de tipo "{1}".</target> <note /> </trans-unit> <trans-unit id="The_address_of_a_variable_is_used_inside_the_selected_code"> <source>The address of a variable is used inside the selected code.</source> <target state="translated">O endereço de uma variável é usado dentro do código selecionado.</target> <note /> </trans-unit> <trans-unit id="Assigning_to_readonly_fields_must_be_done_in_a_constructor_colon_bracket_0_bracket"> <source>Assigning to readonly fields must be done in a constructor : [{0}].</source> <target state="translated">A atribuição a campos somente leitura deve ser feita em um construtor: [{0}].</target> <note /> </trans-unit> <trans-unit id="generated_code_is_overlapping_with_hidden_portion_of_the_code"> <source>generated code is overlapping with hidden portion of the code</source> <target state="translated">o código gerado se sobrepõe à porção oculta do código</target> <note /> </trans-unit> <trans-unit id="Add_optional_parameters_to_0"> <source>Add optional parameters to '{0}'</source> <target state="translated">Adicionar parâmetros opcionais ao '{0}'</target> <note /> </trans-unit> <trans-unit id="Add_parameters_to_0"> <source>Add parameters to '{0}'</source> <target state="translated">Adicionar parâmetros ao '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_delegating_constructor_0_1"> <source>Generate delegating constructor '{0}({1})'</source> <target state="translated">Gerar construtor delegante "{0}({1})"</target> <note /> </trans-unit> <trans-unit id="Generate_constructor_0_1"> <source>Generate constructor '{0}({1})'</source> <target state="translated">Gerar construtor "{0}({1})"</target> <note /> </trans-unit> <trans-unit id="Generate_field_assigning_constructor_0_1"> <source>Generate field assigning constructor '{0}({1})'</source> <target state="translated">Gerar construtor de atribuição de campo "{0}({1})"</target> <note /> </trans-unit> <trans-unit id="Generate_Equals_and_GetHashCode"> <source>Generate Equals and GetHashCode</source> <target state="translated">Gerar Equals e GetHashCode</target> <note /> </trans-unit> <trans-unit id="Generate_Equals_object"> <source>Generate Equals(object)</source> <target state="translated">Gerar Equals(object)</target> <note /> </trans-unit> <trans-unit id="Generate_GetHashCode"> <source>Generate GetHashCode()</source> <target state="translated">Gerar GetHashCode()</target> <note /> </trans-unit> <trans-unit id="Generate_constructor_in_0"> <source>Generate constructor in '{0}'</source> <target state="translated">Gerar construtor em '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_all"> <source>Generate all</source> <target state="translated">Gerar todos</target> <note /> </trans-unit> <trans-unit id="Generate_enum_member_1_0"> <source>Generate enum member '{1}.{0}'</source> <target state="translated">Gerar membro enum '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_constant_1_0"> <source>Generate constant '{1}.{0}'</source> <target state="translated">Gerar constante '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_read_only_property_1_0"> <source>Generate read-only property '{1}.{0}'</source> <target state="translated">Gerar propriedade somente leitura '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_property_1_0"> <source>Generate property '{1}.{0}'</source> <target state="translated">Gerar propriedade '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_read_only_field_1_0"> <source>Generate read-only field '{1}.{0}'</source> <target state="translated">Gerar campo somente leitura '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_field_1_0"> <source>Generate field '{1}.{0}'</source> <target state="translated">Gerar campo '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_local_0"> <source>Generate local '{0}'</source> <target state="translated">Gerar local '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_0_1_in_new_file"> <source>Generate {0} '{1}' in new file</source> <target state="translated">Gerar {0} '{1}' no novo arquivo</target> <note /> </trans-unit> <trans-unit id="Generate_nested_0_1"> <source>Generate nested {0} '{1}'</source> <target state="translated">Gerar {0} '{1}' aninhado</target> <note /> </trans-unit> <trans-unit id="Global_Namespace"> <source>Global Namespace</source> <target state="translated">Namespace Global</target> <note /> </trans-unit> <trans-unit id="Implement_interface_abstractly"> <source>Implement interface abstractly</source> <target state="translated">Implementar interface de forma abstrata</target> <note /> </trans-unit> <trans-unit id="Implement_interface_through_0"> <source>Implement interface through '{0}'</source> <target state="translated">Implementar interface por meio de "{0}"</target> <note /> </trans-unit> <trans-unit id="Implement_interface"> <source>Implement interface</source> <target state="translated">Implementar a interface</target> <note /> </trans-unit> <trans-unit id="Introduce_field_for_0"> <source>Introduce field for '{0}'</source> <target state="translated">Encapsular campo para "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_local_for_0"> <source>Introduce local for '{0}'</source> <target state="translated">Introduzir local para "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_constant_for_0"> <source>Introduce constant for '{0}'</source> <target state="translated">Introduzir constante para "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_local_constant_for_0"> <source>Introduce local constant for '{0}'</source> <target state="translated">Introduzir constante local para "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_field_for_all_occurrences_of_0"> <source>Introduce field for all occurrences of '{0}'</source> <target state="translated">Introduzir campo para todas as ocorrências de "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_local_for_all_occurrences_of_0"> <source>Introduce local for all occurrences of '{0}'</source> <target state="translated">Introduzir local para todas as ocorrências de "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_constant_for_all_occurrences_of_0"> <source>Introduce constant for all occurrences of '{0}'</source> <target state="translated">Introduzir constante para todas as ocorrências de "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_local_constant_for_all_occurrences_of_0"> <source>Introduce local constant for all occurrences of '{0}'</source> <target state="translated">Introduzir constante de local para todas as ocorrências de "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_query_variable_for_all_occurrences_of_0"> <source>Introduce query variable for all occurrences of '{0}'</source> <target state="translated">Introduzir variável de consulta para todas as ocorrências de "{0}"</target> <note /> </trans-unit> <trans-unit id="Introduce_query_variable_for_0"> <source>Introduce query variable for '{0}'</source> <target state="translated">Introduzir variável de consulta para "{0}"</target> <note /> </trans-unit> <trans-unit id="Anonymous_Types_colon"> <source>Anonymous Types:</source> <target state="translated">Tipos Anônimos:</target> <note /> </trans-unit> <trans-unit id="is_"> <source>is</source> <target state="translated">é</target> <note /> </trans-unit> <trans-unit id="Represents_an_object_whose_operations_will_be_resolved_at_runtime"> <source>Represents an object whose operations will be resolved at runtime.</source> <target state="translated">Representa um objeto cujas operações serão resolvidas no tempo de execução.</target> <note /> </trans-unit> <trans-unit id="constant"> <source>constant</source> <target state="translated">constante</target> <note /> </trans-unit> <trans-unit id="field"> <source>field</source> <target state="translated">Campo</target> <note /> </trans-unit> <trans-unit id="local_constant"> <source>local constant</source> <target state="translated">constante local</target> <note /> </trans-unit> <trans-unit id="local_variable"> <source>local variable</source> <target state="translated">variável local</target> <note /> </trans-unit> <trans-unit id="label"> <source>label</source> <target state="translated">Rótulo</target> <note /> </trans-unit> <trans-unit id="period_era"> <source>period/era</source> <target state="translated">período/era</target> <note /> </trans-unit> <trans-unit id="period_era_description"> <source>The "g" or "gg" custom format specifiers (plus any number of additional "g" specifiers) represents the period or era, such as A.D. The formatting operation ignores this specifier if the date to be formatted doesn't have an associated period or era string. If the "g" format specifier is used without other custom format specifiers, it's interpreted as the "g" standard date and time format specifier.</source> <target state="translated">Os especificadores de formato personalizado "g" ou "gg" (mais qualquer número de especificadores "g" adicionais) representam o período ou a era, como D.C. A operação de formatação ignorará o especificador se a data a ser formatada não tiver um período associado ou uma cadeia de caracteres de era. Se o especificador de formato "g" for usado sem outros especificadores de formato personalizado, ele será interpretado como o especificador de formato padrão de data e hora "g".</target> <note /> </trans-unit> <trans-unit id="property_accessor"> <source>property accessor</source> <target state="new">property accessor</target> <note /> </trans-unit> <trans-unit id="range_variable"> <source>range variable</source> <target state="translated">variável de intervalo</target> <note /> </trans-unit> <trans-unit id="parameter"> <source>parameter</source> <target state="translated">parâmetro</target> <note /> </trans-unit> <trans-unit id="in_"> <source>in</source> <target state="translated">Em</target> <note /> </trans-unit> <trans-unit id="Summary_colon"> <source>Summary:</source> <target state="translated">Resumo:</target> <note /> </trans-unit> <trans-unit id="Locals_and_parameters"> <source>Locals and parameters</source> <target state="translated">Locais e parâmetros</target> <note /> </trans-unit> <trans-unit id="Type_parameters_colon"> <source>Type parameters:</source> <target state="translated">Parâmetros de Tipo:</target> <note /> </trans-unit> <trans-unit id="Returns_colon"> <source>Returns:</source> <target state="translated">Devoluções:</target> <note /> </trans-unit> <trans-unit id="Exceptions_colon"> <source>Exceptions:</source> <target state="translated">Exceções:</target> <note /> </trans-unit> <trans-unit id="Remarks_colon"> <source>Remarks:</source> <target state="translated">Comentários:</target> <note /> </trans-unit> <trans-unit id="generating_source_for_symbols_of_this_type_is_not_supported"> <source>generating source for symbols of this type is not supported</source> <target state="translated">gerar fonte para símbolos deste tipo não é suportado</target> <note /> </trans-unit> <trans-unit id="Assembly"> <source>Assembly</source> <target state="translated">assembly</target> <note /> </trans-unit> <trans-unit id="location_unknown"> <source>location unknown</source> <target state="translated">local desconhecido</target> <note /> </trans-unit> <trans-unit id="Unexpected_interface_member_kind_colon_0"> <source>Unexpected interface member kind: {0}</source> <target state="translated">Tipo de membro de interface inesperado: {0}</target> <note /> </trans-unit> <trans-unit id="Unknown_symbol_kind"> <source>Unknown symbol kind</source> <target state="translated">Tipo de símbolo desconhecido</target> <note /> </trans-unit> <trans-unit id="Generate_abstract_property_1_0"> <source>Generate abstract property '{1}.{0}'</source> <target state="translated">Gerar propriedade abstrata '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_abstract_method_1_0"> <source>Generate abstract method '{1}.{0}'</source> <target state="translated">Gerar método abstrato '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_method_1_0"> <source>Generate method '{1}.{0}'</source> <target state="translated">Gerar método '{1}.{0}'</target> <note /> </trans-unit> <trans-unit id="Requested_assembly_already_loaded_from_0"> <source>Requested assembly already loaded from '{0}'.</source> <target state="translated">Assembly solicitado já carregado de "{0}".</target> <note /> </trans-unit> <trans-unit id="The_symbol_does_not_have_an_icon"> <source>The symbol does not have an icon.</source> <target state="translated">O símbolo não tem um ícone.</target> <note /> </trans-unit> <trans-unit id="Asynchronous_method_cannot_have_ref_out_parameters_colon_bracket_0_bracket"> <source>Asynchronous method cannot have ref/out parameters : [{0}]</source> <target state="translated">Método assíncrono não pode ter parâmetros ref/out: [{0}]</target> <note /> </trans-unit> <trans-unit id="The_member_is_defined_in_metadata"> <source>The member is defined in metadata.</source> <target state="translated">O membro é definido em metadados.</target> <note /> </trans-unit> <trans-unit id="You_can_only_change_the_signature_of_a_constructor_indexer_method_or_delegate"> <source>You can only change the signature of a constructor, indexer, method or delegate.</source> <target state="translated">Você só pode alterar a assinatura de um construtor, indexador, método ou delegate.</target> <note /> </trans-unit> <trans-unit id="This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue"> <source>This symbol has related definitions or references in metadata. Changing its signature may result in build errors. Do you want to continue?</source> <target state="translated">Este símbolo possui definições relacionadas ou referências nos metadados. Alterar sua assinatura pode resultar em erros de compilação. Deseja continuar?</target> <note /> </trans-unit> <trans-unit id="Change_signature"> <source>Change signature...</source> <target state="translated">Alterar assinatura...</target> <note /> </trans-unit> <trans-unit id="Generate_new_type"> <source>Generate new type...</source> <target state="translated">Gerar novo tipo...</target> <note /> </trans-unit> <trans-unit id="User_Diagnostic_Analyzer_Failure"> <source>User Diagnostic Analyzer Failure.</source> <target state="translated">Falha do Analisador de Diagnóstico do Usuário.</target> <note /> </trans-unit> <trans-unit id="Analyzer_0_threw_an_exception_of_type_1_with_message_2"> <source>Analyzer '{0}' threw an exception of type '{1}' with message '{2}'.</source> <target state="translated">O analisador '{0}' gerou uma exceção do tipo '{1}' com a mensagem '{2}'.</target> <note /> </trans-unit> <trans-unit id="Analyzer_0_threw_the_following_exception_colon_1"> <source>Analyzer '{0}' threw the following exception: '{1}'.</source> <target state="translated">O analisador '{0}' gerou a seguinte exceção: '{1}'.</target> <note /> </trans-unit> <trans-unit id="Simplify_Names"> <source>Simplify Names</source> <target state="translated">Simplificar Nomes</target> <note /> </trans-unit> <trans-unit id="Simplify_Member_Access"> <source>Simplify Member Access</source> <target state="translated">Simplificar o Acesso de Membro</target> <note /> </trans-unit> <trans-unit id="Remove_qualification"> <source>Remove qualification</source> <target state="translated">Remover qualificação</target> <note /> </trans-unit> <trans-unit id="Unknown_error_occurred"> <source>Unknown error occurred</source> <target state="translated">Erro desconhecido</target> <note /> </trans-unit> <trans-unit id="Available"> <source>Available</source> <target state="translated">Disponível</target> <note /> </trans-unit> <trans-unit id="Not_Available"> <source>Not Available ⚠</source> <target state="translated">Não Disponível ⚠</target> <note /> </trans-unit> <trans-unit id="_0_1"> <source> {0} - {1}</source> <target state="translated"> {0} - {1}</target> <note /> </trans-unit> <trans-unit id="in_Source"> <source>in Source</source> <target state="translated">na Fonte</target> <note /> </trans-unit> <trans-unit id="in_Suppression_File"> <source>in Suppression File</source> <target state="translated">no Arquivo de Supressão</target> <note /> </trans-unit> <trans-unit id="Remove_Suppression_0"> <source>Remove Suppression {0}</source> <target state="translated">Remover a Supressão {0}</target> <note /> </trans-unit> <trans-unit id="Remove_Suppression"> <source>Remove Suppression</source> <target state="translated">Remover Supressão</target> <note /> </trans-unit> <trans-unit id="Pending"> <source>&lt;Pending&gt;</source> <target state="translated">&lt;Pendente&gt;</target> <note /> </trans-unit> <trans-unit id="Note_colon_Tab_twice_to_insert_the_0_snippet"> <source>Note: Tab twice to insert the '{0}' snippet.</source> <target state="translated">Observação: pressione Tab duas vezes para inserir o snippet '{0}'.</target> <note /> </trans-unit> <trans-unit id="Implement_interface_explicitly_with_Dispose_pattern"> <source>Implement interface explicitly with Dispose pattern</source> <target state="translated">Implementar interface explicitamente com Padrão de descarte</target> <note /> </trans-unit> <trans-unit id="Implement_interface_with_Dispose_pattern"> <source>Implement interface with Dispose pattern</source> <target state="translated">Implementar interface com Padrão de descarte</target> <note /> </trans-unit> <trans-unit id="Re_triage_0_currently_1"> <source>Re-triage {0}(currently '{1}')</source> <target state="translated">Fazer nova triagem de {0}(no momento, "{1}")</target> <note /> </trans-unit> <trans-unit id="Argument_cannot_have_a_null_element"> <source>Argument cannot have a null element.</source> <target state="translated">O argumento não pode ter um elemento nulo.</target> <note /> </trans-unit> <trans-unit id="Argument_cannot_be_empty"> <source>Argument cannot be empty.</source> <target state="translated">O argumento não pode estar vazio.</target> <note /> </trans-unit> <trans-unit id="Reported_diagnostic_with_ID_0_is_not_supported_by_the_analyzer"> <source>Reported diagnostic with ID '{0}' is not supported by the analyzer.</source> <target state="translated">O analisador não dá suporte ao diagnóstico relatado com ID '{0}'.</target> <note /> </trans-unit> <trans-unit id="Computing_fix_all_occurrences_code_fix"> <source>Computing fix all occurrences code fix...</source> <target state="translated">Computando a correção de todas as correções de código de ocorrências…</target> <note /> </trans-unit> <trans-unit id="Fix_all_occurrences"> <source>Fix all occurrences</source> <target state="translated">Corrigir todas as ocorrências</target> <note /> </trans-unit> <trans-unit id="Document"> <source>Document</source> <target state="translated">Documento</target> <note /> </trans-unit> <trans-unit id="Project"> <source>Project</source> <target state="translated">Projeto</target> <note /> </trans-unit> <trans-unit id="Solution"> <source>Solution</source> <target state="translated">Solução</target> <note /> </trans-unit> <trans-unit id="TODO_colon_dispose_managed_state_managed_objects"> <source>TODO: dispose managed state (managed objects)</source> <target state="new">TODO: dispose managed state (managed objects)</target> <note /> </trans-unit> <trans-unit id="TODO_colon_set_large_fields_to_null"> <source>TODO: set large fields to null</source> <target state="new">TODO: set large fields to null</target> <note /> </trans-unit> <trans-unit id="Compiler2"> <source>Compiler</source> <target state="translated">Compilador</target> <note /> </trans-unit> <trans-unit id="Live"> <source>Live</source> <target state="translated">Ao Vivo</target> <note /> </trans-unit> <trans-unit id="enum_value"> <source>enum value</source> <target state="translated">valor de enum</target> <note>{Locked="enum"} "enum" is a C#/VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="const_field"> <source>const field</source> <target state="translated">campo const</target> <note>{Locked="const"} "const" is a C#/VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="method"> <source>method</source> <target state="translated">método</target> <note /> </trans-unit> <trans-unit id="operator_"> <source>operator</source> <target state="translated">Operador</target> <note /> </trans-unit> <trans-unit id="constructor"> <source>constructor</source> <target state="translated">construtor</target> <note /> </trans-unit> <trans-unit id="auto_property"> <source>auto-property</source> <target state="translated">propriedade automática</target> <note /> </trans-unit> <trans-unit id="property_"> <source>property</source> <target state="translated">propriedade</target> <note /> </trans-unit> <trans-unit id="event_accessor"> <source>event accessor</source> <target state="translated">acessador de evento</target> <note /> </trans-unit> <trans-unit id="rfc1123_date_time"> <source>rfc1123 date/time</source> <target state="translated">data/hora rfc1123</target> <note /> </trans-unit> <trans-unit id="rfc1123_date_time_description"> <source>The "R" or "r" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.RFC1123Pattern property. The pattern reflects a defined standard, and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'". When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.</source> <target state="translated">O especificador de formato padrão "R" ou "r" representa uma cadeia de caracteres de formato de data e hora personalizado definida pela propriedade DateTimeFormatInfo.RFC1123Pattern. O padrão reflete um padrão definido e a propriedade é somente leitura. Portanto, é sempre o mesmo, independentemente da cultura usada ou do provedor de formato fornecido. A cadeia de caracteres de formato personalizado é "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'". Quando esse especificador de formato padrão é usado, a operação de análise ou formatação sempre usa a cultura invariável.</target> <note /> </trans-unit> <trans-unit id="round_trip_date_time"> <source>round-trip date/time</source> <target state="translated">data/hora de viagem de ida e volta</target> <note /> </trans-unit> <trans-unit id="round_trip_date_time_description"> <source>The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information and emits a result string that complies with ISO 8601. For DateTime values, this format specifier is designed to preserve date and time values along with the DateTime.Kind property in text. The formatted string can be parsed back by using the DateTime.Parse(String, IFormatProvider, DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set to DateTimeStyles.RoundtripKind. The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values. In this string, the pairs of single quotation marks that delimit individual characters, such as the hyphens, the colons, and the letter "T", indicate that the individual character is a literal that cannot be changed. The apostrophes do not appear in the output string. The "O" or "o" standard format specifier (and the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string) takes advantage of the three ways that ISO 8601 represents time zone information to preserve the Kind property of DateTime values: The time zone component of DateTimeKind.Local date and time values is an offset from UTC (for example, +01:00, -07:00). All DateTimeOffset values are also represented in this format. The time zone component of DateTimeKind.Utc date and time values uses "Z" (which stands for zero offset) to represent UTC. DateTimeKind.Unspecified date and time values have no time zone information. Because the "O" or "o" standard format specifier conforms to an international standard, the formatting or parsing operation that uses the specifier always uses the invariant culture and the Gregorian calendar. Strings that are passed to the Parse, TryParse, ParseExact, and TryParseExact methods of DateTime and DateTimeOffset can be parsed by using the "O" or "o" format specifier if they are in one of these formats. In the case of DateTime objects, the parsing overload that you call should also include a styles parameter with a value of DateTimeStyles.RoundtripKind. Note that if you call a parsing method with the custom format string that corresponds to the "O" or "o" format specifier, you won't get the same results as "O" or "o". This is because parsing methods that use a custom format string can't parse the string representation of date and time values that lack a time zone component or use "Z" to indicate UTC.</source> <target state="translated">O especificador de formato padrão "O" ou "o" representa uma cadeia de caracteres de formato de data e hora personalizado usando um padrão que preserva as informações de fuso horário e emite uma cadeia de resultado que está em conformidade com o ISO 8601. Para valores DateTime, esse especificador de formato é projetado para preservar valores de data e hora juntamente com a propriedade DateTime.Kind no texto. A cadeia de caracteres formatada poderá ser analisada novamente usando o método DateTime.Parse (String, IFormatProvider, DateTimeStyles) ou DateTime.ParseExact se o parâmetro styles estiver definido como DateTimeStyles.RoundtripKind. O especificador de formato padrão "O" ou "o" corresponde à cadeia de caracteres de formato personalizado "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" para valores DateTime e à cadeia de caracteres de formato personalizado "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" para valores de DateTimeOffset. Nessa cadeia de caracteres, os pares de aspas simples que delimitam caracteres individuais, como hifens, dois-pontos e a letra "T", indicam que o caractere individual é um literal que não pode ser alterado. Os apóstrofos não aparecem na cadeia de caracteres de saída. O especificador de formato padrão "O" ou "o" (e a cadeia de caracteres de formato personalizado "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK") aproveita as três maneiras pelas quais o ISO 8601 representa as informações de fuso horário para preservar a propriedade Kind dos valores DateTime: O componente de fuso horário de DateTimeKind.Local dos valores de data e hora é uma diferença do UTC (por exemplo, +01:00, -07:00). Todos os valores de DateTimeOffset também são representados nesse formato. O componente de fuso horário de DateTimeKind.Utc dos valores de data e hora usa "Z" (que significa diferença zero) para representar o UTC. Os valores de data e hora de DateTimeKind.Unspecified não especificados não têm informações de fuso horário. Como o especificador de formato padrão "O" ou "o" está em conformidade com um padrão internacional, a operação de formatação ou análise que usa o especificador sempre usa a cultura invariável e o calendário gregoriano. As cadeias de caracteres que são passadas para os métodos Parse, TryParse, ParseExact e TryParseExact de DateTime e DateTimeOffset podem ser analisadas usando o especificador de formato "O" ou "o" caso elas estejam em um desses formatos. No caso de objetos DateTime, a sobrecarga de análise que você chama também deve incluir um parâmetro styles com um valor de DateTimeStyles.RoundtripKind. Observe que, se você chamar um método de análise com a cadeia de caracteres de formato personalizado que corresponde ao especificador de formato "O" ou "o", você não obterá os mesmos resultados de "O" ou "o". Isso porque os métodos de análise que usam uma cadeia de caracteres de formato personalizado não podem analisar a representação de cadeia de caracteres dos valores de data e hora que não têm um componente de fuso horário ou usar "Z" para indicar o UTC.</target> <note /> </trans-unit> <trans-unit id="second_1_2_digits"> <source>second (1-2 digits)</source> <target state="translated">segundo (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="second_1_2_digits_description"> <source>The "s" custom format specifier represents the seconds as a number from 0 through 59. The result represents whole seconds that have passed since the last minute. A single-digit second is formatted without a leading zero. If the "s" format specifier is used without other custom format specifiers, it's interpreted as the "s" standard date and time format specifier.</source> <target state="translated">O especificador de formato personalizado "s" representa os segundos como um número de 0 a 59. O resultado representa segundos inteiros que passaram desde o último minuto. Um segundo de dígito único é formatado sem um zero à esquerda. Se o especificador de formato "s" for usado sem outros especificadores de formato personalizado, ele será interpretado como o especificador de formato de data e hora padrão "s".</target> <note /> </trans-unit> <trans-unit id="second_2_digits"> <source>second (2 digits)</source> <target state="translated">segundo (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="second_2_digits_description"> <source>The "ss" custom format specifier (plus any number of additional "s" specifiers) represents the seconds as a number from 00 through 59. The result represents whole seconds that have passed since the last minute. A single-digit second is formatted with a leading zero.</source> <target state="translated">O especificador de formato personalizado "ss" (mais qualquer número de especificadores "s" adicionais) representa os segundos como um número de 00 a 59. O resultado representa segundos inteiros que passaram desde o último minuto. Um segundo de dígito único é formatado com um zero à esquerda.</target> <note /> </trans-unit> <trans-unit id="short_date"> <source>short date</source> <target state="translated">data abreviada</target> <note /> </trans-unit> <trans-unit id="short_date_description"> <source>The "d" standard format specifier represents a custom date and time format string that is defined by a specific culture's DateTimeFormatInfo.ShortDatePattern property. For example, the custom format string that is returned by the ShortDatePattern property of the invariant culture is "MM/dd/yyyy".</source> <target state="translated">O especificador de formato padrão "d" representa uma cadeia de caracteres de formato personalizado de data e hora que é definida pela propriedade DateTimeFormatInfo.ShortDatePattern de uma cultura específica. Por exemplo, a cadeia de caracteres de formato personalizado retornada pela propriedade ShortDatePattern da cultura invariável é "MM/dd/yyyy".</target> <note /> </trans-unit> <trans-unit id="short_time"> <source>short time</source> <target state="translated">hora abreviada</target> <note /> </trans-unit> <trans-unit id="short_time_description"> <source>The "t" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.ShortTimePattern property. For example, the custom format string for the invariant culture is "HH:mm".</source> <target state="translated">O especificador de formato padrão "t" representa uma cadeia de caracteres de formato de data e hora personalizada que é definida pela propriedade DateTimeFormatInfo.ShortTimePattern atual. Por exemplo, a cadeia de caracteres de formato personalizado para a cultura invariável é "HH:mm".</target> <note /> </trans-unit> <trans-unit id="sortable_date_time"> <source>sortable date/time</source> <target state="translated">data/hora classificável</target> <note /> </trans-unit> <trans-unit id="sortable_date_time_description"> <source>The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard (ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss". The purpose of the "s" format specifier is to produce result strings that sort consistently in ascending or descending order based on date and time values. As a result, although the "s" standard format specifier represents a date and time value in a consistent format, the formatting operation does not modify the value of the date and time object that is being formatted to reflect its DateTime.Kind property or its DateTimeOffset.Offset value. For example, the result strings produced by formatting the date and time values 2014-11-15T18:32:17+00:00 and 2014-11-15T18:32:17+08:00 are identical. When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.</source> <target state="translated">O especificador de formato padrão "s" representa uma cadeia de caracteres de formato personalizado de data e hora que é definida pela propriedade DateTimeFormatInfo.SortableDateTimePattern. O padrão reflete um padrão definido (ISO 8601) e a propriedade é somente leitura. Portanto, é sempre o mesmo, independentemente da cultura usada ou do provedor de formato fornecido. A cadeia de caracteres de formato personalizado é "yyyy'-'MM'-'dd'T'HH':'mm':'ss". O objetivo do especificador de formato "s" é produzir cadeias de caracteres de resultado que são classificadas consistentemente em ordem crescente ou decrescente com base nos valores de data e hora. Como resultado, embora o especificador de formato padrão "s" represente um valor de data e hora em um formato consistente, a operação de formatação não modifica o valor do objeto de data e hora que está sendo formatado para refletir sua propriedade DateTime.Kind ou seu valor DateTimeOffset.Offset. Por exemplo, as cadeias de caracteres de resultado produzidas pela formatação dos valores de data e hora 2014-11-15T18:32:17+00:00 e 2014-11-15T18:32:17+08:00 são idênticas. Quando esse especificador de formato padrão é usado, a operação de análise ou formatação sempre usa a cultura invariável.</target> <note /> </trans-unit> <trans-unit id="static_constructor"> <source>static constructor</source> <target state="translated">construtor estático</target> <note /> </trans-unit> <trans-unit id="symbol_cannot_be_a_namespace"> <source>'symbol' cannot be a namespace.</source> <target state="translated">"símbolo" não pode ser um namespace.</target> <note /> </trans-unit> <trans-unit id="time_separator"> <source>time separator</source> <target state="translated">separador de hora</target> <note /> </trans-unit> <trans-unit id="time_separator_description"> <source>The ":" custom format specifier represents the time separator, which is used to differentiate hours, minutes, and seconds. The appropriate localized time separator is retrieved from the DateTimeFormatInfo.TimeSeparator property of the current or specified culture. Note: To change the time separator for a particular date and time string, specify the separator character within a literal string delimiter. For example, the custom format string hh'_'dd'_'ss produces a result string in which "_" (an underscore) is always used as the time separator. To change the time separator for all dates for a culture, either change the value of the DateTimeFormatInfo.TimeSeparator property of the current culture, or instantiate a DateTimeFormatInfo object, assign the character to its TimeSeparator property, and call an overload of the formatting method that includes an IFormatProvider parameter. If the ":" format specifier is used without other custom format specifiers, it's interpreted as a standard date and time format specifier and throws a FormatException.</source> <target state="translated">O especificador de formato personalizado ":" representa o separador de hora, que é usado para diferenciar horas, minutos e segundos. O separador de hora localizado apropriado é recuperado da propriedade DateTimeFormatInfo.TimeSeparator da cultura atual ou especificada. Observação: para alterar o separador de hora de uma determinada cadeia de caracteres de data e hora, especifique o caractere separador em um delimitador de cadeia de caracteres literal. Por exemplo, a cadeia de caracteres de formato personalizado hh'_'dd'_'ss produz uma cadeia de caracteres de resultado na qual "_" (um sublinhado) é sempre usado como o separador de hora. Para alterar o separador de hora para todas as datas para uma cultura, altere o valor da propriedade DateTimeFormatInfo.TimeSeparator da cultura atual ou crie uma instância de um objeto DateTimeFormatInfo, atribua o caractere à propriedade TimeSeparator e chame uma sobrecarga do método de formatação que inclui um parâmetro IFormatProvider. Se o especificador de formato ":" for usado sem outros especificadores de formato personalizado, ele será interpretado como um especificador de formato padrão de data e hora e gerará uma FormatException.</target> <note /> </trans-unit> <trans-unit id="time_zone"> <source>time zone</source> <target state="translated">fuso horário</target> <note /> </trans-unit> <trans-unit id="time_zone_description"> <source>The "K" custom format specifier represents the time zone information of a date and time value. When this format specifier is used with DateTime values, the result string is defined by the value of the DateTime.Kind property: For the local time zone (a DateTime.Kind property value of DateTimeKind.Local), this specifier is equivalent to the "zzz" specifier and produces a result string containing the local offset from Coordinated Universal Time (UTC); for example, "-07:00". For a UTC time (a DateTime.Kind property value of DateTimeKind.Utc), the result string includes a "Z" character to represent a UTC date. For a time from an unspecified time zone (a time whose DateTime.Kind property equals DateTimeKind.Unspecified), the result is equivalent to String.Empty. For DateTimeOffset values, the "K" format specifier is equivalent to the "zzz" format specifier, and produces a result string containing the DateTimeOffset value's offset from UTC. If the "K" format specifier is used without other custom format specifiers, it's interpreted as a standard date and time format specifier and throws a FormatException.</source> <target state="translated">O especificador de formato personalizado "K" representa as informações de fuso horário de um valor de data e hora. Quando esse especificador de formato é usado com valores DateTime, a cadeia de caracteres de resultado é definida pelo valor da propriedade DateTime.Kind: Para o fuso horário local (um valor da propriedade DateTime.Kind de DateTimeKind.Local), este especificador é equivalente ao especificador "zzz" e produz uma cadeia de caracteres de resultado contendo o deslocamento local do UTC (Tempo Universal Coordenado); por exemplo, "-07:00". Para uma hora UTC (um valor de propriedade DateTime.Kind de DateTimeKind.Utc), a cadeia de caracteres de resultado inclui um caractere "Z" para representar uma data UTC. Para um horário de um fuso horário não especificado (uma hora cuja propriedade DateTime.Kind seja igual a DateTimeKind.Unspecified), o resultado é equivalente a String.Empty. Para os valores de DateTimeOffset, o especificador de formato "K" é equivalente ao especificador de formato "zzz" e produz uma cadeia de caracteres de resultado contendo o deslocamento do valor de DateTimeOffset do UTC. Se o especificador de formato "K" for usado sem outros especificadores de formato personalizado, ele será interpretado como um especificador de formato padrão de data e hora e gerará uma FormatException.</target> <note /> </trans-unit> <trans-unit id="type"> <source>type</source> <target state="new">type</target> <note /> </trans-unit> <trans-unit id="type_constraint"> <source>type constraint</source> <target state="translated">restrição de tipo</target> <note /> </trans-unit> <trans-unit id="type_parameter"> <source>type parameter</source> <target state="translated">parâmetro de tipo</target> <note /> </trans-unit> <trans-unit id="attribute"> <source>attribute</source> <target state="translated">atributo</target> <note /> </trans-unit> <trans-unit id="Replace_0_and_1_with_property"> <source>Replace '{0}' and '{1}' with property</source> <target state="translated">Substituir "{0}" e "{1}" por propriedades</target> <note /> </trans-unit> <trans-unit id="Replace_0_with_property"> <source>Replace '{0}' with property</source> <target state="translated">Substituir "{0}" por uma propriedade</target> <note /> </trans-unit> <trans-unit id="Method_referenced_implicitly"> <source>Method referenced implicitly</source> <target state="translated">Método referenciado implicitamente</target> <note /> </trans-unit> <trans-unit id="Generate_type_0"> <source>Generate type '{0}'</source> <target state="translated">Gerar tipo '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_0_1"> <source>Generate {0} '{1}'</source> <target state="translated">Gerar {0} '{1}'</target> <note /> </trans-unit> <trans-unit id="Change_0_to_1"> <source>Change '{0}' to '{1}'.</source> <target state="translated">Alterar '{0}' para '{1}'.</target> <note /> </trans-unit> <trans-unit id="Non_invoked_method_cannot_be_replaced_with_property"> <source>Non-invoked method cannot be replaced with property.</source> <target state="translated">O método não invocado não pode ser substituído por uma propriedade.</target> <note /> </trans-unit> <trans-unit id="Only_methods_with_a_single_argument_which_is_not_an_out_variable_declaration_can_be_replaced_with_a_property"> <source>Only methods with a single argument, which is not an out variable declaration, can be replaced with a property.</source> <target state="translated">Somente os métodos com um único argumento, que não é uma declaração de variável externa, podem ser substituídos por uma propriedade.</target> <note /> </trans-unit> <trans-unit id="Roslyn_HostError"> <source>Roslyn.HostError</source> <target state="translated">Roslyn.HostError</target> <note /> </trans-unit> <trans-unit id="An_instance_of_analyzer_0_cannot_be_created_from_1_colon_2"> <source>An instance of analyzer {0} cannot be created from {1}: {2}.</source> <target state="translated">Uma instância do analisador de {0} não pode ser criada de {1} : {2}.</target> <note /> </trans-unit> <trans-unit id="The_assembly_0_does_not_contain_any_analyzers"> <source>The assembly {0} does not contain any analyzers.</source> <target state="translated">O assembly {0} não contém quaisquer analisadores.</target> <note /> </trans-unit> <trans-unit id="Unable_to_load_Analyzer_assembly_0_colon_1"> <source>Unable to load Analyzer assembly {0}: {1}</source> <target state="translated">Não é possível carregar o assembly do Analisador {0} : {1}</target> <note /> </trans-unit> <trans-unit id="Make_method_synchronous"> <source>Make method synchronous</source> <target state="translated">Tornar o método síncrono</target> <note /> </trans-unit> <trans-unit id="from_0"> <source>from {0}</source> <target state="translated">de {0}</target> <note /> </trans-unit> <trans-unit id="Find_and_install_latest_version"> <source>Find and install latest version</source> <target state="translated">Localizar e instalar a versão mais recente</target> <note /> </trans-unit> <trans-unit id="Use_local_version_0"> <source>Use local version '{0}'</source> <target state="translated">Usar a versão local '{0}'</target> <note /> </trans-unit> <trans-unit id="Use_locally_installed_0_version_1_This_version_used_in_colon_2"> <source>Use locally installed '{0}' version '{1}' This version used in: {2}</source> <target state="translated">Use a versão '{0}' instalada localmente '{1}' Essa versão é usada no: {2}</target> <note /> </trans-unit> <trans-unit id="Find_and_install_latest_version_of_0"> <source>Find and install latest version of '{0}'</source> <target state="translated">Localizar e instalar a versão mais recente de '{0}'</target> <note /> </trans-unit> <trans-unit id="Install_with_package_manager"> <source>Install with package manager...</source> <target state="translated">Instalar com o gerenciador de pacotes...</target> <note /> </trans-unit> <trans-unit id="Install_0_1"> <source>Install '{0} {1}'</source> <target state="translated">Instalar '{0} {1}'</target> <note /> </trans-unit> <trans-unit id="Install_version_0"> <source>Install version '{0}'</source> <target state="translated">Instalar a versão '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_variable_0"> <source>Generate variable '{0}'</source> <target state="translated">Gerar variável '{0}'</target> <note /> </trans-unit> <trans-unit id="Classes"> <source>Classes</source> <target state="translated">Classes</target> <note /> </trans-unit> <trans-unit id="Constants"> <source>Constants</source> <target state="translated">Constantes</target> <note /> </trans-unit> <trans-unit id="Delegates"> <source>Delegates</source> <target state="translated">Delega</target> <note /> </trans-unit> <trans-unit id="Enums"> <source>Enums</source> <target state="translated">Enums</target> <note /> </trans-unit> <trans-unit id="Events"> <source>Events</source> <target state="translated">Eventos</target> <note /> </trans-unit> <trans-unit id="Extension_methods"> <source>Extension methods</source> <target state="translated">Métodos de extensão</target> <note /> </trans-unit> <trans-unit id="Fields"> <source>Fields</source> <target state="translated">Campos</target> <note /> </trans-unit> <trans-unit id="Interfaces"> <source>Interfaces</source> <target state="translated">Interfaces</target> <note /> </trans-unit> <trans-unit id="Locals"> <source>Locals</source> <target state="translated">Locais</target> <note /> </trans-unit> <trans-unit id="Methods"> <source>Methods</source> <target state="translated">Métodos</target> <note /> </trans-unit> <trans-unit id="Modules"> <source>Modules</source> <target state="translated">Módulos</target> <note /> </trans-unit> <trans-unit id="Namespaces"> <source>Namespaces</source> <target state="translated">Namespaces</target> <note /> </trans-unit> <trans-unit id="Properties"> <source>Properties</source> <target state="translated">Propriedades</target> <note /> </trans-unit> <trans-unit id="Structures"> <source>Structures</source> <target state="translated">Estruturas</target> <note /> </trans-unit> <trans-unit id="Parameters_colon"> <source>Parameters:</source> <target state="translated">Parâmetros:</target> <note /> </trans-unit> <trans-unit id="Variadic_SignatureHelpItem_must_have_at_least_one_parameter"> <source>Variadic SignatureHelpItem must have at least one parameter.</source> <target state="translated">Variadic SignatureHelpItem deve ter pelo menos um parâmetro.</target> <note /> </trans-unit> <trans-unit id="Replace_0_with_method"> <source>Replace '{0}' with method</source> <target state="translated">Substituir '{0}' com método</target> <note /> </trans-unit> <trans-unit id="Replace_0_with_methods"> <source>Replace '{0}' with methods</source> <target state="translated">Substituir '{0}' com métodos</target> <note /> </trans-unit> <trans-unit id="Property_referenced_implicitly"> <source>Property referenced implicitly</source> <target state="translated">Propriedade referenciada implicitamente</target> <note /> </trans-unit> <trans-unit id="Property_cannot_safely_be_replaced_with_a_method_call"> <source>Property cannot safely be replaced with a method call</source> <target state="translated">A propriedade não pode ser substituída com segurança com uma chamada de método</target> <note /> </trans-unit> <trans-unit id="Convert_to_interpolated_string"> <source>Convert to interpolated string</source> <target state="translated">Converter para cadeia de caracteres interpolada</target> <note /> </trans-unit> <trans-unit id="Move_type_to_0"> <source>Move type to {0}</source> <target state="translated">Mover tipo para {0}</target> <note /> </trans-unit> <trans-unit id="Rename_file_to_0"> <source>Rename file to {0}</source> <target state="translated">Renomear arquivo para {0}</target> <note /> </trans-unit> <trans-unit id="Rename_type_to_0"> <source>Rename type to {0}</source> <target state="translated">Renomear tipo para {0}</target> <note /> </trans-unit> <trans-unit id="Remove_tag"> <source>Remove tag</source> <target state="translated">Remover tag</target> <note /> </trans-unit> <trans-unit id="Add_missing_param_nodes"> <source>Add missing param nodes</source> <target state="translated">Adicionar nós de parâmetro ausentes</target> <note /> </trans-unit> <trans-unit id="Make_containing_scope_async"> <source>Make containing scope async</source> <target state="translated">Tornar o escopo contentor assíncrono</target> <note /> </trans-unit> <trans-unit id="Make_containing_scope_async_return_Task"> <source>Make containing scope async (return Task)</source> <target state="translated">Tornar o escopo contentor assíncrono (retornar Task)</target> <note /> </trans-unit> <trans-unit id="paren_Unknown_paren"> <source>(Unknown)</source> <target state="translated">(Desconhecido)</target> <note /> </trans-unit> <trans-unit id="Use_framework_type"> <source>Use framework type</source> <target state="translated">Usar o tipo de estrutura</target> <note /> </trans-unit> <trans-unit id="Install_package_0"> <source>Install package '{0}'</source> <target state="translated">Instalar o pacote '{0}'</target> <note /> </trans-unit> <trans-unit id="project_0"> <source>project {0}</source> <target state="translated">projeto {0}</target> <note /> </trans-unit> <trans-unit id="Fully_qualify_0"> <source>Fully qualify '{0}'</source> <target state="translated">Qualificar '{0}' totalmente</target> <note /> </trans-unit> <trans-unit id="Remove_reference_to_0"> <source>Remove reference to '{0}'.</source> <target state="translated">Remova a referência a '{0}'.</target> <note /> </trans-unit> <trans-unit id="Keywords"> <source>Keywords</source> <target state="translated">Palavras-chave</target> <note /> </trans-unit> <trans-unit id="Snippets"> <source>Snippets</source> <target state="translated">Snippets</target> <note /> </trans-unit> <trans-unit id="All_lowercase"> <source>All lowercase</source> <target state="translated">Tudo em minúsculas</target> <note /> </trans-unit> <trans-unit id="All_uppercase"> <source>All uppercase</source> <target state="translated">Tudo em maiúsculas</target> <note /> </trans-unit> <trans-unit id="First_word_capitalized"> <source>First word capitalized</source> <target state="translated">Primeira palavra em maiúsculas</target> <note /> </trans-unit> <trans-unit id="Pascal_Case"> <source>Pascal Case</source> <target state="translated">Pascal Case</target> <note /> </trans-unit> <trans-unit id="Remove_document_0"> <source>Remove document '{0}'</source> <target state="translated">Remover documento '{0}'</target> <note /> </trans-unit> <trans-unit id="Add_document_0"> <source>Add document '{0}'</source> <target state="translated">Adicionar documento '{0}'</target> <note /> </trans-unit> <trans-unit id="Add_argument_name_0"> <source>Add argument name '{0}'</source> <target state="translated">Adicionar nome de argumento '{0}'</target> <note /> </trans-unit> <trans-unit id="Take_0"> <source>Take '{0}'</source> <target state="translated">Obter '{0}'</target> <note /> </trans-unit> <trans-unit id="Take_both"> <source>Take both</source> <target state="translated">Obter ambos</target> <note /> </trans-unit> <trans-unit id="Take_bottom"> <source>Take bottom</source> <target state="translated">Obter inferior</target> <note /> </trans-unit> <trans-unit id="Take_top"> <source>Take top</source> <target state="translated">Obter superior</target> <note /> </trans-unit> <trans-unit id="Remove_unused_variable"> <source>Remove unused variable</source> <target state="translated">Remover variável não usada</target> <note /> </trans-unit> <trans-unit id="Convert_to_binary"> <source>Convert to binary</source> <target state="translated">Converter em binário</target> <note /> </trans-unit> <trans-unit id="Convert_to_decimal"> <source>Convert to decimal</source> <target state="translated">Converter em decimal</target> <note /> </trans-unit> <trans-unit id="Convert_to_hex"> <source>Convert to hex</source> <target state="translated">Converter para hexa</target> <note /> </trans-unit> <trans-unit id="Separate_thousands"> <source>Separate thousands</source> <target state="translated">Separar milhares</target> <note /> </trans-unit> <trans-unit id="Separate_words"> <source>Separate words</source> <target state="translated">Separar palavras</target> <note /> </trans-unit> <trans-unit id="Separate_nibbles"> <source>Separate nibbles</source> <target state="translated">Separar nibbles</target> <note /> </trans-unit> <trans-unit id="Remove_separators"> <source>Remove separators</source> <target state="translated">Remover separadores</target> <note /> </trans-unit> <trans-unit id="Add_parameter_to_0"> <source>Add parameter to '{0}'</source> <target state="translated">Adicionar parâmetro ao '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_constructor"> <source>Generate constructor...</source> <target state="translated">Gerar construtor...</target> <note /> </trans-unit> <trans-unit id="Pick_members_to_be_used_as_constructor_parameters"> <source>Pick members to be used as constructor parameters</source> <target state="translated">Escolher membros para que sejam usados como parâmetros do construtor</target> <note /> </trans-unit> <trans-unit id="Pick_members_to_be_used_in_Equals_GetHashCode"> <source>Pick members to be used in Equals/GetHashCode</source> <target state="translated">Escolher membros para que sejam usados em Equals/GetHashCode</target> <note /> </trans-unit> <trans-unit id="Generate_overrides"> <source>Generate overrides...</source> <target state="translated">Gerar substituições...</target> <note /> </trans-unit> <trans-unit id="Pick_members_to_override"> <source>Pick members to override</source> <target state="translated">Escolher membros para substituir</target> <note /> </trans-unit> <trans-unit id="Add_null_check"> <source>Add null check</source> <target state="translated">Adicionar verificação nula</target> <note /> </trans-unit> <trans-unit id="Add_string_IsNullOrEmpty_check"> <source>Add 'string.IsNullOrEmpty' check</source> <target state="translated">Adicionar a verificação 'string.IsNullOrEmpty'</target> <note /> </trans-unit> <trans-unit id="Add_string_IsNullOrWhiteSpace_check"> <source>Add 'string.IsNullOrWhiteSpace' check</source> <target state="translated">Adicionar a verificação 'string.IsNullOrWhiteSpace'</target> <note /> </trans-unit> <trans-unit id="Initialize_field_0"> <source>Initialize field '{0}'</source> <target state="translated">Inicializar campo '{0}'</target> <note /> </trans-unit> <trans-unit id="Initialize_property_0"> <source>Initialize property '{0}'</source> <target state="translated">Inicializar propriedade '{0}'</target> <note /> </trans-unit> <trans-unit id="Add_null_checks"> <source>Add null checks</source> <target state="translated">Adicionar verificações nulas</target> <note /> </trans-unit> <trans-unit id="Generate_operators"> <source>Generate operators</source> <target state="translated">Gerar operadores</target> <note /> </trans-unit> <trans-unit id="Implement_0"> <source>Implement {0}</source> <target state="translated">Implementar {0}</target> <note /> </trans-unit> <trans-unit id="Reported_diagnostic_0_has_a_source_location_in_file_1_which_is_not_part_of_the_compilation_being_analyzed"> <source>Reported diagnostic '{0}' has a source location in file '{1}', which is not part of the compilation being analyzed.</source> <target state="translated">O diagnóstico relatado '{0}' tem um local de origem no arquivo '{1}', que não faz parte da compilação sendo analisada.</target> <note /> </trans-unit> <trans-unit id="Reported_diagnostic_0_has_a_source_location_1_in_file_2_which_is_outside_of_the_given_file"> <source>Reported diagnostic '{0}' has a source location '{1}' in file '{2}', which is outside of the given file.</source> <target state="translated">O diagnóstico relatado '{0}' tem um local de origem '{1}' no arquivo '{2}', que está fora do arquivo fornecido.</target> <note /> </trans-unit> <trans-unit id="in_0_project_1"> <source>in {0} (project {1})</source> <target state="translated">em {0} (projeto {1})</target> <note /> </trans-unit> <trans-unit id="Add_accessibility_modifiers"> <source>Add accessibility modifiers</source> <target state="translated">Adicionar modificadores de acessibilidade</target> <note /> </trans-unit> <trans-unit id="Move_declaration_near_reference"> <source>Move declaration near reference</source> <target state="translated">Mover declaração para próximo da referência</target> <note /> </trans-unit> <trans-unit id="Convert_to_full_property"> <source>Convert to full property</source> <target state="translated">Converter em propriedade completa</target> <note /> </trans-unit> <trans-unit id="Warning_Method_overrides_symbol_from_metadata"> <source>Warning: Method overrides symbol from metadata</source> <target state="translated">Aviso: o método substitui o símbolo de metadados</target> <note /> </trans-unit> <trans-unit id="Use_0"> <source>Use {0}</source> <target state="translated">Usar {0}</target> <note /> </trans-unit> <trans-unit id="Add_argument_name_0_including_trailing_arguments"> <source>Add argument name '{0}' (including trailing arguments)</source> <target state="translated">Adicionar nome de argumento '{0}' (incluindo argumentos à direita)</target> <note /> </trans-unit> <trans-unit id="local_function"> <source>local function</source> <target state="translated">função local</target> <note /> </trans-unit> <trans-unit id="indexer_"> <source>indexer</source> <target state="translated">indexador</target> <note /> </trans-unit> <trans-unit id="Alias_ambiguous_type_0"> <source>Alias ambiguous type '{0}'</source> <target state="translated">Tipo de alias ambíguo '{0}'</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Collection_was_modified_during_iteration"> <source>Warning: Collection was modified during iteration.</source> <target state="translated">Aviso: a coleção foi modificada durante a iteração.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Iteration_variable_crossed_function_boundary"> <source>Warning: Iteration variable crossed function boundary.</source> <target state="translated">Aviso: a variável de iteração passou o limite da função.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Collection_may_be_modified_during_iteration"> <source>Warning: Collection may be modified during iteration.</source> <target state="translated">Aviso: a coleção pode ser modificada durante a iteração.</target> <note /> </trans-unit> <trans-unit id="universal_full_date_time"> <source>universal full date/time</source> <target state="translated">data/hora universal por extenso</target> <note /> </trans-unit> <trans-unit id="universal_full_date_time_description"> <source>The "U" standard format specifier represents a custom date and time format string that is defined by a specified culture's DateTimeFormatInfo.FullDateTimePattern property. The pattern is the same as the "F" pattern. However, the DateTime value is automatically converted to UTC before it is formatted.</source> <target state="translated">O especificador de formato padrão "U" representa uma cadeia de caracteres de formato personalizado de data e hora que é definida pela propriedade DateTimeFormatInfo.FullDateTimePattern de uma cultura especificada. O padrão é o mesmo que o padrão "F". No entanto, o valor DateTime é convertido automaticamente para UTC antes de ser formatado.</target> <note /> </trans-unit> <trans-unit id="universal_sortable_date_time"> <source>universal sortable date/time</source> <target state="translated">data/hora universal classificável</target> <note /> </trans-unit> <trans-unit id="universal_sortable_date_time_description"> <source>The "u" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.UniversalSortableDateTimePattern property. The pattern reflects a defined standard, and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd HH':'mm':'ss'Z'". When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture. Although the result string should express a time as Coordinated Universal Time (UTC), no conversion of the original DateTime value is performed during the formatting operation. Therefore, you must convert a DateTime value to UTC by calling the DateTime.ToUniversalTime method before formatting it.</source> <target state="translated">O especificador de formato padrão "u" representa uma cadeia de caracteres de formato personalizado de data e hora que é definida pela propriedade DateTimeFormatInfo.UniversalSortableDateTimePattern. O padrão reflete um padrão definido e a propriedade é somente leitura. Portanto, é sempre o mesmo, independentemente da cultura usada ou do provedor de formato fornecido. A cadeia de caracteres de formato personalizado é "yyyy'-'MM'-'dd HH':'mm':'ss'Z'". Quando esse especificador de formato padrão é usado, a operação de análise ou formatação sempre usa a cultura invariável. Embora a cadeia de caracteres de resultado deva expressar um horário como UTC (Tempo Universal Coordenado), nenhuma conversão do valor original DateTime é executada durante a operação de formatação. Portanto, você precisa converter um valor DateTime para UTC chamando o método DateTime.ToUniversalTime antes de formatá-lo.</target> <note /> </trans-unit> <trans-unit id="updating_usages_in_containing_member"> <source>updating usages in containing member</source> <target state="translated">atualizando os usos em contém membros</target> <note /> </trans-unit> <trans-unit id="updating_usages_in_containing_project"> <source>updating usages in containing project</source> <target state="translated">usos em que contém o projeto de atualização</target> <note /> </trans-unit> <trans-unit id="updating_usages_in_containing_type"> <source>updating usages in containing type</source> <target state="translated">usos em que contém o tipo de atualização</target> <note /> </trans-unit> <trans-unit id="updating_usages_in_dependent_projects"> <source>updating usages in dependent projects</source> <target state="translated">atualizar usos em projetos dependentes</target> <note /> </trans-unit> <trans-unit id="utc_hour_and_minute_offset"> <source>utc hour and minute offset</source> <target state="translated">diferença de hora e minuto UTC</target> <note /> </trans-unit> <trans-unit id="utc_hour_and_minute_offset_description"> <source>With DateTime values, the "zzz" custom format specifier represents the signed offset of the local operating system's time zone from UTC, measured in hours and minutes. It doesn't reflect the value of an instance's DateTime.Kind property. For this reason, the "zzz" format specifier is not recommended for use with DateTime values. With DateTimeOffset values, this format specifier represents the DateTimeOffset value's offset from UTC in hours and minutes. The offset is always displayed with a leading sign. A plus sign (+) indicates hours ahead of UTC, and a minus sign (-) indicates hours behind UTC. A single-digit offset is formatted with a leading zero.</source> <target state="translated">Com os valores DateTime, o especificador de formato personalizado "ZZZ" representa o deslocamento assinado do fuso horário do sistema operacional local do UTC, medido em horas e minutos. Ele não reflete o valor da propriedade DateTime.Kind de uma instância. Por esse motivo, o especificador de formato "ZZZ" não é recomendado para uso com valores DateTime. Com os valores de DateTimeOffset, este especificador de formato representa o deslocamento do valor de DateTimeOffset do UTC em horas e minutos. O deslocamento é sempre exibido com um sinal à esquerda. Um sinal de adição (+) indica horas à frente do UTC e um sinal de subtração (-) indica horas atrás do UTC. Um deslocamento de dígito único é formatado com um zero à esquerda.</target> <note /> </trans-unit> <trans-unit id="utc_hour_offset_1_2_digits"> <source>utc hour offset (1-2 digits)</source> <target state="translated">diferença horária UTC (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="utc_hour_offset_1_2_digits_description"> <source>With DateTime values, the "z" custom format specifier represents the signed offset of the local operating system's time zone from Coordinated Universal Time (UTC), measured in hours. It doesn't reflect the value of an instance's DateTime.Kind property. For this reason, the "z" format specifier is not recommended for use with DateTime values. With DateTimeOffset values, this format specifier represents the DateTimeOffset value's offset from UTC in hours. The offset is always displayed with a leading sign. A plus sign (+) indicates hours ahead of UTC, and a minus sign (-) indicates hours behind UTC. A single-digit offset is formatted without a leading zero. If the "z" format specifier is used without other custom format specifiers, it's interpreted as a standard date and time format specifier and throws a FormatException.</source> <target state="translated">Com valores DateTime, o especificador de formato personalizado "z" representa o deslocamento assinado do fuso horário do sistema operacional local do UTC (Tempo Universal Coordenado), medido em horas. Ele não reflete o valor da propriedade DateTime.Kind de uma instância. Por esse motivo, o especificador de formato "z" não é recomendado para uso com valores DateTime. Com os valores de DateTimeOffset, este especificador de formato representa o deslocamento do valor de DateTimeOffset do UTC em horas. O deslocamento é sempre exibido com um sinal à esquerda. Um sinal de adição (+) indica horas à frente do UTC e um sinal de subtração (-) indica horas atrás do UTC. Um deslocamento de dígito único é formatado sem um zero à esquerda. Se o especificador de formato "z" for usado sem outros especificadores de formato personalizado, ele será interpretado como um especificador de formato padrão de data e hora e gerará uma FormatException.</target> <note /> </trans-unit> <trans-unit id="utc_hour_offset_2_digits"> <source>utc hour offset (2 digits)</source> <target state="translated">diferença horária UTC (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="utc_hour_offset_2_digits_description"> <source>With DateTime values, the "zz" custom format specifier represents the signed offset of the local operating system's time zone from UTC, measured in hours. It doesn't reflect the value of an instance's DateTime.Kind property. For this reason, the "zz" format specifier is not recommended for use with DateTime values. With DateTimeOffset values, this format specifier represents the DateTimeOffset value's offset from UTC in hours. The offset is always displayed with a leading sign. A plus sign (+) indicates hours ahead of UTC, and a minus sign (-) indicates hours behind UTC. A single-digit offset is formatted with a leading zero.</source> <target state="translated">Com valores DateTime, o especificador de formato personalizado "zz" representa o deslocamento assinado do fuso horário do sistema operacional local do UTC, medido em horas. Ele não reflete o valor da propriedade DateTime.Kind de uma instância. Por esse motivo, o especificador de formato "zz" não é recomendado para uso com valores DateTime. Com os valores de DateTimeOffset, este especificador de formato representa o deslocamento do valor de DateTimeOffset do UTC em horas. O deslocamento é sempre exibido com um sinal à esquerda. Um sinal de adição (+) indica horas à frente do UTC e um sinal de subtração (-) indica horas atrás do UTC. Um deslocamento de dígito único é formatado com um zero à esquerda.</target> <note /> </trans-unit> <trans-unit id="x_y_range_in_reverse_order"> <source>[x-y] range in reverse order</source> <target state="translated">intervalo [x-y] em ordem inversa</target> <note>This is an error message shown to the user when they write an invalid Regular Expression. Example: [b-a]</note> </trans-unit> <trans-unit id="year_1_2_digits"> <source>year (1-2 digits)</source> <target state="translated">ano (1-2 dígitos)</target> <note /> </trans-unit> <trans-unit id="year_1_2_digits_description"> <source>The "y" custom format specifier represents the year as a one-digit or two-digit number. If the year has more than two digits, only the two low-order digits appear in the result. If the first digit of a two-digit year begins with a zero (for example, 2008), the number is formatted without a leading zero. If the "y" format specifier is used without other custom format specifiers, it's interpreted as the "y" standard date and time format specifier.</source> <target state="translated">O especificador de formato personalizado "y" representa o ano como um número de um ou dois dígitos. Se o ano tiver mais de dois dígitos, somente os dois dígitos de ordem baixa aparecerão no resultado. Se o primeiro dígito de um ano de dois dígitos começar com zero (por exemplo, 2008), o número será formatado sem um zero à esquerda. Se o especificador de formato "y" for usado sem outros especificadores de formato personalizado, ele será interpretado como o especificador de formato padrão de data e hora "y".</target> <note /> </trans-unit> <trans-unit id="year_2_digits"> <source>year (2 digits)</source> <target state="translated">ano (2 dígitos)</target> <note /> </trans-unit> <trans-unit id="year_2_digits_description"> <source>The "yy" custom format specifier represents the year as a two-digit number. If the year has more than two digits, only the two low-order digits appear in the result. If the two-digit year has fewer than two significant digits, the number is padded with leading zeros to produce two digits. In a parsing operation, a two-digit year that is parsed using the "yy" custom format specifier is interpreted based on the Calendar.TwoDigitYearMax property of the format provider's current calendar. The following example parses the string representation of a date that has a two-digit year by using the default Gregorian calendar of the en-US culture, which, in this case, is the current culture. It then changes the current culture's CultureInfo object to use a GregorianCalendar object whose TwoDigitYearMax property has been modified.</source> <target state="translated">O especificador de formato personalizado "yy" representa o ano como um número de dois dígitos. Se o ano tiver mais de dois dígitos, somente os dois dígitos de ordem baixa aparecerão no resultado. Se o ano de dois dígitos tiver menos de dois dígitos significativos, o número será preenchido com zeros à esquerda para produzir dois dígitos. Em uma operação de análise, um ano de dois dígitos analisado usando o especificador de formato personalizado "yy" é interpretado com base na Propriedade Calendar.TwoDigitYearMax do calendário atual do provedor de formato. O exemplo a seguir analisa a representação de cadeia de caracteres de uma data que tem um ano de dois dígitos usando o calendário gregoriano padrão da cultura en-US, que, neste caso, é a cultura atual. Em seguida, altera o objeto CultureInfo da cultura atual para usar um objeto GregorianCalendar cuja propriedade TwoDigitYearMax foi modificada.</target> <note /> </trans-unit> <trans-unit id="year_3_4_digits"> <source>year (3-4 digits)</source> <target state="translated">ano (3-4 dígitos)</target> <note /> </trans-unit> <trans-unit id="year_3_4_digits_description"> <source>The "yyy" custom format specifier represents the year with a minimum of three digits. If the year has more than three significant digits, they are included in the result string. If the year has fewer than three digits, the number is padded with leading zeros to produce three digits.</source> <target state="translated">O especificador de formato personalizado "yyy" representa o ano com um mínimo de três dígitos. Se o ano tiver mais de três dígitos significativos, eles serão incluídos na cadeia de caracteres de resultado. Se o ano tiver menos de três dígitos, o número será preenchido com zeros à esquerda para produzir três dígitos.</target> <note /> </trans-unit> <trans-unit id="year_4_digits"> <source>year (4 digits)</source> <target state="translated">ano (4 dígitos)</target> <note /> </trans-unit> <trans-unit id="year_4_digits_description"> <source>The "yyyy" custom format specifier represents the year with a minimum of four digits. If the year has more than four significant digits, they are included in the result string. If the year has fewer than four digits, the number is padded with leading zeros to produce four digits.</source> <target state="translated">O especificador de formato personalizado "yyyy" representa o ano com um mínimo de quatro dígitos. Se o ano tiver mais de quatro dígitos significativos, eles serão incluídos na cadeia de caracteres de resultado. Se o ano tiver menos de quatro dígitos, o número será preenchido com zeros à esquerda para produzir quatro dígitos.</target> <note /> </trans-unit> <trans-unit id="year_5_digits"> <source>year (5 digits)</source> <target state="translated">ano (5 dígitos)</target> <note /> </trans-unit> <trans-unit id="year_5_digits_description"> <source>The "yyyyy" custom format specifier (plus any number of additional "y" specifiers) represents the year with a minimum of five digits. If the year has more than five significant digits, they are included in the result string. If the year has fewer than five digits, the number is padded with leading zeros to produce five digits. If there are additional "y" specifiers, the number is padded with as many leading zeros as necessary to produce the number of "y" specifiers.</source> <target state="translated">O especificador de formato personalizado "yyyyy" (mais qualquer número de especificadores "y" adicionais) representa o ano com um mínimo de cinco dígitos. Se o ano tiver mais de cinco dígitos significativos, eles serão incluídos na cadeia de caracteres de resultado. Se o ano tiver menos de cinco dígitos, o número será preenchido com zeros à esquerda para produzir cinco dígitos. Se houver especificadores "y" adicionais, o número será preenchido com quantos zeros à esquerda forem necessários para produzir o número de especificadores "y".</target> <note /> </trans-unit> <trans-unit id="year_month"> <source>year month</source> <target state="translated">mês do ano</target> <note /> </trans-unit> <trans-unit id="year_month_description"> <source>The "Y" or "y" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.YearMonthPattern property of a specified culture. For example, the custom format string for the invariant culture is "yyyy MMMM".</source> <target state="translated">O especificador de formato padrão "Y" ou "y" representa uma cadeia de caracteres de formato de data e hora personalizado definida pela propriedade DateTimeFormatInfo.YearMonthPattern de uma cultura especificada. Por exemplo, a cadeia de caracteres de formato personalizado para a cultura invariável é "yyyy MMMM".</target> <note /> </trans-unit> </body> </file> </xliff>
-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/Test/Semantic/Semantics/TopLevelStatementsTests.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.Immutable; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.TopLevelStatements)] public class TopLevelStatementsTests : CompilingTestBase { private static CSharpParseOptions DefaultParseOptions => TestOptions.Regular9; private static bool IsNullableAnalysisEnabled(CSharpCompilation compilation) { var type = compilation.GlobalNamespace.GetTypeMember("Program"); var methods = type.GetMembers().OfType<SynthesizedSimpleProgramEntryPointSymbol>(); return methods.Any(m => m.IsNullableAnalysisEnabled()); } [Fact] public void Simple_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.Same(entryPoint, comp.GetEntryPoint(default)); Assert.False(entryPoint.CanBeReferencedByName); Assert.True(entryPoint.ContainingType.CanBeReferencedByName); Assert.Equal("<Main>$", entryPoint.Name); Assert.Equal("Program", entryPoint.ContainingType.Name); } private static void AssertEntryPointParameter(SynthesizedSimpleProgramEntryPointSymbol entryPoint) { Assert.Equal(1, entryPoint.ParameterCount); ParameterSymbol parameter = entryPoint.Parameters.Single(); Assert.Equal("System.String[] args", parameter.ToTestDisplayString(includeNonNullable: true)); Assert.True(parameter.IsImplicitlyDeclared); Assert.Same(entryPoint, parameter.ContainingSymbol); } [Fact] public void Simple_02() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "hello async main"); } [Fact] public void Simple_03() { var text1 = @" System.Console.Write(""1""); "; var text2 = @" // System.Console.Write(""2""); System.Console.WriteLine(); System.Console.WriteLine(); "; var text3 = @" // // System.Console.Write(""3""); System.Console.WriteLine(); System.Console.WriteLine(); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // System.Console.Write("2"); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "System").WithLocation(3, 1) ); comp = CreateCompilation(new[] { text1, text2, text3 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // System.Console.Write("2"); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "System").WithLocation(3, 1), // (4,1): error CS8802: Only one compilation unit can have top-level statements. // System.Console.Write("3"); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "System").WithLocation(4, 1) ); } [Fact] public void Simple_04() { var text = @" Type.M(); static class Type { public static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Simple_05() { var text1 = @" Type.M(); "; var text2 = @" static class Type { public static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Simple_06_01() { var text1 = @" local(); void local() => System.Console.WriteLine(2); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); verifyModel(comp, comp.SyntaxTrees[0]); comp = CreateCompilation(text1, options: TestOptions.DebugExe.WithNullableContextOptions(NullableContextOptions.Enable), parseOptions: DefaultParseOptions); verifyModel(comp, comp.SyntaxTrees[0], nullableEnabled: true); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1, bool nullableEnabled = false) { Assert.Equal(nullableEnabled, IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); verifyModelForGlobalStatements(tree1, model1); var unit1 = (CompilationUnitSyntax)tree1.GetRoot(); var localRef = unit1.DescendantNodes().OfType<IdentifierNameSyntax>().First(); var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Equal("void local()", refSymbol.ToTestDisplayString()); Assert.Contains(refSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(refSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(refSymbol, model1.LookupSymbols(localRef.SpanStart, name: refSymbol.Name).Single()); var operation1 = model1.GetOperation(localRef.Parent); Assert.NotNull(operation1); Assert.IsAssignableFrom<IInvocationOperation>(operation1); Assert.NotNull(ControlFlowGraph.Create((IMethodBodyOperation)((IBlockOperation)operation1.Parent.Parent).Parent)); model1.VerifyOperationTree(unit1, @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'local(); ... iteLine(2);') BlockBody: IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'local(); ... iteLine(2);') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'local();') Expression: IInvocationOperation (void local()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'local()') Instance Receiver: null Arguments(0) ILocalFunctionOperation (Symbol: void local()) (OperationKind.LocalFunction, Type: null) (Syntax: 'void local( ... iteLine(2);') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '=> System.C ... riteLine(2)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'System.Cons ... riteLine(2)') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(2)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '=> System.C ... riteLine(2)') ReturnedValue: null ExpressionBody: null "); var localDecl = unit1.DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Same(declSymbol.ContainingSymbol, model1.GetDeclaredSymbol(unit1)); Assert.Same(declSymbol.ContainingSymbol, model1.GetDeclaredSymbol((SyntaxNode)unit1)); Assert.Same(refSymbol, declSymbol); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); var operation2 = model1.GetOperation(localDecl); Assert.NotNull(operation2); Assert.IsAssignableFrom<ILocalFunctionOperation>(operation2); static void verifyModelForGlobalStatements(SyntaxTree tree1, SemanticModel model1) { var symbolInfo = model1.GetSymbolInfo(tree1.GetRoot()); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var typeInfo = model1.GetTypeInfo(tree1.GetRoot()); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); foreach (var globalStatement in tree1.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>()) { symbolInfo = model1.GetSymbolInfo(globalStatement); Assert.Null(model1.GetOperation(globalStatement)); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); typeInfo = model1.GetTypeInfo(globalStatement); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } } } } [Fact] public void Simple_06_02() { var text1 = @"local();"; var text2 = @"void local() => System.Console.WriteLine(2);"; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8802: Only one compilation unit can have top-level statements. // void local() => System.Console.WriteLine(2); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(1, 1), // (1,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(1, 1), // (1,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(1, 6) ); verifyModel(comp, comp.SyntaxTrees[0], comp.SyntaxTrees[1]); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8802: Only one compilation unit can have top-level statements. // local(); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "local").WithLocation(1, 1), // (1,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(1, 1), // (1,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(1, 6) ); verifyModel(comp, comp.SyntaxTrees[1], comp.SyntaxTrees[0]); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe.WithNullableContextOptions(NullableContextOptions.Enable), parseOptions: DefaultParseOptions); verifyModel(comp, comp.SyntaxTrees[0], comp.SyntaxTrees[1], nullableEnabled: true); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1, SyntaxTree tree2, bool nullableEnabled = false) { Assert.Equal(nullableEnabled, IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); verifyModelForGlobalStatements(tree1, model1); var unit1 = (CompilationUnitSyntax)tree1.GetRoot(); var localRef = unit1.DescendantNodes().OfType<IdentifierNameSyntax>().Single(); var refSymbol = model1.GetSymbolInfo(localRef).Symbol; var refMethod = model1.GetDeclaredSymbol(unit1); Assert.NotNull(refMethod); Assert.Null(refSymbol); var name = localRef.Identifier.ValueText; Assert.DoesNotContain(name, model1.LookupNames(localRef.SpanStart)); Assert.Empty(model1.LookupSymbols(localRef.SpanStart).Where(s => s.Name == name)); Assert.Empty(model1.LookupSymbols(localRef.SpanStart, name: name)); var operation1 = model1.GetOperation(localRef.Parent); Assert.NotNull(operation1); Assert.IsAssignableFrom<IInvalidOperation>(operation1); Assert.NotNull(ControlFlowGraph.Create((IMethodBodyOperation)((IBlockOperation)operation1.Parent.Parent).Parent)); model1.VerifyOperationTree(unit1, @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'local();') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'local();') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'local();') Expression: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'local()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'local') Children(0) ExpressionBody: null "); SyntaxTreeSemanticModel syntaxTreeModel = ((SyntaxTreeSemanticModel)model1); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit1]; var model2 = comp.GetSemanticModel(tree2); verifyModelForGlobalStatements(tree2, model2); var unit2 = (CompilationUnitSyntax)tree2.GetRoot(); var declMethod = model2.GetDeclaredSymbol(unit2); var localDecl = unit2.DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model2.GetDeclaredSymbol(localDecl); Assert.Equal("void local()", declSymbol.ToTestDisplayString()); Assert.Same(declSymbol.ContainingSymbol, declMethod); Assert.NotEqual(refMethod, declMethod); Assert.Contains(declSymbol.Name, model2.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model2.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model2.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); var operation2 = model2.GetOperation(localDecl); Assert.NotNull(operation2); Assert.IsAssignableFrom<ILocalFunctionOperation>(operation2); Assert.NotNull(ControlFlowGraph.Create((IMethodBodyOperation)((IBlockOperation)operation2.Parent).Parent)); var isInvalid = comp.SyntaxTrees[1] == tree2 ? ", IsInvalid" : ""; model2.VerifyOperationTree(unit2, @" IMethodBodyOperation (OperationKind.MethodBody, Type: null" + isInvalid + @") (Syntax: 'void local( ... iteLine(2);') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null" + isInvalid + @", IsImplicit) (Syntax: 'void local( ... iteLine(2);') ILocalFunctionOperation (Symbol: void local()) (OperationKind.LocalFunction, Type: null" + isInvalid + @") (Syntax: 'void local( ... iteLine(2);') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '=> System.C ... riteLine(2)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'System.Cons ... riteLine(2)') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(2)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '=> System.C ... riteLine(2)') ReturnedValue: null ExpressionBody: null "); static void verifyModelForGlobalStatements(SyntaxTree tree1, SemanticModel model1) { var symbolInfo = model1.GetSymbolInfo(tree1.GetRoot()); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var typeInfo = model1.GetTypeInfo(tree1.GetRoot()); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); foreach (var globalStatement in tree1.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>()) { symbolInfo = model1.GetSymbolInfo(globalStatement); Assert.Null(model1.GetOperation(globalStatement)); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); typeInfo = model1.GetTypeInfo(globalStatement); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } } } } [Fact] public void Simple_07() { var text1 = @" var i = 1; local(); "; var text2 = @" void local() => System.Console.WriteLine(i); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(2, 1), // (2,5): warning CS0219: The variable 'i' is assigned but its value is never used // var i = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(2, 5), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,42): error CS0103: The name 'i' does not exist in the current context // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(2, 42), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1) ); verifyModel(comp, comp.SyntaxTrees[0], comp.SyntaxTrees[1]); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var i = 1; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,5): warning CS0219: The variable 'i' is assigned but its value is never used // var i = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(2, 5), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,42): error CS0103: The name 'i' does not exist in the current context // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(2, 42), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1) ); verifyModel(comp, comp.SyntaxTrees[1], comp.SyntaxTrees[0]); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1, SyntaxTree tree2) { Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); Assert.NotNull(model1.GetOperation(tree1.GetRoot())); var operation1 = model1.GetOperation(localDecl); Assert.NotNull(operation1); Assert.IsAssignableFrom<IVariableDeclaratorOperation>(operation1); var localFuncRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local").Single(); Assert.Contains(declSymbol.Name, model1.LookupNames(localFuncRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart, name: declSymbol.Name).Single()); Assert.DoesNotContain(declSymbol, model1.AnalyzeDataFlow(localDecl.Ancestors().OfType<StatementSyntax>().First()).DataFlowsOut); var model2 = comp.GetSemanticModel(tree2); var localRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").Single(); var refSymbol = model2.GetSymbolInfo(localRef).Symbol; Assert.Null(refSymbol); var name = localRef.Identifier.ValueText; Assert.DoesNotContain(name, model2.LookupNames(localRef.SpanStart)); Assert.Empty(model2.LookupSymbols(localRef.SpanStart).Where(s => s.Name == name)); Assert.Empty(model2.LookupSymbols(localRef.SpanStart, name: name)); Assert.NotNull(model2.GetOperation(tree2.GetRoot())); var operation2 = model2.GetOperation(localRef); Assert.NotNull(operation2); Assert.IsAssignableFrom<IInvalidOperation>(operation2); Assert.DoesNotContain(declSymbol, model2.AnalyzeDataFlow(localRef).DataFlowsIn); } } [Fact] public void Simple_08() { var text1 = @" var i = 1; System.Console.Write(i++); System.Console.Write(i); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "12"); var tree1 = comp.SyntaxTrees[0]; Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); var localRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").ToArray(); Assert.Equal(2, localRefs.Length); foreach (var localRef in localRefs) { var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Same(declSymbol, refSymbol); Assert.Contains(declSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localRef.SpanStart, name: declSymbol.Name).Single()); } } [Fact] public void Simple_09() { var text1 = @" var i = 1; local(); void local() => System.Console.WriteLine(i); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1"); verifyModel(comp, comp.SyntaxTrees[0]); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1) { Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); Assert.NotNull(model1.GetOperation(tree1.GetRoot())); var operation1 = model1.GetOperation(localDecl); Assert.NotNull(operation1); Assert.IsAssignableFrom<IVariableDeclaratorOperation>(operation1); var localFuncRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local").Single(); Assert.Contains(declSymbol.Name, model1.LookupNames(localFuncRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart, name: declSymbol.Name).Single()); Assert.Contains(declSymbol, model1.AnalyzeDataFlow(localDecl.Ancestors().OfType<StatementSyntax>().First()).DataFlowsOut); var localRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").Single(); var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Same(declSymbol, refSymbol); Assert.Contains(refSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(refSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(refSymbol, model1.LookupSymbols(localRef.SpanStart, name: refSymbol.Name).Single()); var operation2 = model1.GetOperation(localRef); Assert.NotNull(operation2); Assert.IsAssignableFrom<ILocalReferenceOperation>(operation2); // The following assert fails due to https://github.com/dotnet/roslyn/issues/41853, enable once the issue is fixed. //Assert.Contains(declSymbol, model1.AnalyzeDataFlow(localRef).DataFlowsIn); } } [Fact] public void LanguageVersion_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (1,1): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, @"System.Console.WriteLine(""Hi!"");").WithArguments("top-level statements", "9.0").WithLocation(1, 1) ); } [Fact] public void WithinType_01() { var text = @" class Test { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, parseOptions: DefaultParseOptions); var expected = new[] { // (4,29): error CS1519: Invalid token '(' in class, record, struct, or interface member declaration // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "(").WithArguments("(").WithLocation(4, 29), // (4,30): error CS1031: Type expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_TypeExpected, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS8124: Tuple must contain at least two elements. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_TupleTooFewElements, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS1026: ) expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_CloseParenExpected, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS1519: Invalid token '"Hi!"' in class, record, struct, or interface member declaration // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, @"""Hi!""").WithArguments(@"""Hi!""").WithLocation(4, 30) }; comp.GetDiagnostics(CompilationStage.Parse, includeEarlierStages: false, cancellationToken: default).Verify(expected); comp.VerifyDiagnostics(expected); } [Fact] public void WithinNamespace_01() { var text = @" namespace Test { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, parseOptions: DefaultParseOptions); var expected = new[] { // (4,20): error CS0116: A namespace cannot directly contain members such as fields or methods // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "WriteLine").WithLocation(4, 20), // (4,30): error CS1026: ) expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_CloseParenExpected, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS1022: Type or namespace definition, or end-of-file expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_EOFExpected, @"""Hi!""").WithLocation(4, 30) }; comp.GetDiagnostics(CompilationStage.Parse, includeEarlierStages: false, cancellationToken: default).Verify(expected); comp.VerifyDiagnostics(expected); } [Fact] public void LocalDeclarationStatement_01() { var text = @" string s = ""Hi!""; System.Console.WriteLine(s); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "s").Single(); var local = model.GetDeclaredSymbol(declarator); Assert.Same(local, model.GetSymbolInfo(reference).Symbol); Assert.Equal("System.String s", local.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, local.Kind); Assert.Equal(SymbolKind.Method, local.ContainingSymbol.Kind); Assert.False(local.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, local.ContainingSymbol.ContainingSymbol.Kind); Assert.Equal("Program", local.ContainingSymbol.ContainingSymbol.Name); Assert.False(local.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)local.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); } [Fact] public void LocalDeclarationStatement_02() { var text = @" new string a = ""Hi!""; System.Console.WriteLine(a); public string b = ""Hi!""; System.Console.WriteLine(b); static string c = ""Hi!""; System.Console.WriteLine(c); readonly string d = ""Hi!""; System.Console.WriteLine(d); volatile string e = ""Hi!""; System.Console.WriteLine(e); [System.Obsolete()] string f = ""Hi!""; System.Console.WriteLine(f); [System.Obsolete()] const string g = ""Hi!""; System.Console.WriteLine(g); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,12): error CS0116: A namespace cannot directly contain members such as fields or methods // new string a = "Hi!"; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "a").WithLocation(2, 12), // (2,12): warning CS0109: The member '<invalid-global-code>.a' does not hide an accessible member. The new keyword is not required. // new string a = "Hi!"; Diagnostic(ErrorCode.WRN_NewNotRequired, "a").WithArguments("<invalid-global-code>.a").WithLocation(2, 12), // (3,26): error CS0103: The name 'a' does not exist in the current context // System.Console.WriteLine(a); Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(3, 26), // (4,15): error CS0116: A namespace cannot directly contain members such as fields or methods // public string b = "Hi!"; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(4, 15), // (5,26): error CS0103: The name 'b' does not exist in the current context // System.Console.WriteLine(b); Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(5, 26), // (6,1): error CS0106: The modifier 'static' is not valid for this item // static string c = "Hi!"; Diagnostic(ErrorCode.ERR_BadMemberFlag, "static").WithArguments("static").WithLocation(6, 1), // (8,1): error CS0106: The modifier 'readonly' is not valid for this item // readonly string d = "Hi!"; Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 1), // (10,1): error CS0106: The modifier 'volatile' is not valid for this item // volatile string e = "Hi!"; Diagnostic(ErrorCode.ERR_BadMemberFlag, "volatile").WithArguments("volatile").WithLocation(10, 1), // (12,1): error CS7014: Attributes are not valid in this context. // [System.Obsolete()] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[System.Obsolete()]").WithLocation(12, 1), // (15,1): error CS7014: Attributes are not valid in this context. // [System.Obsolete()] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[System.Obsolete()]").WithLocation(15, 1) ); } [Fact] public void LocalDeclarationStatement_03() { var text = @" string a = ""1""; string a = ""2""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,8): warning CS0219: The variable 'a' is assigned but its value is never used // string a = "1"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(2, 8), // (3,8): error CS0128: A local variable or function named 'a' is already defined in this scope // string a = "2"; Diagnostic(ErrorCode.ERR_LocalDuplicate, "a").WithArguments("a").WithLocation(3, 8), // (3,8): warning CS0219: The variable 'a' is assigned but its value is never used // string a = "2"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(3, 8) ); } [Fact] public void LocalDeclarationStatement_04() { var text = @" using System; using System.Threading.Tasks; var s = await local(); System.Console.WriteLine(s); async Task<string> local() { await Task.Factory.StartNew(() => 5); return ""Hi!""; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalDeclarationStatement_05() { var text = @" const string s = ""Hi!""; System.Console.WriteLine(s); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalDeclarationStatement_06() { var text = @" a.ToString(); string a = ""2""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0841: Cannot use local variable 'a' before it is declared // a.ToString(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "a").WithArguments("a").WithLocation(2, 1) ); } [Fact] public void LocalDeclarationStatement_07() { var text1 = @" string x = ""1""; System.Console.Write(x); "; var text2 = @" int x = 1; System.Console.Write(x); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // int x = 1; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "int").WithLocation(2, 1) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single()); Assert.Equal("System.String x", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single()).Symbol); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var symbol2 = model2.GetDeclaredSymbol(tree2.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single()); Assert.Equal("System.Int32 x", symbol2.ToTestDisplayString()); Assert.Same(symbol2, model2.GetSymbolInfo(tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single()).Symbol); } [Fact] public void LocalDeclarationStatement_08() { var text = @" int a = 0; int b = 0; int c = -100; ref int d = ref c; d = 300; d = ref local(true, ref a, ref b); d = 100; d = ref local(false, ref a, ref b); d = 200; System.Console.Write(a); System.Console.Write(' '); System.Console.Write(b); System.Console.Write(' '); System.Console.Write(c); ref int local(bool flag, ref int a, ref int b) { return ref flag ? ref a : ref b; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "100 200 300", verify: Verification.Skipped); } [Fact] public void LocalDeclarationStatement_09() { var text = @" using var a = new MyDisposable(); System.Console.Write(1); class MyDisposable : System.IDisposable { public void Dispose() { System.Console.Write(2); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "12", verify: Verification.Skipped); } [Fact] public void LocalDeclarationStatement_10() { string source = @" await using var x = new C(); System.Console.Write(""body ""); class C : System.IAsyncDisposable, System.IDisposable { public System.Threading.Tasks.ValueTask DisposeAsync() { System.Console.Write(""DisposeAsync""); return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask); } public void Dispose() { System.Console.Write(""IGNORED""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body DisposeAsync"); } [Fact] public void LocalDeclarationStatement_11() { var text1 = @" string x = ""1""; System.Console.Write(x); int x = 1; System.Console.Write(x); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,5): error CS0128: A local variable or function named 'x' is already defined in this scope // int x = 1; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(4, 5), // (4,5): warning CS0219: The variable 'x' is assigned but its value is never used // int x = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(4, 5) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First()); Assert.Equal("System.String x", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").First()).Symbol); var symbol2 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Skip(1).Single()); Assert.Equal("System.Int32 x", symbol2.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Skip(1).Single()).Symbol); } [Fact] public void LocalDeclarationStatement_12() { var text = @" (int x, int y) = (1, 2); System.Console.WriteLine(x+y); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void LocalDeclarationStatement_13() { var text = @" var (x, y) = (1, 2); System.Console.WriteLine(x+y); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void LocalDeclarationStatement_14() { var text1 = @" string args = ""1""; System.Console.Write(args); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,8): error CS0136: A local or parameter named 'args' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string args = "1"; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "args").WithArguments("args").WithLocation(2, 8) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First()); Assert.Equal("System.String args", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").Single()).Symbol); } [Fact] public void LocalDeclarationStatement_15() { var text1 = @" using System.Linq; string x = null; _ = from x in new object[0] select x; System.Console.Write(x); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,10): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // _ = from x in new object[0] select x; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(4, 10) ); } [Fact] public void LocalDeclarationStatement_16() { var text = @" System.Console.WriteLine(); string await = ""Hi!""; System.Console.WriteLine(await); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,8): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // string await = "Hi!"; Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(3, 8), // (3,8): warning CS0219: The variable 'await' is assigned but its value is never used // string await = "Hi!"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "await").WithArguments("await").WithLocation(3, 8), // (4,31): error CS1525: Invalid expression term ')' // System.Console.WriteLine(await); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(4, 31) ); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnType.IsErrorType()); AssertEntryPointParameter(entryPoint); } [Fact] public void LocalDeclarationStatement_17() { var text = @" string async = ""Hi!""; System.Console.WriteLine(async); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalDeclarationStatement_18() { var text = @" int c = -100; ref int d = ref c; System.Console.Write(d); await System.Threading.Tasks.Task.Yield(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,9): error CS8177: Async methods cannot have by-reference locals // ref int d = ref c; Diagnostic(ErrorCode.ERR_BadAsyncLocalType, "d").WithLocation(3, 9) ); } [Fact] public void UsingStatement_01() { string source = @" await using (var x = new C()) { System.Console.Write(""body ""); } class C : System.IAsyncDisposable, System.IDisposable { public System.Threading.Tasks.ValueTask DisposeAsync() { System.Console.Write(""DisposeAsync""); return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask); } public void Dispose() { System.Console.Write(""IGNORED""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body DisposeAsync"); } [Fact] public void UsingStatement_02() { string source = @" await using (new C()) { System.Console.Write(""body ""); } class C : System.IAsyncDisposable, System.IDisposable { public System.Threading.Tasks.ValueTask DisposeAsync() { System.Console.Write(""DisposeAsync""); return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask); } public void Dispose() { System.Console.Write(""IGNORED""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body DisposeAsync"); } [Fact] public void UsingStatement_03() { string source = @" using (new C()) { System.Console.Write(""body ""); } class C : System.IDisposable { public void Dispose() { System.Console.Write(""Dispose""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body Dispose"); } [Fact] public void ForeachStatement_01() { string source = @" using System.Threading.Tasks; await foreach (var i in new C()) { } System.Console.Write(""Done""); class C { public Enumerator GetAsyncEnumerator() { return new Enumerator(); } public sealed class Enumerator { public async Task<bool> MoveNextAsync() { System.Console.Write(""MoveNextAsync ""); await Task.Yield(); return false; } public int Current { get => throw null; } public async Task DisposeAsync() { System.Console.Write(""DisposeAsync ""); await Task.Yield(); } } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] public void ForeachStatement_02() { var text = @" int i = 0; foreach (var j in new [] {2, 3}) { i += j; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] public void ForeachStatement_03() { var text = @" int i = 0; foreach (var (j, k) in new [] {(2,200), (3,300)}) { i += j; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] public void LocalUsedBeforeDeclaration_01() { var text1 = @" const string x = y; System.Console.Write(x); "; var text2 = @" const string y = x; System.Console.Write(y); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // const string y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "const").WithLocation(2, 1), // (2,18): error CS0103: The name 'y' does not exist in the current context // const string x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 18), // (2,18): error CS0103: The name 'x' does not exist in the current context // const string y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 18) ); comp = CreateCompilation(new[] { "System.Console.WriteLine();", text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // const string x = y; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "const").WithLocation(2, 1), // (2,1): error CS8802: Only one compilation unit can have top-level statements. // const string y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "const").WithLocation(2, 1), // (2,18): error CS0103: The name 'y' does not exist in the current context // const string x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 18), // (2,18): error CS0103: The name 'x' does not exist in the current context // const string y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 18) ); } [Fact] public void LocalUsedBeforeDeclaration_02() { var text1 = @" var x = y; System.Console.Write(x); "; var text2 = @" var y = x; System.Console.Write(y); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,9): error CS0103: The name 'y' does not exist in the current context // var x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 9), // (2,9): error CS0103: The name 'x' does not exist in the current context // var y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 9) ); comp = CreateCompilation(new[] { "System.Console.WriteLine();", text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var x = y; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,9): error CS0103: The name 'y' does not exist in the current context // var x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 9), // (2,9): error CS0103: The name 'x' does not exist in the current context // var y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 9) ); } [Fact] public void LocalUsedBeforeDeclaration_03() { var text1 = @" string x = ""x""; System.Console.Write(x); "; var text2 = @" class C1 { void Test() { System.Console.Write(x); } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,30): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // System.Console.Write(x); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(6, 30) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); var symbol2 = model2.GetSymbolInfo(nameRef).Symbol; Assert.Equal("System.String x", symbol2.ToTestDisplayString()); Assert.Equal("System.String", model2.GetTypeInfo(nameRef).Type.ToTestDisplayString()); Assert.Null(model2.GetOperation(tree2.GetRoot())); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,30): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // System.Console.Write(x); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(6, 30) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel tree2 = comp.SyntaxTrees[0]; model2 = comp.GetSemanticModel(tree2); nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); symbol2 = model2.GetSymbolInfo(nameRef).Symbol; Assert.Equal("System.String x", symbol2.ToTestDisplayString()); Assert.Equal("System.String", model2.GetTypeInfo(nameRef).Type.ToTestDisplayString()); Assert.Null(model2.GetOperation(tree2.GetRoot())); } [Fact] public void LocalUsedBeforeDeclaration_04() { var text1 = @" string x = ""x""; local(); "; var text2 = @" void local() { System.Console.Write(x); } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // void local() Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(2, 1), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,8): warning CS0219: The variable 'x' is assigned but its value is never used // string x = "x"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(2, 8), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1), // (4,26): error CS0103: The name 'x' does not exist in the current context // System.Console.Write(x); Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(4, 26) ); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // string x = "x"; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "string").WithLocation(2, 1), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,8): warning CS0219: The variable 'x' is assigned but its value is never used // string x = "x"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(2, 8), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1), // (4,26): error CS0103: The name 'x' does not exist in the current context // System.Console.Write(x); Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(4, 26) ); } [Fact] public void FlowAnalysis_01() { var text = @" #nullable enable string a = ""1""; string? b; System.Console.WriteLine(b); string? c = null; c.ToString(); d: System.Console.WriteLine(); string e() => ""1""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,8): warning CS0219: The variable 'a' is assigned but its value is never used // string a = "1"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(3, 8), // (5,26): error CS0165: Use of unassigned local variable 'b' // System.Console.WriteLine(b); Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(5, 26), // (7,1): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(7, 1), // (8,1): warning CS0164: This label has not been referenced // d: System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(8, 1), // (9,8): warning CS8321: The local function 'e' is declared but never used // string e() => "1"; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "e").WithArguments("e").WithLocation(9, 8) ); var tree = comp.SyntaxTrees.Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "c").Single(); var model1 = comp.GetSemanticModel(tree); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model1.GetTypeInfo(reference).Nullability.FlowState); var model2 = comp.GetSemanticModel(tree); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model1.GetTypeInfo(reference).Nullability.FlowState); } [Fact] public void FlowAnalysis_02() { var text = @" System.Console.WriteLine(); if (args.Length == 0) { return 10; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0161: '<top-level-statements-entry-point>': not all code paths return a value // System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_ReturnExpected, @"System.Console.WriteLine(); if (args.Length == 0) { return 10; } ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1) ); } [Fact] public void NullableRewrite_01() { var text1 = @" void local1() { System.Console.WriteLine(""local1 - "" + s); } "; var text2 = @" using System; string s = ""Hello world!""; foreach (var c in s) { Console.Write(c); } goto label1; label1: Console.WriteLine(); local1(); local2(); "; var text3 = @" void local2() { System.Console.WriteLine(""local2 - "" + s); } "; var comp = CreateCompilation(new[] { text1, text2, text3 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var tree = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree); foreach (var id in tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>()) { _ = model1.GetTypeInfo(id).Nullability; } var model2 = comp.GetSemanticModel(tree); foreach (var id in tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>()) { _ = model2.GetTypeInfo(id).Nullability; } } [Fact] public void Scope_01() { var text = @" using alias1 = Test; string Test = ""1""; System.Console.WriteLine(Test); class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 5 Test.ToString(); // 6 Test.EndsWith(null); // 7 _ = nameof(Test); // 8 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20), // (34,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(34, 38), // (35,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(35, 13), // (36,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 13), // (37,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 24) ); var getHashCode = ((Compilation)comp).GetMember("System.Object." + nameof(GetHashCode)); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); Assert.Contains(getHashCode.Name, names); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains(getHashCode, symbols); Assert.Same(getHashCode, model1.LookupSymbols(localDecl.SpanStart, name: getHashCode.Name).Single()); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var nameRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[1]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); names = model.LookupNames(nameRef.SpanStart); Assert.DoesNotContain(getHashCode.Name, names); Assert.Contains("Test", names); symbols = model.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(getHashCode, symbols); Assert.Empty(model.LookupSymbols(nameRef.SpanStart, name: getHashCode.Name)); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[2]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[4]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[8]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[9]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[11]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model, IdentifierNameSyntax nameRef) { var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_02() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using alias1 = Test; class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 5 Test.ToString(); // 6 Test.EndsWith(null); // 7 _ = nameof(Test); // 8 } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20), // (31,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(31, 38), // (32,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(32, 13), // (33,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(33, 13), // (34,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(34, 24) ); var getHashCode = ((Compilation)comp).GetMember("System.Object." + nameof(GetHashCode)); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); Assert.Contains(getHashCode.Name, names); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains(getHashCode, symbols); Assert.Same(getHashCode, model1.LookupSymbols(localDecl.SpanStart, name: getHashCode.Name).Single()); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); Assert.Null(model2.GetDeclaredSymbol((CompilationUnitSyntax)tree2.GetRoot())); var nameRefs = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); names = model2.LookupNames(nameRef.SpanStart); Assert.DoesNotContain(getHashCode.Name, names); Assert.Contains("Test", names); symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(getHashCode, symbols); Assert.Empty(model2.LookupSymbols(nameRef.SpanStart, name: getHashCode.Name)); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[1]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model2.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[3]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[7]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[8]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model2.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[10]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_03() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" class Test {} class Derived : Test { void M() { int Test = 0; System.Console.WriteLine(Test++); } } namespace N1 { class Derived : Test { void M() { int Test = 1; System.Console.WriteLine(Test++); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); Assert.Throws<System.ArgumentException>(() => CreateCompilation(new[] { Parse(text1, filename: "text1", DefaultParseOptions), Parse(text1, filename: "text2", TestOptions.Regular6) }, options: TestOptions.DebugExe)); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (2,1): error CS8107: Feature 'top-level statements' is not available in C# 7.0. Please use language version 9.0 or greater. // string Test = "1"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, @"string Test = ""1"";").WithArguments("top-level statements", "9.0").WithLocation(2, 1) ); } [Fact] public void Scope_04() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20), // (36,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 38), // (37,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 13), // (38,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 13), // (39,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(39, 45), // (41,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(41, 24) ); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test()", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); var nameRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); names = model1.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model1.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[2]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[4]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[9]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[10]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[12]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_05() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using alias1 = Test; class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20), // (33,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(33, 38), // (34,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(34, 13), // (35,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(35, 13), // (36,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 45), // (38,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 24) ); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test()", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var nameRefs = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[1]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[3]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[8]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[9]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[11]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_06() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" class Test {} class Derived : Test { void M() { int Test() => 1; int x = Test() + 1; System.Console.WriteLine(x); } } namespace N1 { class Derived : Test { void M() { int Test() => 1; int x = Test() + 1; System.Console.WriteLine(x); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (2,1): error CS8107: Feature 'top-level statements' is not available in C# 7.0. Please use language version 9.0 or greater. // string Test() => "1"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, @"string Test() => ""1"";").WithArguments("top-level statements", "9.0").WithLocation(2, 1) ); } [Fact] public void Scope_07() { var text = @" using alias1 = Test; goto Test; Test: System.Console.WriteLine(""1""); class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); goto Test; // 1 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); goto Test; // 2 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (15,14): error CS0159: No such label 'Test' within the scope of the goto statement // goto Test; // 1 Diagnostic(ErrorCode.ERR_LabelNotFound, "Test").WithArguments("Test").WithLocation(15, 14), // (30,18): error CS0159: No such label 'Test' within the scope of the goto statement // goto Test; // 2 Diagnostic(ErrorCode.ERR_LabelNotFound, "Test").WithArguments("Test").WithLocation(30, 18) ); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var labelDecl = tree1.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(labelDecl); Assert.Equal("Test", declSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Label, declSymbol.Kind); var names = model1.LookupNames(labelDecl.SpanStart); var symbols = model1.LookupSymbols(labelDecl.SpanStart); Assert.Contains("Test", names); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(labelDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(labelDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(labelDecl.SpanStart, name: "Test").Single()); Assert.Same(declSymbol, model1.LookupLabels(labelDecl.SpanStart).Single()); Assert.Same(declSymbol, model1.LookupLabels(labelDecl.SpanStart, name: "Test").Single()); var nameRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); names = model1.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model1.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); Assert.Empty(model1.LookupLabels(nameRef.SpanStart)); Assert.Empty(model1.LookupLabels(nameRef.SpanStart, name: "Test")); nameRef = nameRefs[1]; Assert.Equal("goto Test;", nameRef.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); names = model1.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model1.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); Assert.Same(declSymbol, model1.LookupLabels(nameRef.SpanStart).Single()); Assert.Same(declSymbol, model1.LookupLabels(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[2]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[4]; Assert.Equal("goto Test;", nameRef.Parent.ToString()); Assert.Null(model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[5]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[6]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[8]; Assert.Null(model1.GetSymbolInfo(nameRef).Symbol); Assert.Equal("goto Test;", nameRef.Parent.ToString()); verifyModel(model1, nameRef); void verifyModel(SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); Assert.Empty(model2.LookupLabels(nameRef.SpanStart)); Assert.Empty(model2.LookupLabels(nameRef.SpanStart, name: "Test")); } } [Fact] public void Scope_08() { var text = @" goto Test; Test: System.Console.WriteLine(""1""); class Test {} class Derived : Test { void M() { goto Test; Test: System.Console.WriteLine(); } } namespace N1 { class Derived : Test { void M() { goto Test; Test: System.Console.WriteLine(); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); } [Fact] public void Scope_09() { var text = @" string Test = ""1""; System.Console.WriteLine(Test); new void M() { int Test = 0; System.Console.WriteLine(Test++); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,10): error CS0116: A namespace cannot directly contain members such as fields or methods // new void M() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "M").WithLocation(5, 10), // (5,10): warning CS0109: The member '<invalid-global-code>.M()' does not hide an accessible member. The new keyword is not required. // new void M() Diagnostic(ErrorCode.WRN_NewNotRequired, "M").WithArguments("<invalid-global-code>.M()").WithLocation(5, 10) ); } [Fact] public void Scope_10() { var text = @" string Test = ""1""; System.Console.WriteLine(Test); new int F = C1.GetInt(out var Test); class C1 { public static int GetInt(out int v) { v = 1; return v; } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,9): error CS0116: A namespace cannot directly contain members such as fields or methods // new int F = C1.GetInt(out var Test); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "F").WithLocation(5, 9), // (5,9): warning CS0109: The member '<invalid-global-code>.F' does not hide an accessible member. The new keyword is not required. // new int F = C1.GetInt(out var Test); Diagnostic(ErrorCode.WRN_NewNotRequired, "F").WithArguments("<invalid-global-code>.F").WithLocation(5, 9) ); } [Fact] public void Scope_11() { var text = @" goto Test; Test: System.Console.WriteLine(); new void M() { goto Test; Test: System.Console.WriteLine(); }"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,10): error CS0116: A namespace cannot directly contain members such as fields or methods // new void M() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "M").WithLocation(5, 10), // (5,10): warning CS0109: The member '<invalid-global-code>.M()' does not hide an accessible member. The new keyword is not required. // new void M() Diagnostic(ErrorCode.WRN_NewNotRequired, "M").WithArguments("<invalid-global-code>.M()").WithLocation(5, 10) ); } [Fact] public void Scope_12() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} struct Derived { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; struct Derived { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20), // (36,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 38), // (37,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 13), // (38,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 13), // (39,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(39, 45), // (41,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(41, 24) ); } [Fact] public void Scope_13() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} interface Derived { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; interface Derived { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20), // (36,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 38), // (37,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 13), // (38,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 13), // (39,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(39, 45), // (41,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(41, 24) ); } [Fact] public void Scope_14() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} delegate Test D(alias1 x); namespace N1 { using alias2 = Test; delegate Test D(alias2 x); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); } [Fact] public void Scope_15() { var text = @" const int Test = 1; System.Console.WriteLine(Test); class Test {} enum E1 { T = Test, } namespace N1 { enum E1 { T = Test, } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (9,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // T = Test, Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(9, 9), // (16,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // T = Test, Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 13) ); } [Fact] public void Scope_16() { var text1 = @" using alias1 = System.String; alias1 x = ""1""; alias2 y = ""1""; System.Console.WriteLine(x); System.Console.WriteLine(y); local(); "; var text2 = @" using alias2 = System.String; void local() { alias1 a = ""2""; alias2 b = ""2""; System.Console.WriteLine(a); System.Console.WriteLine(b); } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // void local() Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(3, 1), // (3,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(3, 6), // (4,1): error CS0246: The type or namespace name 'alias2' could not be found (are you missing a using directive or an assembly reference?) // alias2 y = "1"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias2").WithArguments("alias2").WithLocation(4, 1), // (5,5): error CS0246: The type or namespace name 'alias1' could not be found (are you missing a using directive or an assembly reference?) // alias1 a = "2"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias1").WithArguments("alias1").WithLocation(5, 5), // (7,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(7, 1) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var nameRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias1" && !id.Parent.IsKind(SyntaxKind.NameEquals)).Single(); Assert.NotEmpty(model1.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias1")); Assert.Empty(model1.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias2")); nameRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias2").Single(); model1.GetDiagnostics(nameRef.Ancestors().OfType<StatementSyntax>().First().Span).Verify( // (4,1): error CS0246: The type or namespace name 'alias2' could not be found (are you missing a using directive or an assembly reference?) // alias2 y = "1"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias2").WithArguments("alias2").WithLocation(4, 1) ); model1.GetDiagnostics().Verify( // (4,1): error CS0246: The type or namespace name 'alias2' could not be found (are you missing a using directive or an assembly reference?) // alias2 y = "1"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias2").WithArguments("alias2").WithLocation(4, 1), // (7,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(7, 1) ); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias2" && !id.Parent.IsKind(SyntaxKind.NameEquals)).Single(); Assert.Empty(model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias1")); Assert.NotEmpty(model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias2")); nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias1").Single(); model2.GetDiagnostics(nameRef.Ancestors().OfType<StatementSyntax>().First().Span).Verify( // (5,5): error CS0246: The type or namespace name 'alias1' could not be found (are you missing a using directive or an assembly reference?) // alias1 a = "2"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias1").WithArguments("alias1").WithLocation(5, 5) ); model2.GetDiagnostics().Verify( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // void local() Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(3, 1), // (3,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(3, 6), // (5,5): error CS0246: The type or namespace name 'alias1' could not be found (are you missing a using directive or an assembly reference?) // alias1 a = "2"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias1").WithArguments("alias1").WithLocation(5, 5) ); } [Fact] public void Scope_17() { var text = @" using alias1 = N2.Test; using N2; string Test = ""1""; System.Console.WriteLine(Test); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20) ); } [Fact] public void Scope_18() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using alias1 = N2.Test; using N2; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20) ); } [Fact] public void Scope_19() { var text = @" using alias1 = N2.Test; using N2; string Test() => ""1""; System.Console.WriteLine(Test()); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20) ); } [Fact] public void Scope_20() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using alias1 = N2.Test; using N2; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_21() { var text = @" using Test = N2.Test; string Test = ""1""; System.Console.WriteLine(Test); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20) ); } [Fact] public void Scope_22() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using Test = N2.Test; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20) ); } [Fact] public void Scope_23() { var text = @" using Test = N2.Test; string Test() => ""1""; System.Console.WriteLine(Test()); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20) ); } [Fact] public void Scope_24() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using Test = N2.Test; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_25() { var text = @" using alias1 = N2.Test; using static N2; string Test = ""1""; System.Console.WriteLine(Test); class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20) ); } [Fact] public void Scope_26() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using alias1 = N2.Test; using static N2; class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20) ); } [Fact] public void Scope_27() { var text = @" using alias1 = N2.Test; using static N2; string Test() => ""1""; System.Console.WriteLine(Test()); class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20) ); } [Fact] public void Scope_28() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using alias1 = N2.Test; using static N2; class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_29() { var text = @" using static N2; string Test() => ""1""; System.Console.WriteLine(Test()); class N2 { public static string Test() => null; } class Derived { void M() { System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using static N2; class Derived { void M() { System.Console.WriteLine(Test()); Test().ToString(); Test().EndsWith(null); var d = new System.Func<string>(Test); d(); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using static N2; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N2;").WithLocation(2, 1), // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_30() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using static N2; class N2 { public static string Test() => null; } class Derived { void M() { System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using static N2; class Derived { void M() { System.Console.WriteLine(Test()); Test().ToString(); Test().EndsWith(null); var d = new System.Func<string>(Test); d(); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using static N2; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N2;").WithLocation(2, 1), // (10,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(10, 34), // (11,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(11, 9), // (12,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(12, 9), // (13,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 33), // (15,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 20) ); } [Fact] public void Scope_31() { var text = @" using alias1 = args; System.Console.WriteLine(args); class args {} class Derived : args { void M() { args x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 1 args.ToString(); // 2 args[0].EndsWith(null); // 3 _ = nameof(args); } } namespace N1 { using alias2 = args; class Derived : args { void M() { args x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 4 args.ToString(); // 5 args[0].EndsWith(null); // 6 _ = nameof(args); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (15,34): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 1 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(15, 34), // (16,9): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 2 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(16, 9), // (17,9): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(17, 9), // (33,38): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 4 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(33, 38), // (34,13): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 5 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(34, 13), // (35,13): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 6 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(35, 13) ); var testType = ((Compilation)comp).GetTypeByMetadataName("args"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nameRefs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); nameRef = nameRefs[1]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); var parameter = model.GetSymbolInfo(nameRef).Symbol; Assert.Equal("System.String[] args", parameter.ToTestDisplayString()); Assert.Equal("<top-level-statements-entry-point>", parameter.ContainingSymbol.ToTestDisplayString()); names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); symbols = model.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(parameter, symbols); Assert.Same(parameter, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(parameter, symbols); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "args").Single()); nameRef = nameRefs[2]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[4]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[8]; Assert.Equal("using alias2 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[9]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[11]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model, IdentifierNameSyntax nameRef) { var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "args").Single()); } } [Fact] public void Scope_32() { var text1 = @" System.Console.WriteLine(args); "; var text2 = @" using alias1 = args; class args {} class Derived : args { void M() { args x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 1 args.ToString(); // 2 args[0].EndsWith(null); // 3 _ = nameof(args); } } namespace N1 { using alias2 = args; class Derived : args { void M() { args x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 4 args.ToString(); // 5 args[0].EndsWith(null); // 6 _ = nameof(args); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 1 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(13, 34), // (14,9): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 2 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(14, 9), // (15,9): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(15, 9), // (31,38): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 4 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(31, 38), // (32,13): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 5 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(32, 13), // (33,13): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 6 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(33, 13) ); var testType = ((Compilation)comp).GetTypeByMetadataName("args"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees[1]; var model = comp.GetSemanticModel(tree); var nameRefs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); nameRef = nameRefs[1]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[3]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[7]; Assert.Equal("using alias2 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[8]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[10]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); void verifyModel(SemanticModel model, IdentifierNameSyntax nameRef) { var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "args").Single()); } } [Fact] public void Scope_33() { var text = @" System.Console.WriteLine(args); class Test { void M() { System.Console.WriteLine(args); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,34): error CS0103: The name 'args' does not exist in the current context // System.Console.WriteLine(args); Diagnostic(ErrorCode.ERR_NameNotInContext, "args").WithArguments("args").WithLocation(8, 34) ); } [Fact] public void Scope_34() { var text1 = @" System.Console.WriteLine(args); "; var text2 = @" class Test { void M() { System.Console.WriteLine(args); } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,34): error CS0103: The name 'args' does not exist in the current context // System.Console.WriteLine(args); Diagnostic(ErrorCode.ERR_NameNotInContext, "args").WithArguments("args").WithLocation(6, 34) ); } [Fact] public void LocalFunctionStatement_01() { var text = @" local(); void local() { System.Console.WriteLine(15); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "15"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local").Single(); var local = model.GetDeclaredSymbol(declarator); Assert.Same(local, model.GetSymbolInfo(reference).Symbol); Assert.Equal("void local()", local.ToTestDisplayString()); Assert.Equal(MethodKind.LocalFunction, ((IMethodSymbol)local).MethodKind); Assert.Equal(SymbolKind.Method, local.ContainingSymbol.Kind); Assert.False(local.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, local.ContainingSymbol.ContainingSymbol.Kind); Assert.False(local.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)local.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); VerifyFlowGraph(comp, tree.GetRoot(), @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local()] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'local();') Expression: IInvocationOperation (void local()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'local()') Instance Receiver: null Arguments(0) Next (Regular) Block[B2] Leaving: {R1} { void local() Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... teLine(15);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... iteLine(15)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '15') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 15) (Syntax: '15') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2#0R1] Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact] public void LocalFunctionStatement_02() { var text = @" local(); void local() => System.Console.WriteLine(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalFunctionStatement_03() { var text = @" local(); void I1.local() { System.Console.WriteLine(""Hi!""); } interface I1 { void local(); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 1), // (4,6): error CS0540: '<invalid-global-code>.I1.local()': containing type does not implement interface 'I1' // void I1.local() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("<invalid-global-code>.I1.local()", "I1").WithLocation(4, 6), // (4,9): error CS0116: A namespace cannot directly contain members such as fields or methods // void I1.local() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 9) ); } [Fact] public void LocalFunctionStatement_04() { var text = @" new void localA() => System.Console.WriteLine(); localA(); public void localB() => System.Console.WriteLine(); localB(); virtual void localC() => System.Console.WriteLine(); localC(); sealed void localD() => System.Console.WriteLine(); localD(); override void localE() => System.Console.WriteLine(); localE(); abstract void localF() => System.Console.WriteLine(); localF(); partial void localG() => System.Console.WriteLine(); localG(); extern void localH() => System.Console.WriteLine(); localH(); [System.Obsolete()] void localI() => System.Console.WriteLine(); localI(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,10): error CS0116: A namespace cannot directly contain members such as fields or methods // new void localA() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localA").WithLocation(2, 10), // (2,10): warning CS0109: The member '<invalid-global-code>.localA()' does not hide an accessible member. The new keyword is not required. // new void localA() => System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_NewNotRequired, "localA").WithArguments("<invalid-global-code>.localA()").WithLocation(2, 10), // (3,1): error CS0103: The name 'localA' does not exist in the current context // localA(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localA").WithArguments("localA").WithLocation(3, 1), // (4,1): error CS0106: The modifier 'public' is not valid for this item // public void localB() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(4, 1), // (6,14): error CS0116: A namespace cannot directly contain members such as fields or methods // virtual void localC() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localC").WithLocation(6, 14), // (6,14): error CS0621: '<invalid-global-code>.localC()': virtual or abstract members cannot be private // virtual void localC() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "localC").WithArguments("<invalid-global-code>.localC()").WithLocation(6, 14), // (7,1): error CS0103: The name 'localC' does not exist in the current context // localC(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localC").WithArguments("localC").WithLocation(7, 1), // (8,13): error CS0116: A namespace cannot directly contain members such as fields or methods // sealed void localD() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localD").WithLocation(8, 13), // (8,13): error CS0238: '<invalid-global-code>.localD()' cannot be sealed because it is not an override // sealed void localD() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_SealedNonOverride, "localD").WithArguments("<invalid-global-code>.localD()").WithLocation(8, 13), // (9,1): error CS0103: The name 'localD' does not exist in the current context // localD(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localD").WithArguments("localD").WithLocation(9, 1), // (10,15): error CS0116: A namespace cannot directly contain members such as fields or methods // override void localE() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localE").WithLocation(10, 15), // (10,15): error CS0621: '<invalid-global-code>.localE()': virtual or abstract members cannot be private // override void localE() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "localE").WithArguments("<invalid-global-code>.localE()").WithLocation(10, 15), // (10,15): error CS0115: '<invalid-global-code>.localE()': no suitable method found to override // override void localE() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "localE").WithArguments("<invalid-global-code>.localE()").WithLocation(10, 15), // (11,1): error CS0103: The name 'localE' does not exist in the current context // localE(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localE").WithArguments("localE").WithLocation(11, 1), // (12,15): error CS0116: A namespace cannot directly contain members such as fields or methods // abstract void localF() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localF").WithLocation(12, 15), // (12,15): error CS0500: '<invalid-global-code>.localF()' cannot declare a body because it is marked abstract // abstract void localF() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_AbstractHasBody, "localF").WithArguments("<invalid-global-code>.localF()").WithLocation(12, 15), // (12,15): error CS0621: '<invalid-global-code>.localF()': virtual or abstract members cannot be private // abstract void localF() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "localF").WithArguments("<invalid-global-code>.localF()").WithLocation(12, 15), // (13,1): error CS0103: The name 'localF' does not exist in the current context // localF(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localF").WithArguments("localF").WithLocation(13, 1), // (14,14): error CS0116: A namespace cannot directly contain members such as fields or methods // partial void localG() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localG").WithLocation(14, 14), // (14,14): error CS0759: No defining declaration found for implementing declaration of partial method '<invalid-global-code>.localG()' // partial void localG() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "localG").WithArguments("<invalid-global-code>.localG()").WithLocation(14, 14), // (14,14): error CS0751: A partial method must be declared within a partial type // partial void localG() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "localG").WithLocation(14, 14), // (15,1): error CS0103: The name 'localG' does not exist in the current context // localG(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localG").WithArguments("localG").WithLocation(15, 1), // (16,13): error CS0179: 'localH()' cannot be extern and declare a body // extern void localH() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_ExternHasBody, "localH").WithArguments("localH()").WithLocation(16, 13), // (20,1): warning CS0612: 'localI()' is obsolete // localI(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "localI()").WithArguments("localI()").WithLocation(20, 1) ); } [Fact] public void LocalFunctionStatement_05() { var text = @" void local1() => System.Console.Write(""1""); local1(); void local2() => System.Console.Write(""2""); local2(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "12"); } [Fact] public void LocalFunctionStatement_06() { var text = @" local(); static void local() { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalFunctionStatement_07() { var text1 = @" local1(1); void local1(int x) {} local2(); "; var text2 = @" void local1(byte y) {} void local2() { local1(2); } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // void local1(byte y) Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(2, 1), // (5,1): error CS0103: The name 'local2' does not exist in the current context // local2(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local2").WithArguments("local2").WithLocation(5, 1), // (5,6): warning CS8321: The local function 'local2' is declared but never used // void local2() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local2").WithArguments("local2").WithLocation(5, 6) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single()); Assert.Equal("void local1(System.Int32 x)", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").Single()).Symbol); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var symbol2 = model2.GetDeclaredSymbol(tree2.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().First()); Assert.Equal("void local1(System.Byte y)", symbol2.ToTestDisplayString()); Assert.Same(symbol2, model2.GetSymbolInfo(tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").Single()).Symbol); } [Fact] public void LocalFunctionStatement_08() { var text = @" void local() { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6) ); CompileAndVerify(comp, expectedOutput: ""); } [Fact] public void LocalFunctionStatement_09() { var text1 = @" local1(1); void local1(int x) {} local2(); void local1(byte y) {} void local2() { local1(2); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (7,6): error CS0128: A local variable or function named 'local1' is already defined in this scope // void local1(byte y) Diagnostic(ErrorCode.ERR_LocalDuplicate, "local1").WithArguments("local1").WithLocation(7, 6), // (7,6): warning CS8321: The local function 'local1' is declared but never used // void local1(byte y) Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local1").WithArguments("local1").WithLocation(7, 6) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().First()); Assert.Equal("void local1(System.Int32 x)", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").First()).Symbol); var symbol2 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Skip(1).First()); Assert.Equal("void local1(System.Byte y)", symbol2.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").Skip(1).Single()).Symbol); } [Fact] public void LocalFunctionStatement_10() { var text = @" int i = 1; local(); System.Console.WriteLine(i); void local() { i++; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void LocalFunctionStatement_11() { var text1 = @" args(1); void args(int x) {} "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,6): error CS0136: A local or parameter named 'args' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void args(int x) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "args").WithArguments("args").WithLocation(3, 6) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().First()); Assert.Equal("void args(System.Int32 x)", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").Single()).Symbol); } [Fact] public void LocalFunctionStatement_12() { var text1 = @" local(1); void local<args>(args x) { System.Console.WriteLine(x); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "1"); } [Fact] public void LocalFunctionStatement_13() { var text1 = @" local(); void local() { var args = 2; System.Console.WriteLine(args); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void LocalFunctionStatement_14() { var text1 = @" local(3); void local(int args) { System.Console.WriteLine(args); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void LocalFunctionStatement_15() { var text1 = @" local(); void local() { args(4); void args(int x) { System.Console.WriteLine(x); } } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void LocalFunctionStatement_16() { var text1 = @" using System.Linq; _ = from local in new object[0] select local; local(); void local() {} "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,10): error CS1931: The range variable 'local' conflicts with a previous declaration of 'local' // _ = from local in new object[0] select local; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "local").WithArguments("local").WithLocation(3, 10) ); } [Fact] public void LocalFunctionStatement_17() { var text = @" System.Console.WriteLine(); string await() => ""Hi!""; System.Console.WriteLine(await()); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,8): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // string await() => "Hi!"; Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(3, 8), // (3,8): warning CS8321: The local function 'await' is declared but never used // string await() => "Hi!"; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "await").WithArguments("await").WithLocation(3, 8), // (4,32): error CS1525: Invalid expression term ')' // System.Console.WriteLine(await()); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(4, 32) ); } [Fact] public void LocalFunctionStatement_18() { var text = @" string async() => ""Hi!""; System.Console.WriteLine(async()); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Lambda_01() { var text = @" int i = 1; System.Action l = () => i++; l(); System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void PropertyDeclaration_01() { var text = @" _ = local; int local => 1; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,5): error CS0103: The name 'local' does not exist in the current context // _ = local; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 5), // (4,5): error CS0116: A namespace cannot directly contain members such as fields or methods // int local => 1; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 5) ); } [Fact] public void PropertyDeclaration_02() { var text = @" _ = local; int local { get => 1; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,5): error CS0103: The name 'local' does not exist in the current context // _ = local; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 5), // (4,5): error CS0116: A namespace cannot directly contain members such as fields or methods // int local { get => 1; } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 5) ); } [Fact] public void PropertyDeclaration_03() { var text = @" _ = local; int local { get { return 1; } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,5): error CS0103: The name 'local' does not exist in the current context // _ = local; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 5), // (4,5): error CS0116: A namespace cannot directly contain members such as fields or methods // int local { get { return 1; } } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 5) ); } [Fact] public void EventDeclaration_01() { var text = @" local += null; event System.Action local; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0103: The name 'local' does not exist in the current context // local += null; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 1), // (4,21): error CS0116: A namespace cannot directly contain members such as fields or methods // event System.Action local; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 21) ); } [Fact] public void EventDeclaration_02() { var text = @" local -= null; event System.Action local { add {} remove {} } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0103: The name 'local' does not exist in the current context // local -= null; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 1), // (4,21): error CS0116: A namespace cannot directly contain members such as fields or methods // event System.Action local Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 21) ); } [Fact] public void LabeledStatement_01() { var text = @" goto label1; label1: System.Console.WriteLine(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "label1").Single(); var label = model.GetDeclaredSymbol(declarator); Assert.Same(label, model.GetSymbolInfo(reference).Symbol); Assert.Equal("label1", label.ToTestDisplayString()); Assert.Equal(SymbolKind.Label, label.Kind); Assert.Equal(SymbolKind.Method, label.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, label.ContainingSymbol.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)label.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); } [Fact] public void LabeledStatement_02() { var text = @" goto label1; label1: System.Console.WriteLine(""Hi!""); label1: System.Console.WriteLine(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS0140: The label 'label1' is a duplicate // label1: System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_DuplicateLabel, "label1").WithArguments("label1").WithLocation(4, 1) ); } [Fact] public void LabeledStatement_03() { var text1 = @" goto label1; label1: System.Console.Write(1); "; var text2 = @" label1: System.Console.Write(2); goto label1; "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // label1: System.Console.Write(2); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "label1").WithLocation(2, 1) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single()); Assert.Equal("label1", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "label1").Single()).Symbol); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var symbol2 = model2.GetDeclaredSymbol(tree2.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single()); Assert.Equal("label1", symbol2.ToTestDisplayString()); Assert.NotEqual(symbol1, symbol2); Assert.Same(symbol2, model2.GetSymbolInfo(tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "label1").Single()).Symbol); } [Fact] public void LabeledStatement_04() { var text = @" goto args; args: System.Console.WriteLine(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").Single(); var label = model.GetDeclaredSymbol(declarator); Assert.Same(label, model.GetSymbolInfo(reference).Symbol); Assert.Equal("args", label.ToTestDisplayString()); Assert.Equal(SymbolKind.Label, label.Kind); Assert.Equal(SymbolKind.Method, label.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, label.ContainingSymbol.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)label.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); } [Fact] public void ExplicitMain_01() { var text = @" static void Main() {} System.Console.Write(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,13): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(2, 13), // (2,13): warning CS8321: The local function 'Main' is declared but never used // static void Main() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Main").WithArguments("Main").WithLocation(2, 13) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_02() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); static void Main() { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,13): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(6, 13) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_03() { var text = @" using System; using System.Threading.Tasks; System.Console.Write(""Hi!""); partial class Program { static async Task Main() { Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (9,23): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static async Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(9, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_04() { var text = @" using System; using System.Threading.Tasks; await Task.Factory.StartNew(() => 5); System.Console.Write(""Hi!""); partial class Program { static async Task Main() { Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (10,23): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static async Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(10, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_05() { var text = @" using System; using System.Threading.Tasks; await Task.Factory.StartNew(() => 5); System.Console.Write(""Hi!""); partial class Program { static void Main() { Console.Write(""hello ""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (10,17): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(10, 17) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_06() { var text = @" System.Console.Write(""Hi!""); partial class Program { static void Main() { System.Console.Write(""hello ""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,17): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(6, 17) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_07() { var text = @" using System; using System.Threading.Tasks; System.Console.Write(""Hi!""); class Program2 { static void Main(string[] args) { Console.Write(""hello ""); } static async Task Main() { Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (9,17): warning CS7022: The entry point of the program is global code; ignoring 'Program2.Main(string[])' entry point. // static void Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program2.Main(string[])").WithLocation(9, 17), // (14,23): warning CS7022: The entry point of the program is global code; ignoring 'Program2.Main()' entry point. // static async Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program2.Main()").WithLocation(14, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_08() { var text = @" using System; using System.Threading.Tasks; await Task.Factory.StartNew(() => 5); System.Console.Write(""Hi!""); class Program2 { static void Main() { Console.Write(""hello ""); } static async Task Main(string[] args) { await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (10,17): warning CS7022: The entry point of the program is global code; ignoring 'Program2.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program2.Main()").WithLocation(10, 17), // (15,23): warning CS7022: The entry point of the program is global code; ignoring 'Program2.Main(string[])' entry point. // static async Task Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program2.Main(string[])").WithLocation(15, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_09() { var text1 = @" using System; using System.Threading.Tasks; string s = ""Hello world!""; foreach (var c in s) { await N1.Helpers.Wait(); Console.Write(c); } Console.WriteLine(); namespace N1 { class Helpers { static void Main() { } public static async Task Wait() { await Task.Delay(500); } } }"; var text4 = @" using System.Threading.Tasks; class Helpers { public static async Task Wait() { await Task.Delay(500); } } "; var comp = CreateCompilation(new[] { text1, text4 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (19,21): warning CS7022: The entry point of the program is global code; ignoring 'Helpers.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("N1.Helpers.Main()").WithLocation(19, 21) ); } [Fact] public void ExplicitMain_10() { var text = @" using System.Threading.Tasks; System.Console.Write(""Hi!""); class Program2 { static void Main() { } static async Task Main(string[] args) { await Task.Factory.StartNew(() => 5); } } class Program3 { static void Main(string[] args) { } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithMainTypeName("Program2"), parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // error CS8804: Cannot specify /main if there is a compilation unit with top-level statements. Diagnostic(ErrorCode.ERR_SimpleProgramDisallowsMainType).WithLocation(1, 1), // (12,23): warning CS8892: Method 'Program2.Main(string[])' will not be used as an entry point because a synchronous entry point 'Program2.Main()' was found. // static async Task Main(string[] args) Diagnostic(ErrorCode.WRN_SyncAndAsyncEntryPoints, "Main").WithArguments("Program2.Main(string[])", "Program2.Main()").WithLocation(12, 23) ); } [Fact] public void ExplicitMain_11() { var text = @" using System.Threading.Tasks; System.Console.Write(""Hi!""); partial class Program { static void Main() { } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithMainTypeName(""), parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // error CS7088: Invalid 'MainTypeName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "").WithLocation(1, 1), // error CS8804: Cannot specify /main if there is a compilation unit with top-level statements. Diagnostic(ErrorCode.ERR_SimpleProgramDisallowsMainType).WithLocation(1, 1) ); } [Fact] public void ExplicitMain_12() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); void Main() { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_13() { var text = @" System.Console.Write(""H""); Main(""""); System.Console.Write(""!""); static void Main(string args) { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_14() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); static long Main() { System.Console.Write(""i""); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_15() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); static int Main() { System.Console.Write(""i""); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,12): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static int Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(6, 12) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_16() { var text = @" System.Console.Write(""H""); Main(null); System.Console.Write(""!""); static void Main(string[] args) { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,13): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static void Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(6, 13) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_17() { var text = @" System.Console.Write(""H""); Main(null); System.Console.Write(""!""); static int Main(string[] args) { System.Console.Write(""i""); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,12): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static int Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(6, 12) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_18() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(); System.Console.Write(""!""); async static Task Main() { System.Console.Write(""i""); await Task.Yield(); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,19): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // async static Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(8, 19) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_19() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(); System.Console.Write(""!""); static async Task<int> Main() { System.Console.Write(""i""); await Task.Yield(); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,24): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static async Task<int> Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(8, 24) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_20() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(null); System.Console.Write(""!""); static async Task Main(string[] args) { System.Console.Write(""i""); await Task.Yield(); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,19): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static async Task Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(8, 19) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_21() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(null); System.Console.Write(""!""); static async Task<int> Main(string[] args) { System.Console.Write(""i""); await Task.Yield(); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,24): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static async Task<int> Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(8, 24) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_22() { var text = @" System.Console.Write(""H""); Main<int>(); System.Console.Write(""!""); static void Main<T>() { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_23() { var text = @" System.Console.Write(""H""); local(); System.Console.Write(""!""); static void local() { Main(); static void Main() { System.Console.Write(""i""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_24() { var text = @" System.Console.Write(42); partial class Program { static partial void Main(string[] args); } "; var comp = CreateCompilation(text); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyDiagnostics(); } [Fact] public void Yield_01() { var text = @"yield break;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // yield break; Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield break;").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(1, 1) ); } [Fact] public void Yield_02() { var text = @"{yield return 0;}"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // {yield return 0;} Diagnostic(ErrorCode.ERR_BadIteratorReturn, "{yield return 0;}").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(1, 1) ); } [Fact] public void OutOfOrder_01() { var text = @" class C {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(4, 1) ); } [Fact] public void OutOfOrder_02() { var text = @" System.Console.WriteLine(0); namespace C {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_03() { var text = @" class C {} System.Console.WriteLine(1); System.Console.WriteLine(2); class D {} System.Console.WriteLine(3); System.Console.WriteLine(4); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(4, 1) ); } [Fact] public void OutOfOrder_04() { var text = @" System.Console.WriteLine(0); namespace C {} System.Console.WriteLine(1); System.Console.WriteLine(2); namespace D {} System.Console.WriteLine(3); System.Console.WriteLine(4); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_05() { var text = @" System.Console.WriteLine(0); struct S {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_06() { var text = @" System.Console.WriteLine(0); enum C { V } System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_07() { var text = @" System.Console.WriteLine(0); interface C {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_08() { var text = @" System.Console.WriteLine(0); delegate void D (); System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_09() { var text = @" System.Console.WriteLine(0); using System; Console.WriteLine(1); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // using System; Diagnostic(ErrorCode.ERR_UsingAfterElements, "using System;").WithLocation(4, 1), // (6,1): error CS0103: The name 'Console' does not exist in the current context // Console.WriteLine(1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Console").WithArguments("Console").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_10() { var text = @" System.Console.WriteLine(0); [module: MyAttribute] class MyAttribute : System.Attribute {} "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,2): error CS1730: Assembly and module attributes must precede all other elements defined in a file except using clauses and extern alias declarations // [module: MyAttribute] Diagnostic(ErrorCode.ERR_GlobalAttributesNotFirst, "module").WithLocation(4, 2) ); } [Fact] public void OutOfOrder_11() { var text = @" System.Console.WriteLine(0); extern alias A; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS0439: An extern alias declaration must precede all other elements defined in the namespace // extern alias A; Diagnostic(ErrorCode.ERR_ExternAfterElements, "extern").WithLocation(4, 1) ); } [Fact] public void OutOfOrder_12() { var text = @" extern alias A; using System; [module: MyAttribute] Console.WriteLine(1); class MyAttribute : System.Attribute {} "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): hidden CS8020: Unused extern alias. // extern alias A; Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias A;").WithLocation(2, 1), // (2,14): error CS0430: The extern alias 'A' was not specified in a /reference option // extern alias A; Diagnostic(ErrorCode.ERR_BadExternAlias, "A").WithArguments("A").WithLocation(2, 14) ); } [Fact] public void OutOfOrder_13() { var text = @" local(); class C {} void local() => System.Console.WriteLine(1); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // void local() => System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "void local() => System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void Attributes_01() { var text1 = @" [MyAttribute(i)] const int i = 1; [MyAttribute(i + 1)] System.Console.Write(i); [MyAttribute(i + 2)] int j = i; System.Console.Write(j); [MyAttribute(i + 3)] new MyAttribute(i); [MyAttribute(i + 4)] local(); [MyAttribute(i + 5)] void local() {} class MyAttribute : System.Attribute { public MyAttribute(int x) {} } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i)]").WithLocation(2, 1), // (5,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i + 1)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i + 1)]").WithLocation(5, 1), // (8,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i + 2)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i + 2)]").WithLocation(8, 1), // (12,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i + 3)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i + 3)]").WithLocation(12, 1), // (16,1): error CS0246: The type or namespace name 'local' could not be found (are you missing a using directive or an assembly reference?) // local(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "local").WithArguments("local").WithLocation(16, 1), // (16,6): error CS1001: Identifier expected // local(); Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(16, 6), // (16,6): error CS8112: Local function '()' must declare a body because it is not marked 'static extern'. // local(); Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "").WithArguments("()").WithLocation(16, 6), // (19,6): warning CS8321: The local function 'local' is declared but never used // void local() {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(19, 6) ); var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); var localRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").ToArray(); Assert.Equal(9, localRefs.Length); foreach (var localRef in localRefs) { var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Same(declSymbol, refSymbol); Assert.Contains(declSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localRef.SpanStart, name: declSymbol.Name).Single()); } localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1); declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 j", declSymbol.ToTestDisplayString()); } [Fact] public void Attributes_02() { var source = @" using System.Runtime.CompilerServices; return; #pragma warning disable 8321 // Unreferenced local function [MethodImpl(MethodImplOptions.ForwardRef)] static void forwardRef() { System.Console.WriteLine(0); } [MethodImpl(MethodImplOptions.NoInlining)] static void noInlining() { System.Console.WriteLine(1); } [MethodImpl(MethodImplOptions.NoOptimization)] static void noOptimization() { System.Console.WriteLine(2); } [MethodImpl(MethodImplOptions.Synchronized)] static void synchronized() { System.Console.WriteLine(3); } [MethodImpl(MethodImplOptions.InternalCall)] extern static void internalCallStatic(); "; var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: DefaultParseOptions, assemblyValidator: validateAssembly, verify: Verification.Skipped); var comp = verifier.Compilation; var syntaxTree = comp.SyntaxTrees.Single(); var semanticModel = comp.GetSemanticModel(syntaxTree); var localFunctions = syntaxTree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToList(); checkImplAttributes(localFunctions[0], MethodImplAttributes.ForwardRef); checkImplAttributes(localFunctions[1], MethodImplAttributes.NoInlining); checkImplAttributes(localFunctions[2], MethodImplAttributes.NoOptimization); checkImplAttributes(localFunctions[3], MethodImplAttributes.Synchronized); checkImplAttributes(localFunctions[4], MethodImplAttributes.InternalCall); void checkImplAttributes(LocalFunctionStatementSyntax localFunctionStatement, MethodImplAttributes expectedFlags) { var localFunction = semanticModel.GetDeclaredSymbol(localFunctionStatement).GetSymbol<LocalFunctionSymbol>(); Assert.Equal(expectedFlags, localFunction.ImplementationAttributes); } void validateAssembly(PEAssembly assembly) { var peReader = assembly.GetMetadataReader(); foreach (var methodHandle in peReader.MethodDefinitions) { var methodDef = peReader.GetMethodDefinition(methodHandle); var actualFlags = methodDef.ImplAttributes; var methodName = peReader.GetString(methodDef.Name); var expectedFlags = methodName switch { "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__forwardRef|0_0" => MethodImplAttributes.ForwardRef, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__noInlining|0_1" => MethodImplAttributes.NoInlining, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__noOptimization|0_2" => MethodImplAttributes.NoOptimization, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__synchronized|0_3" => MethodImplAttributes.Synchronized, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__internalCallStatic|0_4" => MethodImplAttributes.InternalCall, ".ctor" => MethodImplAttributes.IL, WellKnownMemberNames.TopLevelStatementsEntryPointMethodName => MethodImplAttributes.IL, _ => throw TestExceptionUtilities.UnexpectedValue(methodName) }; Assert.Equal(expectedFlags, actualFlags); } } } [Fact] public void Attributes_03() { var source = @" using System.Runtime.InteropServices; local1(); [DllImport( ""something.dll"", EntryPoint = ""a"", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true, PreserveSig = false, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] static extern void local1(); "; var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: DefaultParseOptions, symbolValidator: validate, sourceSymbolValidator: validate, verify: Verification.Skipped); var comp = verifier.Compilation; var syntaxTree = comp.SyntaxTrees.Single(); var semanticModel = comp.GetSemanticModel(syntaxTree); var localFunction = semanticModel .GetDeclaredSymbol(syntaxTree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single()) .GetSymbol<LocalFunctionSymbol>(); Assert.Equal(new[] { "DllImportAttribute" }, GetAttributeNames(localFunction.GetAttributes())); validateLocalFunction(localFunction); void validate(ModuleSymbol module) { var fromSource = module is SourceModuleSymbol; var program = module.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName); var programAttributes = GetAttributeNames(program.GetAttributes().As<CSharpAttributeData>()); Assert.False(program.IsImplicitlyDeclared); if (fromSource) { Assert.Empty(programAttributes); } else { Assert.Equal(new[] { "CompilerGeneratedAttribute" }, programAttributes); } MethodSymbol method = program.GetMethod(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName); Assert.Empty(method.GetAttributes()); Assert.False(method.IsImplicitlyDeclared); if (!fromSource) { var localFn1 = program.GetMethod("<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__local1|0_0"); Assert.Equal(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(localFn1.GetAttributes().As<CSharpAttributeData>())); validateLocalFunction(localFn1); } } static void validateLocalFunction(MethodSymbol localFunction) { Assert.True(localFunction.IsExtern); var importData = localFunction.GetDllImportData(); Assert.NotNull(importData); Assert.Equal("something.dll", importData.ModuleName); Assert.Equal("a", importData.EntryPointName); Assert.Equal(CharSet.Ansi, importData.CharacterSet); Assert.True(importData.SetLastError); Assert.True(importData.ExactSpelling); Assert.Equal(MethodImplAttributes.IL, localFunction.ImplementationAttributes); Assert.Equal(CallingConvention.Cdecl, importData.CallingConvention); Assert.False(importData.BestFitMapping); Assert.True(importData.ThrowOnUnmappableCharacter); } } [Fact] public void ModelWithIgnoredAccessibility_01() { var source = @" new A().M(); class A { A M() { return new A(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,9): error CS0122: 'A.M()' is inaccessible due to its protection level // new A().M(); Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("A.M()").WithLocation(2, 9) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree = comp.SyntaxTrees.Single(); var invocation = syntaxTree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var semanticModel = comp.GetSemanticModel(syntaxTree); Assert.Equal("A", semanticModel.GetTypeInfo(invocation).Type.Name); Assert.Null(semanticModel.GetSymbolInfo(invocation).Symbol); Assert.Equal("M", semanticModel.GetSymbolInfo(invocation).CandidateSymbols.Single().Name); Assert.Equal(CandidateReason.Inaccessible, semanticModel.GetSymbolInfo(invocation).CandidateReason); Assert.Empty(semanticModel.LookupSymbols(invocation.SpanStart, container: a, name: "M")); semanticModel = comp.GetSemanticModel(syntaxTree, ignoreAccessibility: true); Assert.Equal("A", semanticModel.GetTypeInfo(invocation).Type.Name); Assert.Equal("M", semanticModel.GetSymbolInfo(invocation).Symbol.Name); Assert.NotEmpty(semanticModel.LookupSymbols(invocation.SpanStart, container: a, name: "M")); } [Fact] public void ModelWithIgnoredAccessibility_02() { var source = @" var x = new A().M(); class A { A M() { x = null; return new A(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,17): error CS0122: 'A.M()' is inaccessible due to its protection level // var x = new A().M(); Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("A.M()").WithLocation(2, 17), // (8,9): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // x = null; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(8, 9) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree = comp.SyntaxTrees.Single(); var localDecl = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var localRef = syntaxTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); var semanticModel = comp.GetSemanticModel(syntaxTree, ignoreAccessibility: true); var x = semanticModel.GetDeclaredSymbol(localDecl); Assert.Same(x, semanticModel.LookupSymbols(localDecl.SpanStart, name: "x").Single()); Assert.Same(x, semanticModel.GetSymbolInfo(localRef).Symbol); Assert.Same(x, semanticModel.LookupSymbols(localRef.SpanStart, name: "x").Single()); } [Fact] public void ModelWithIgnoredAccessibility_03() { var source = @" var x = new B().M(1); class A { public long M(long i) => i; } class B : A { protected int M(int i) { _ = x; return i; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,13): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // _ = x; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(13, 13) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree1 = comp.SyntaxTrees.Single(); var localDecl = syntaxTree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var localRef = syntaxTree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); verifyModel(ignoreAccessibility: true, "System.Int32"); verifyModel(ignoreAccessibility: false, "System.Int64"); void verifyModel(bool ignoreAccessibility, string expectedType) { var semanticModel1 = comp.GetSemanticModel(syntaxTree1, ignoreAccessibility); var xDecl = semanticModel1.GetDeclaredSymbol(localDecl); Assert.Same(xDecl, semanticModel1.LookupSymbols(localDecl.SpanStart, name: "x").Single()); var xRef = semanticModel1.GetSymbolInfo(localRef).Symbol; Assert.Same(xRef, semanticModel1.LookupSymbols(localRef.SpanStart, name: "x").Single()); Assert.Equal(expectedType, ((ILocalSymbol)xRef).Type.ToTestDisplayString()); Assert.Equal(expectedType, ((ILocalSymbol)xDecl).Type.ToTestDisplayString()); Assert.Same(xDecl, xRef); } } [Fact] public void ModelWithIgnoredAccessibility_04() { var source1 = @" var x = new B().M(1); "; var source2 = @" class A { public long M(long i) => i; } class B : A { protected int M(int i) { _ = x; return i; } } "; var comp = CreateCompilation(new[] { source1, source2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (11,13): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // _ = x; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(11, 13) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree1 = comp.SyntaxTrees.First(); var localDecl = syntaxTree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var syntaxTree2 = comp.SyntaxTrees[1]; var localRef = syntaxTree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); verifyModel(ignoreAccessibility: true, "System.Int32"); verifyModel(ignoreAccessibility: false, "System.Int64"); void verifyModel(bool ignoreAccessibility, string expectedType) { var semanticModel1 = comp.GetSemanticModel(syntaxTree1, ignoreAccessibility); var xDecl = semanticModel1.GetDeclaredSymbol(localDecl); Assert.Same(xDecl, semanticModel1.LookupSymbols(localDecl.SpanStart, name: "x").Single()); Assert.Equal(expectedType, ((ILocalSymbol)xDecl).Type.ToTestDisplayString()); var semanticModel2 = comp.GetSemanticModel(syntaxTree2, ignoreAccessibility); var xRef = semanticModel2.GetSymbolInfo(localRef).Symbol; Assert.Same(xRef, semanticModel2.LookupSymbols(localRef.SpanStart, name: "x").Single()); Assert.Equal(expectedType, ((ILocalSymbol)xRef).Type.ToTestDisplayString()); Assert.Same(xDecl, xRef); } } [Fact] public void AnalyzerActions_01() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_01_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(0, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(0, analyzer.FireCount6); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_01_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); } private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.GlobalStatement); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.CompilationUnit); } private void Handle1(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var globalStatement = (GlobalStatementSyntax)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (globalStatement.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(globalStatement.SyntaxTree, context.ContainingSymbol.DeclaringSyntaxReferences.Single().SyntaxTree); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(globalStatement.Parent)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[globalStatement.Parent]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(globalStatement.Statement).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(globalStatement.Statement)); } private void Handle2(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var unit = (CompilationUnitSyntax)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (unit.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref context.ContainingSymbol.Kind == SymbolKind.Namespace ? ref FireCount5 : ref FireCount3); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref context.ContainingSymbol.Kind == SymbolKind.Namespace ? ref FireCount6 : ref FireCount4); break; default: Assert.True(false); break; } switch (context.ContainingSymbol.ToTestDisplayString()) { case "<top-level-statements-entry-point>": Assert.Same(unit.SyntaxTree, context.ContainingSymbol.DeclaringSyntaxReferences.Single().SyntaxTree); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(unit)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(unit).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(unit)); break; case "<global namespace>": break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_02() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_02_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_02_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_02_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.Method); } private void Handle(SymbolAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); switch (context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_03() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_03_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(0, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(0, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_03_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); } private class AnalyzerActions_03_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolStartAction(Handle1, SymbolKind.Method); context.RegisterSymbolStartAction(Handle2, SymbolKind.NamedType); } private void Handle1(SymbolStartAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); switch (context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); context.RegisterSymbolEndAction(Handle3); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); context.RegisterSymbolEndAction(Handle4); break; default: Assert.True(false); break; } } private void Handle2(SymbolStartAnalysisContext context) { Assert.Equal(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount3); context.RegisterSymbolEndAction(Handle5); foreach (var syntaxReference in context.Symbol.DeclaringSyntaxReferences) { switch (syntaxReference.GetSyntax().ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount4); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount5); break; default: Assert.True(false); break; } } } private void Handle3(SymbolAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); Assert.Equal("System.Console.WriteLine(1);", context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); } private void Handle4(SymbolAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); Assert.Equal("System.Console.WriteLine(2);", context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); } private void Handle5(SymbolAnalysisContext context) { Assert.Equal(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); } } [Fact] public void AnalyzerActions_04() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_04_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(0, analyzer.FireCount4); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_04_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationAction(Handle1, OperationKind.Invocation); context.RegisterOperationAction(Handle2, OperationKind.Block); } private void Handle1(OperationAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(context.ContainingSymbol.DeclaringSyntaxReferences.Single().SyntaxTree, context.Operation.Syntax.SyntaxTree); Assert.Equal(SyntaxKind.InvocationExpression, context.Operation.Syntax.Kind()); switch (context.Operation.Syntax.ToString()) { case "System.Console.WriteLine(1)": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2)": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } private void Handle2(OperationAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(context.ContainingSymbol.DeclaringSyntaxReferences.Single().GetSyntax(), context.Operation.Syntax); Assert.Equal(SyntaxKind.CompilationUnit, context.Operation.Syntax.Kind()); switch (context.Operation.Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount3); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_05() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_05_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_05_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockAction(Handle); } private void Handle(OperationBlockAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.OperationBlocks.Single().Syntax.Kind()); switch (context.OperationBlocks.Single().Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_06() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_06_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_06_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_06_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle); } private void Handle(OperationBlockStartAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.OperationBlocks.Single().Syntax.Kind()); switch (context.OperationBlocks.Single().Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_07() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_07_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_07_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(Handle); } private void Handle(CodeBlockAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.CodeBlock.Kind()); switch (context.CodeBlock.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } var model = context.SemanticModel; var unit = (CompilationUnitSyntax)context.CodeBlock; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(unit).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(unit)); } } [Fact] public void AnalyzerActions_08() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_08_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_08_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_08_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(Handle); } private void Handle(CodeBlockStartAnalysisContext<SyntaxKind> context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.CodeBlock.Kind()); switch (context.CodeBlock.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } var model = context.SemanticModel; var unit = (CompilationUnitSyntax)context.CodeBlock; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(unit).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(unit)); } } [Fact] public void AnalyzerActions_09() { var text1 = @" System.Console.WriteLine(""Hi!""); "; var text2 = @" class Test { void M() { M(); } } "; var analyzer = new AnalyzerActions_09_Analyzer(); var comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); analyzer = new AnalyzerActions_09_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(2, analyzer.FireCount4); } private class AnalyzerActions_09_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.InvocationExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.CompilationUnit); } private void Handle1(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var node = (CSharpSyntaxNode)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (node.ToString()) { case @"System.Console.WriteLine(""Hi!"")": Interlocked.Increment(ref FireCount1); Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); break; case "M()": Interlocked.Increment(ref FireCount2); Assert.Equal("void Test.M()", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } var decl = (CSharpSyntaxNode)context.ContainingSymbol.DeclaringSyntaxReferences.Single().GetSyntax(); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(decl)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[decl]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(node).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(node)); } private void Handle2(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var node = (CSharpSyntaxNode)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (context.ContainingSymbol.ToTestDisplayString()) { case @"<top-level-statements-entry-point>": Interlocked.Increment(ref FireCount3); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(node)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[node]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(node).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(node)); break; case "<global namespace>": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_10() { var text1 = @" [assembly: MyAttribute(1)] "; var text2 = @" System.Console.WriteLine(""Hi!""); "; var text3 = @" [MyAttribute(2)] class Test { [MyAttribute(3)] void M() { } } class MyAttribute : System.Attribute { public MyAttribute(int x) {} } "; var analyzer = new AnalyzerActions_10_Analyzer(); var comp = CreateCompilation(text1 + text2 + text3, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); analyzer = new AnalyzerActions_10_Analyzer(); comp = CreateCompilation(new[] { text1, text2, text3 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(3, analyzer.FireCount5); } private class AnalyzerActions_10_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.Attribute); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.CompilationUnit); } private void Handle1(SyntaxNodeAnalysisContext context) { var node = (CSharpSyntaxNode)context.Node; switch (node.ToString()) { case @"MyAttribute(1)": Interlocked.Increment(ref FireCount1); Assert.Equal("<global namespace>", context.ContainingSymbol.ToTestDisplayString()); break; case @"MyAttribute(2)": Interlocked.Increment(ref FireCount2); Assert.Equal("Test", context.ContainingSymbol.ToTestDisplayString()); break; case @"MyAttribute(3)": Interlocked.Increment(ref FireCount3); Assert.Equal("void Test.M()", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } } private void Handle2(SyntaxNodeAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case @"<top-level-statements-entry-point>": Interlocked.Increment(ref FireCount4); break; case @"<global namespace>": Interlocked.Increment(ref FireCount5); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_11() { var text1 = @" System.Console.WriteLine(""Hi!""); "; var text2 = @" namespace N1 {} class C1 {} "; var analyzer = new AnalyzerActions_11_Analyzer(); var comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); analyzer = new AnalyzerActions_11_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_11_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle1, SymbolKind.Method); context.RegisterSymbolAction(Handle2, SymbolKind.Namespace); context.RegisterSymbolAction(Handle3, SymbolKind.NamedType); } private void Handle1(SymbolAnalysisContext context) { Interlocked.Increment(ref FireCount1); Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); } private void Handle2(SymbolAnalysisContext context) { Interlocked.Increment(ref FireCount2); Assert.Equal("N1", context.Symbol.ToTestDisplayString()); } private void Handle3(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "C1": Interlocked.Increment(ref FireCount3); break; case WellKnownMemberNames.TopLevelStatementsEntryPointTypeName: Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_12() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_12_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_12_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(2, analyzer.FireCount3); } private class AnalyzerActions_12_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle1); } private void Handle1(OperationBlockStartAnalysisContext context) { Interlocked.Increment(ref FireCount3); context.RegisterOperationBlockEndAction(Handle2); } private void Handle2(OperationBlockAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.OperationBlocks.Single().Syntax.Kind()); switch (context.OperationBlocks.Single().Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_13() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_13_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_13_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(2, analyzer.FireCount3); } private class AnalyzerActions_13_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle1); } private void Handle1(OperationBlockStartAnalysisContext context) { Interlocked.Increment(ref FireCount3); context.RegisterOperationAction(Handle2, OperationKind.Block); } private void Handle2(OperationAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(context.ContainingSymbol.DeclaringSyntaxReferences.Single().GetSyntax(), context.Operation.Syntax); Assert.Equal(SyntaxKind.CompilationUnit, context.Operation.Syntax.Kind()); switch (context.Operation.Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void MissingTypes_01() { var text = @"return;"; var comp = CreateEmptyCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (1,1): error CS0518: Predefined type 'System.Object' is not defined or imported // return; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "return").WithArguments("System.Object").WithLocation(1, 1), // error CS0518: Predefined type 'System.Void' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Void").WithLocation(1, 1), // error CS0518: Predefined type 'System.String' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.String").WithLocation(1, 1), // (1,1): error CS1729: 'object' does not contain a constructor that takes 0 arguments // return; Diagnostic(ErrorCode.ERR_BadCtorArgCount, "return").WithArguments("object", "0").WithLocation(1, 1) ); } [Fact] public void MissingTypes_02() { var text = @"await Test();"; var comp = CreateCompilation(text, targetFramework: TargetFramework.Minimal, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Threading.Tasks.Task' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Threading.Tasks.Task").WithLocation(1, 1), // (1,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await Test(); Diagnostic(ErrorCode.WRN_InvalidMainSig, "await Test();").WithArguments("<top-level-statements-entry-point>").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (1,7): error CS0103: The name 'Test' does not exist in the current context // await Test(); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(1, 7) ); } [Fact] public void MissingTypes_03() { var text = @" System.Console.WriteLine(""Hi!""); return 10; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_Int32); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32[missing]", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Int32' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Int32").WithLocation(1, 1), // (3,8): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 10; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "10").WithArguments("System.Int32").WithLocation(3, 8) ); } [Fact] public void MissingTypes_04() { var text = @" await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_Int32); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32[missing]>", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Int32' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Int32").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (2,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.WRN_InvalidMainSig, @"await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); return 11; ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Int32' is not defined or imported // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await System.Threading.Tasks.Task.Factory.StartNew(() => 5L);").WithArguments("System.Int32").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Int32' is not defined or imported // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await System.Threading.Tasks.Task.Factory.StartNew(() => 5L);").WithArguments("System.Int32").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Int32' is not defined or imported // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await System.Threading.Tasks.Task.Factory.StartNew(() => 5L);").WithArguments("System.Int32").WithLocation(2, 1), // (3,8): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 11; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "11").WithArguments("System.Int32").WithLocation(3, 8) ); } [Fact] public void MissingTypes_05() { var text = @" await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(WellKnownType.System_Threading_Tasks_Task_T); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32>[missing]", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Threading.Tasks.Task`1' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Threading.Tasks.Task`1").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (2,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await System.Threading.Tasks.Task.Factory.StartNew(() => "5"); Diagnostic(ErrorCode.WRN_InvalidMainSig, @"await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1) ); } [Fact] public void MissingTypes_06() { var text = @" await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_Int32); comp.MakeTypeMissing(WellKnownType.System_Threading_Tasks_Task_T); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32[missing]>[missing]", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Threading.Tasks.Task`1' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Threading.Tasks.Task`1").WithLocation(1, 1), // error CS0518: Predefined type 'System.Int32' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Int32").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (2,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await System.Threading.Tasks.Task.Factory.StartNew(() => "5"); Diagnostic(ErrorCode.WRN_InvalidMainSig, @"await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1), // (3,8): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 11; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "11").WithArguments("System.Int32").WithLocation(3, 8) ); } [Fact] public void MissingTypes_07() { var text = @" System.Console.WriteLine(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_String); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.String[missing][] args", entryPoint.Parameters.Single().ToTestDisplayString()); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.String' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.String").WithLocation(1, 1) ); } [Fact] public void Return_01() { var text = @" System.Console.WriteLine(args[0]); return; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Return_01", args: new[] { "Return_01" }); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" name=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2"" startColumn=""1"" endLine=""2"" endColumn=""35"" document=""1"" /> <entry offset=""0x9"" startLine=""3"" startColumn=""1"" endLine=""3"" endColumn=""8"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } private static string EscapeForXML(string toEscape) { return toEscape.Replace("<", "&lt;").Replace(">", "&gt;"); } [Fact] public void Return_02() { var text = @" System.Console.WriteLine(args[0]); return 10; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Return_02", args: new[] { "Return_02" }, expectedReturnCode: 10); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" name=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2"" startColumn=""1"" endLine=""2"" endColumn=""35"" document=""1"" /> <entry offset=""0x9"" startLine=""3"" startColumn=""1"" endLine=""3"" endColumn=""11"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } [Fact] public void Return_03() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(args[0]); return; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "hello Return_03", args: new[] { "Return_03" }); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "+<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">d__0.MoveNext", @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""&lt;Main&gt;"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;&gt;c"" methodName=""&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;b__0_0"" /> <encLocalSlotMap> <slot kind=""27"" offset=""2"" /> <slot kind=""33"" offset=""76"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""5"" startColumn=""1"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x19"" startLine=""6"" startColumn=""1"" endLine=""6"" endColumn=""38"" document=""1"" /> <entry offset=""0x48"" hidden=""true"" document=""1"" /> <entry offset=""0x99"" startLine=""7"" startColumn=""1"" endLine=""7"" endColumn=""24"" document=""1"" /> <entry offset=""0xa7"" startLine=""8"" startColumn=""1"" endLine=""8"" endColumn=""8"" document=""1"" /> <entry offset=""0xa9"" hidden=""true"" document=""1"" /> <entry offset=""0xc1"" hidden=""true"" document=""1"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0xa9"" /> <kickoffMethod declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <await yield=""0x5a"" resume=""0x75"" declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } [Fact] public void Return_04() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(args[0]); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32>", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "hello Return_04", args: new[] { "Return_04" }, expectedReturnCode: 11); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "+<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">d__0.MoveNext", @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""&lt;Main&gt;"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;&gt;c"" methodName=""&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;b__0_0"" /> <encLocalSlotMap> <slot kind=""27"" offset=""2"" /> <slot kind=""20"" offset=""2"" /> <slot kind=""33"" offset=""76"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""5"" startColumn=""1"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x19"" startLine=""6"" startColumn=""1"" endLine=""6"" endColumn=""38"" document=""1"" /> <entry offset=""0x48"" hidden=""true"" document=""1"" /> <entry offset=""0x99"" startLine=""7"" startColumn=""1"" endLine=""7"" endColumn=""24"" document=""1"" /> <entry offset=""0xa7"" startLine=""8"" startColumn=""1"" endLine=""8"" endColumn=""11"" document=""1"" /> <entry offset=""0xac"" hidden=""true"" document=""1"" /> <entry offset=""0xc6"" hidden=""true"" document=""1"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0xac"" /> <kickoffMethod declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <await yield=""0x5a"" resume=""0x75"" declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } [Fact] public void Return_05() { var text = @" System.Console.WriteLine(""Hi!""); return ""error""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyDiagnostics( // (3,8): error CS0029: Cannot implicitly convert type 'string' to 'int' // return "error"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""error""").WithArguments("string", "int").WithLocation(3, 8) ); } [Fact] public void Return_06() { var text = @" System.Func<int, int> d = n => { System.Console.WriteLine(""Hi!""); return n; }; d(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_07() { var text = @" System.Func<int, int> d = delegate(int n) { System.Console.WriteLine(""Hi!""); return n; }; d(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_08() { var text = @" System.Func<int, int> d = (n) => { System.Console.WriteLine(""Hi!""); return n; }; d(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_09() { var text = @" int local(int n) { System.Console.WriteLine(""Hi!""); return n; } local(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_10() { var text = @" bool b = true; if (b) return 0; else return; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyDiagnostics( // (6,5): error CS0126: An object of a type convertible to 'int' is required // return; Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("int").WithLocation(6, 5) ); } [Fact] public void Return_11() { var text = @" bool b = true; if (b) return; else return 0; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyDiagnostics( // (4,5): error CS0126: An object of a type convertible to 'int' is required // return; Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("int").WithLocation(4, 5) ); } [Fact] public void Return_12() { var text = @" System.Console.WriteLine(1); return; System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "1").VerifyDiagnostics( // (4,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(4, 1) ); } [Fact] public void Return_13() { var text = @" System.Console.WriteLine(1); return 13; System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "1", expectedReturnCode: 13).VerifyDiagnostics( // (4,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(4, 1) ); } [Fact] public void Return_14() { var text = @" System.Console.WriteLine(""Hi!""); return default; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!", expectedReturnCode: 0); } [Fact] public void Return_15() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); return default; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32>", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "hello async main", expectedReturnCode: 0); } [Fact] public void Dll_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugDll, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (1,1): error CS8805: Program using top-level statements must be an executable. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, @"System.Console.WriteLine(""Hi!"");").WithLocation(1, 1) ); } [Fact] public void NetModule_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.ReleaseModule, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (1,1): error CS8805: Program using top-level statements must be an executable. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, @"System.Console.WriteLine(""Hi!"");").WithLocation(1, 1) ); } [Fact] public void ExpressionStatement_01() { // Await expression is covered in other tests var text = @" new Test(0); // ObjectCreationExpression: Test x; x = new Test(1); // SimpleAssignmentExpression: x += 1; // AddAssignmentExpression: x -= 2; // SubtractAssignmentExpression: x *= 3; // MultiplyAssignmentExpression: x /= 4; // DivideAssignmentExpression: x %= 5; // ModuloAssignmentExpression: x &= 6; // AndAssignmentExpression: x |= 7; // OrAssignmentExpression: x ^= 8; // ExclusiveOrAssignmentExpression: x <<= 9; // LeftShiftAssignmentExpression: x >>= 10; // RightShiftAssignmentExpression: x++; // PostIncrementExpression: x--; // PostDecrementExpression: ++x; // PreIncrementExpression: --x; // PreDecrementExpression: System.Console.WriteLine(x.Count); // InvocationExpression: x?.WhenNotNull(); // ConditionalAccessExpression: x = null; x ??= new Test(-1); // CoalesceAssignmentExpression: System.Console.WriteLine(x.Count); // InvocationExpression: class Test { public readonly int Count; public Test(int count) { Count = count; if (count == 0) { System.Console.WriteLine(""Test..ctor""); } } public static Test operator +(Test x, int y) { return new Test(x.Count + 1); } public static Test operator -(Test x, int y) { return new Test(x.Count + 1); } public static Test operator *(Test x, int y) { return new Test(x.Count + 1); } public static Test operator /(Test x, int y) { return new Test(x.Count + 1); } public static Test operator %(Test x, int y) { return new Test(x.Count + 1); } public static Test operator &(Test x, int y) { return new Test(x.Count + 1); } public static Test operator |(Test x, int y) { return new Test(x.Count + 1); } public static Test operator ^(Test x, int y) { return new Test(x.Count + 1); } public static Test operator <<(Test x, int y) { return new Test(x.Count + 1); } public static Test operator >>(Test x, int y) { return new Test(x.Count + 1); } public static Test operator ++(Test x) { return new Test(x.Count + 1); } public static Test operator --(Test x) { return new Test(x.Count + 1); } public void WhenNotNull() { System.Console.WriteLine(""WhenNotNull""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: @"Test..ctor 15 WhenNotNull -1 "); } [Fact] public void Block_01() { var text = @" { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatement_01() { var text = @" ; System.Console.WriteLine(""Hi!""); ; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void BreakStatement_01() { var text = @"break;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS0139: No enclosing loop out of which to break or continue // break; Diagnostic(ErrorCode.ERR_NoBreakOrCont, "break;").WithLocation(1, 1) ); } [Fact] public void ContinueStatement_01() { var text = @"continue;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS0139: No enclosing loop out of which to break or continue // continue; Diagnostic(ErrorCode.ERR_NoBreakOrCont, "continue;").WithLocation(1, 1) ); } [Fact] public void ThrowStatement_01() { var text = @"throw;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause // throw; Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(1, 1) ); } [Fact] public void ThrowStatement_02() { var text = @"throw null;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp).VerifyIL("<top-level-statements-entry-point>", sequencePoints: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, source: text, expectedIL: @" { // Code size 2 (0x2) .maxstack 1 // sequence point: throw null; IL_0000: ldnull IL_0001: throw } "); } [Fact] public void DoStatement_01() { var text = @" int i = 1; do { i++; } while (i < 4); System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void WhileStatement_01() { var text = @" int i = 1; while (i < 4) { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void ForStatement_01() { var text = @" int i = 1; for (;i < 4;) { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void CheckedStatement_01() { var text = @" int i = 1; i++; checked { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "3").VerifyIL("<top-level-statements-entry-point>", sequencePoints: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, source: text, expectedIL: @" { // Code size 20 (0x14) .maxstack 2 .locals init (int V_0) //i // sequence point: int i = 1; IL_0000: ldc.i4.1 IL_0001: stloc.0 // sequence point: i++; IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: add IL_0005: stloc.0 // sequence point: { IL_0006: nop // sequence point: i++; IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: add.ovf IL_000a: stloc.0 // sequence point: } IL_000b: nop // sequence point: System.Console.WriteLine(i); IL_000c: ldloc.0 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: nop IL_0013: ret } "); } [Fact] public void UncheckedStatement_01() { var text = @" int i = 1; i++; unchecked { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithOverflowChecks(true), parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "3").VerifyIL("<top-level-statements-entry-point>", sequencePoints: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, source: text, expectedIL: @" { // Code size 20 (0x14) .maxstack 2 .locals init (int V_0) //i // sequence point: int i = 1; IL_0000: ldc.i4.1 IL_0001: stloc.0 // sequence point: i++; IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: add.ovf IL_0005: stloc.0 // sequence point: { IL_0006: nop // sequence point: i++; IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: add IL_000a: stloc.0 // sequence point: } IL_000b: nop // sequence point: System.Console.WriteLine(i); IL_000c: ldloc.0 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: nop IL_0013: ret } "); } [Fact] public void UnsafeStatement_01() { var text = @" unsafe { int* p = (int*)0; p++; System.Console.WriteLine((int)p); } "; var comp = CreateCompilation(text, options: TestOptions.UnsafeDebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "4", verify: Verification.Skipped); } [Fact] public void FixedStatement_01() { var text = @" fixed(int *p = &new C().i) {} class C { public int i = 2; } "; var comp = CreateCompilation(text, options: TestOptions.UnsafeDebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (2,1): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed(int *p = &new C().i) {} Diagnostic(ErrorCode.ERR_UnsafeNeeded, "fixed(int *p = &new C().i) {}").WithLocation(2, 1), // (2,7): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed(int *p = &new C().i) {} Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int *").WithLocation(2, 7), // (2,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed(int *p = &new C().i) {} Diagnostic(ErrorCode.ERR_UnsafeNeeded, "&new C().i").WithLocation(2, 16) ); } [Fact] public void LockStatement_01() { var text = @" int i = 1; lock (new object()) { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void IfStatement_01() { var text = @" int i = 1; if (i == 1) { i++; } else { i--; } if (i != 2) { i--; } else { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void SwitchStatement_01() { var text = @" int i = 1; switch (i) { case 1: i++; break; default: i--; break; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void TryStatement_01() { var text = @" try { System.Console.Write(1); throw null; } catch { System.Console.Write(2); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "12"); } [Fact] public void Args_01() { var text = @" #nullable enable System.Console.WriteLine(args.Length == 0 ? 0 : -args[0].Length); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "0").VerifyDiagnostics(); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); AssertEntryPointParameter(entryPoint); } [Fact] public void Args_02() { var text1 = @" using System.Linq; _ = from args in new object[0] select args; "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,10): error CS1931: The range variable 'args' conflicts with a previous declaration of 'args' // _ = from args in new object[0] select args; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "args").WithArguments("args").WithLocation(3, 10) ); } [Fact] public void Args_03() { var text = @" local(); void local() { System.Console.WriteLine(args[0]); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Args_03", args: new[] { "Args_03" }).VerifyDiagnostics(); } [Fact] public void Args_04() { var text = @" System.Action lambda = () => System.Console.WriteLine(args[0]); lambda(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Args_04", args: new[] { "Args_04" }).VerifyDiagnostics(); } [Fact] public void Span_01() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; Span<int> span = default; _ = new { Span = span }; ", options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,11): error CS0828: Cannot assign 'Span<int>' to anonymous type property // _ = new { Span = span }; Diagnostic(ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, "Span = span").WithArguments("System.Span<int>").WithLocation(5, 11) ); } [Fact] public void Span_02() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; Span<int> outer; for (Span<int> inner = stackalloc int[10];; inner = outer) { outer = inner; } ", options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (7,13): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // outer = inner; Diagnostic(ErrorCode.ERR_EscapeLocal, "inner").WithArguments("inner").WithLocation(7, 13) ); } [Fact] [WorkItem(1179569, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1179569")] public void Issue1179569() { var text1 = @"Task v0123456789012345678901234567() { Console.Write(""start v0123456789012345678901234567""); await Task.Delay(2 * 1000); Console.Write(""end v0123456789012345678901234567""); } Task On01234567890123456() { return v0123456789012345678901234567(); } string return Task.WhenAll( Task.WhenAll(this.c01234567890123456789012345678.Select(v01234567 => On01234567890123456(v01234567))), Task.WhenAll(this.c01234567890123456789.Select(v01234567 => v01234567.U0123456789012345678901234()))); "; var oldTree = Parse(text: text1, options: TestOptions.RegularDefault); var text2 = @"Task v0123456789012345678901234567() { Console.Write(""start v0123456789012345678901234567""); await Task.Delay(2 * 1000); Console.Write(""end v0123456789012345678901234567""); } Task On01234567890123456() { return v0123456789012345678901234567(); } string[ return Task.WhenAll( Task.WhenAll(this.c01234567890123456789012345678.Select(v01234567 => On01234567890123456(v01234567))), Task.WhenAll(this.c01234567890123456789.Select(v01234567 => v01234567.U0123456789012345678901234()))); "; var newText = Microsoft.CodeAnalysis.Text.StringText.From(text2, System.Text.Encoding.UTF8); using var lexer = new Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.Lexer(newText, TestOptions.RegularDefault); using var parser = new Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LanguageParser(lexer, (CSharpSyntaxNode)oldTree.GetRoot(), new[] { new Microsoft.CodeAnalysis.Text.TextChangeRange(new Microsoft.CodeAnalysis.Text.TextSpan(282, 0), 1) }); var compilationUnit = (CompilationUnitSyntax)parser.ParseCompilationUnit().CreateRed(); var tree = CSharpSyntaxTree.Create(compilationUnit, TestOptions.RegularDefault, encoding: System.Text.Encoding.UTF8); Assert.Equal(text2, tree.GetText().ToString()); tree.VerifySource(); var fullParseTree = Parse(text: text2, options: TestOptions.RegularDefault); var nodes1 = tree.GetRoot().DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToArray(); var nodes2 = fullParseTree.GetRoot().DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToArray(); Assert.Equal(nodes1.Length, nodes2.Length); for (int i = 0; i < nodes1.Length; i++) { var node1 = nodes1[i]; var node2 = nodes2[i]; Assert.Equal(node1.RawKind, node2.RawKind); Assert.Equal(node1.Span, node2.Span); Assert.Equal(node1.FullSpan, node2.FullSpan); Assert.Equal(node1.ToString(), node2.ToString()); Assert.Equal(node1.ToFullString(), node2.ToFullString()); } } [Fact] public void TopLevelLocalReferencedInClass_IOperation() { var comp = CreateCompilation(@" int i = 1; class C { void M() /*<bind>*/{ _ = i; }/*</bind>*/ } ", options: TestOptions.ReleaseExe); var diagnostics = new[] { // (2,5): warning CS0219: The variable 'i' is assigned but its value is never used // int i = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(2, 5), // (7,13): error CS8801: Cannot use local variable or local function 'i' declared in a top-level statement in this context. // _ = i; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "i").WithArguments("i").WithLocation(7, 13) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = i') Left: IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'i') ", diagnostics); VerifyFlowGraphForTest<BlockSyntax>(comp, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = i') Left: IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'i') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact] public void TopLevelLocalFunctionReferencedInClass_IOperation() { var comp = CreateCompilation(@" _ = """"; static void M1() {} void M2() {} class C { void M() /*<bind>*/{ M1(); M2(); }/*</bind>*/ } ", options: TestOptions.ReleaseExe); var diagnostics = new[] { // (3,13): warning CS8321: The local function 'M1' is declared but never used // static void M1() {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "M1").WithArguments("M1").WithLocation(3, 13), // (4,6): warning CS8321: The local function 'M2' is declared but never used // void M2() {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "M2").WithArguments("M2").WithLocation(4, 6), // (9,9): error CS8801: Cannot use local variable or local function 'M1' declared in a top-level statement in this context. // M1(); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "M1").WithArguments("M1").WithLocation(9, 9), // (10,9): error CS8801: Cannot use local variable or local function 'M2' declared in a top-level statement in this context. // M2(); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "M2").WithArguments("M2").WithLocation(10, 9) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @" IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M1();') Expression: IInvocationOperation (void M1()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M1()') Instance Receiver: null Arguments(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M2();') Expression: IInvocationOperation (void M2()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) ", diagnostics); VerifyFlowGraphForTest<BlockSyntax>(comp, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M1();') Expression: IInvocationOperation (void M1()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M1()') Instance Receiver: null Arguments(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M2();') Expression: IInvocationOperation (void M2()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact] public void EmptyStatements_01() { var text = @";"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8937: At least one top-level statement must be non-empty. // ; Diagnostic(ErrorCode.ERR_SimpleProgramIsEmpty, ";").WithLocation(1, 1) ); } [Fact] public void EmptyStatements_02() { var text = @";; ;; ;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8937: At least one top-level statement must be non-empty. // ;; Diagnostic(ErrorCode.ERR_SimpleProgramIsEmpty, ";").WithLocation(1, 1) ); } [Fact] public void EmptyStatements_03() { var text = @" System.Console.WriteLine(""Hi!""); ;; ; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatements_04() { var text = @" ;; ; System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatements_05() { var text = @" ; System.Console.WriteLine(""Hi!""); ; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatements_06() { var text = @" using System; ; class Program2 { static void Main(String[] args) {} } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8937: At least one top-level statement must be non-empty. // ; Diagnostic(ErrorCode.ERR_SimpleProgramIsEmpty, ";").WithLocation(3, 1), // (7,17): warning CS7022: The entry point of the program is global code; ignoring 'Program2.Main(string[])' entry point. // static void Main(String[] args) {} Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program2.Main(string[])").WithLocation(7, 17) ); } [Fact] public void SpeakableEntryPoint() { var text = @" System.Console.WriteLine(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All)); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Hi!", sourceSymbolValidator: validate, symbolValidator: validate); Assert.Same(entryPoint, comp.GetEntryPoint(default)); Assert.False(entryPoint.CanBeReferencedByName); Assert.True(entryPoint.ContainingType.CanBeReferencedByName); Assert.Equal("<Main>$", entryPoint.Name); Assert.Equal("Program", entryPoint.ContainingType.Name); Assert.Equal(Accessibility.Internal, entryPoint.ContainingType.DeclaredAccessibility); Assert.Equal(Accessibility.Private, entryPoint.DeclaredAccessibility); void validate(ModuleSymbol module) { bool fromSource = module is SourceModuleSymbol; var program = module.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName); Assert.False(program.IsImplicitlyDeclared); if (fromSource) { Assert.Empty(program.GetAttributes().As<CSharpAttributeData>()); } else { Assert.Equal(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(program.GetAttributes().As<CSharpAttributeData>())); } Assert.Empty(program.GetMethod(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName).GetAttributes()); if (fromSource) { Assert.Equal(new[] { "<top-level-statements-entry-point>", "Program..ctor()" }, program.GetMembers().ToTestDisplayStrings()); } else { Assert.Equal(new[] { "void Program.<Main>$(System.String[] args)", "Program..ctor()" }, program.GetMembers().ToTestDisplayStrings()); } } } [Fact] public void SpeakableEntryPoint_ProgramIsPartial() { var text = @" M(); public partial class Program { private static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All)); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Hi!", sourceSymbolValidator: validate, symbolValidator: validate); Assert.Same(entryPoint, comp.GetEntryPoint(default)); Assert.False(entryPoint.CanBeReferencedByName); Assert.True(entryPoint.ContainingType.CanBeReferencedByName); Assert.Equal("<Main>$", entryPoint.Name); Assert.Equal("Program", entryPoint.ContainingType.Name); Assert.Equal(Accessibility.Public, entryPoint.ContainingType.DeclaredAccessibility); Assert.Equal(Accessibility.Private, entryPoint.DeclaredAccessibility); void validate(ModuleSymbol module) { var program = module.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName); Assert.Empty(program.GetAttributes().As<CSharpAttributeData>()); Assert.False(program.IsImplicitlyDeclared); Assert.Empty(program.GetMethod(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName).GetAttributes().As<CSharpAttributeData>()); } } [Fact] public void SpeakableEntryPoint_ProgramIsNotPartial() { var text = @" M(); public class Program { private static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,14): error CS0260: Missing partial modifier on declaration of type 'Program'; another partial declaration of this type exists // public class Program Diagnostic(ErrorCode.ERR_MissingPartial, "Program").WithArguments("Program").WithLocation(4, 14) ); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); Assert.Same(entryPoint, comp.GetEntryPoint(default)); Assert.False(entryPoint.CanBeReferencedByName); Assert.True(entryPoint.ContainingType.CanBeReferencedByName); Assert.Equal("<Main>$", entryPoint.Name); Assert.Equal("Program", entryPoint.ContainingType.Name); Assert.Equal(Accessibility.Public, entryPoint.ContainingType.DeclaredAccessibility); Assert.Equal(Accessibility.Private, entryPoint.DeclaredAccessibility); } [Fact] public void SpeakableEntryPoint_ProgramIsInternal() { var text = @" M(); internal partial class Program { private static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(text); CompileAndVerify(comp, expectedOutput: "Hi!"); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal(Accessibility.Internal, entryPoint.ContainingType.DeclaredAccessibility); Assert.Equal(Accessibility.Private, entryPoint.DeclaredAccessibility); } [Fact] public void SpeakableEntryPoint_ProgramWithoutDeclaredAccessibility() { var text = @" M(); partial class Program { private static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(text); CompileAndVerify(comp, expectedOutput: "Hi!"); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal(Accessibility.Internal, entryPoint.ContainingType.DeclaredAccessibility); Assert.Equal(Accessibility.Private, entryPoint.DeclaredAccessibility); } [Fact] public void SpeakableEntryPoint_ProgramIsStruct() { var text = @" M(); partial struct Program { private static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,1): error CS0261: Partial declarations of 'Program' must be all classes, all record classes, all structs, all record structs, or all interfaces // M(); Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "M").WithArguments("Program").WithLocation(2, 1), // (2,1): error CS0103: The name 'M' does not exist in the current context // M(); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(2, 1) ); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal(Accessibility.Internal, entryPoint.ContainingType.DeclaredAccessibility); Assert.Equal(Accessibility.Private, entryPoint.DeclaredAccessibility); Assert.True(entryPoint.ContainingType.IsReferenceType); } [Fact] public void SpeakableEntryPoint_ProgramIsRecord() { var text = @" M(); partial record Program { private static void M() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,1): error CS0261: Partial declarations of 'Program' must be all classes, all record classes, all structs, all record structs, or all interfaces // M(); Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "M").WithArguments("Program").WithLocation(2, 1), // (2,1): error CS0103: The name 'M' does not exist in the current context // M(); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(2, 1) ); } [Fact] public void SpeakableEntryPoint_ProgramIsInterface() { var text = @" System.Console.Write(42); partial interface Program { } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,1): error CS0261: Partial declarations of 'Program' must be all classes, all record classes, all structs, all record structs, or all interfaces // System.Console.Write(42); Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "System").WithArguments("Program").WithLocation(2, 1) ); } [Fact] public void SpeakableEntryPoint_ProgramCallsMain() { var text = @" M(args); partial class Program { private static void M(string[] args) { Main(); } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (8,9): error CS0103: The name 'Main' does not exist in the current context // Main(); Diagnostic(ErrorCode.ERR_NameNotInContext, "Main").WithArguments("Main").WithLocation(8, 9) ); } [Fact] public void SpeakableEntryPoint_ProgramHasBaseList() { var text = @" new Program().M(); class Base { public void M() { System.Console.Write(42); } } partial class Program : Base { } "; var comp = CreateCompilation(text); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyDiagnostics(); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal(Accessibility.Private, entryPoint.DeclaredAccessibility); Assert.True(entryPoint.IsStatic); Assert.Equal("Base", entryPoint.ContainingType.BaseType().ToTestDisplayString()); Assert.Equal(Accessibility.Internal, entryPoint.ContainingType.DeclaredAccessibility); Assert.False(entryPoint.ContainingType.IsStatic); } [Fact] public void SpeakableEntryPoint_ProgramImplementsInterface() { var text = @" ((Interface)new Program()).M(); interface Interface { void M(); } partial class Program : Interface { void Interface.M() { System.Console.Write(42); } } "; var comp = CreateCompilation(text); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyDiagnostics(); } [Fact] public void SpeakableEntryPoint_ProgramIsAbstractPartial() { var text = @" System.Console.Write(42); abstract partial class Program { } "; var comp = CreateCompilation(text); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyDiagnostics(); } [Fact] public void SpeakableEntryPoint_ProgramIsSealedPartial() { var text = @" System.Console.Write(42); sealed partial class Program { } "; var comp = CreateCompilation(text); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyDiagnostics(); } [Fact] public void SpeakableEntryPoint_ProgramIsStaticPartial() { var text = @" System.Console.Write(42); static partial class Program { } "; var comp = CreateCompilation(text); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyDiagnostics(); } [Fact] public void SpeakableEntryPoint_ProgramIsObsolete() { var text = @" System.Console.Write(42); [System.Obsolete(""error"")] public partial class Program { } public class C { public Program f; } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (11,12): warning CS0618: 'Program' is obsolete: 'error' // public Program f; Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "Program").WithArguments("Program", "error").WithLocation(11, 12) ); } [Fact] public void SpeakableEntryPoint_ProgramIsObsolete_UsedWithinProgram() { var text = @" Program p = new Program(); [System.Obsolete(""error"")] public partial class Program { } "; var comp = CreateCompilation(text); comp.VerifyEmitDiagnostics(); } [Fact] public void SpeakableEntryPoint_ProgramHasMain() { var text = @" System.Console.Write(42); partial class Program { public static void Main(string[] args) { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,24): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main(string[])' entry point. // public static void Main(string[] args) { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main(string[])").WithLocation(6, 24) ); } [Fact] public void SpeakableEntryPoint_ProgramHasMain_DifferentSignature() { var text = @" System.Console.Write(42); partial class Program { public static void Main() { } } "; var comp = CreateCompilation(text); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyDiagnostics( // (6,24): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // public static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(6, 24) ); } [Fact] public void SpeakableEntryPoint_ProgramHasBackingField() { var text = @" System.Console.Write(42); partial class Program { public int Property { get; set; } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All)); CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate); comp.VerifyEmitDiagnostics(); void validate(ModuleSymbol module) { bool fromSource = module is SourceModuleSymbol; var field = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").GetField("<Property>k__BackingField"); Assert.False(field.ContainingType.IsImplicitlyDeclared); var fieldAttributes = GetAttributeNames(field.GetAttributes().As<CSharpAttributeData>()); if (fromSource) { Assert.Empty(fieldAttributes); Assert.Equal(new[] { "<top-level-statements-entry-point>", "System.Int32 Program.<Property>k__BackingField", "System.Int32 Program.Property { get; set; }", "System.Int32 Program.Property.get", "void Program.Property.set", "Program..ctor()" }, field.ContainingType.GetMembers().ToTestDisplayStrings()); } else { Assert.Equal(new[] { "CompilerGeneratedAttribute", "DebuggerBrowsableAttribute" }, fieldAttributes); Assert.Equal(new[] { "System.Int32 Program.<Property>k__BackingField", "void Program.<Main>$(System.String[] args)", "System.Int32 Program.Property.get", "void Program.Property.set", "Program..ctor()", "System.Int32 Program.Property { get; set; }" }, field.ContainingType.GetMembers().ToTestDisplayStrings()); } } } [Fact] public void SpeakableEntryPoint_XmlDoc() { var src = @" System.Console.Write(42); "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("Program"); Assert.Equal("", cMember.GetDocumentationCommentXml()); } [Fact] public void SpeakableEntryPoint_XmlDoc_ProgramIsPartial() { var src = @" System.Console.Write(42); /// <summary>Summary</summary> public partial class Program { } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("Program"); Assert.Equal( @"<member name=""T:Program""> <summary>Summary</summary> </member> ", cMember.GetDocumentationCommentXml()); } [Fact] public void SpeakableEntryPoint_XmlDoc_ProgramIsPartial_NotCommented() { var src = @" System.Console.Write(42); public partial class Program { } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (4,22): warning CS1591: Missing XML comment for publicly visible type or member 'Program' // public partial class Program { } Diagnostic(ErrorCode.WRN_MissingXMLComment, "Program").WithArguments("Program").WithLocation(4, 22) ); var cMember = comp.GetMember<NamedTypeSymbol>("Program"); Assert.Equal("", cMember.GetDocumentationCommentXml()); } [Fact] public void SpeakableEntryPoint_TypeOf() { var src = @" C.M(); public class C { public static void M() { System.Console.Write(typeof(Program)); } } "; var comp = CreateCompilation(src); var verifier = CompileAndVerify(comp, expectedOutput: "Program"); verifier.VerifyDiagnostics(); } [Fact] public void Ordering_InFileScopedNamespace_01() { var src = @" namespace NS; System.Console.Write(42); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,16): error CS0116: A namespace cannot directly contain members such as fields, methods or statements // System.Console.Write(42); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Write").WithLocation(3, 16), // (3,22): error CS1026: ) expected // System.Console.Write(42); Diagnostic(ErrorCode.ERR_CloseParenExpected, "42").WithLocation(3, 22), // (3,22): error CS1022: Type or namespace definition, or end-of-file expected // System.Console.Write(42); Diagnostic(ErrorCode.ERR_EOFExpected, "42").WithLocation(3, 22) ); } [Fact] public void Ordering_InFileScopedNamespace_02() { var src = @" namespace NS; var x = 1; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,1): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // var x = 1; Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(3, 1), // (3,5): error CS0116: A namespace cannot directly contain members such as fields, methods or statements // var x = 1; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x").WithLocation(3, 5) ); } [Fact] public void Ordering_AfterNamespace() { var src = @" namespace NS { } var x = 1; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // var x = 1; Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "var x = 1;").WithLocation(6, 1), // (6,5): warning CS0219: The variable 'x' is assigned but its value is never used // var x = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 5) ); } } }
// 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.Immutable; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.TopLevelStatements)] public class TopLevelStatementsTests : CompilingTestBase { private static CSharpParseOptions DefaultParseOptions => TestOptions.Regular9; private static bool IsNullableAnalysisEnabled(CSharpCompilation compilation) { var type = compilation.GlobalNamespace.GetTypeMember("Program"); var methods = type.GetMembers().OfType<SynthesizedSimpleProgramEntryPointSymbol>(); return methods.Any(m => m.IsNullableAnalysisEnabled()); } [Fact] public void Simple_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.Same(entryPoint, comp.GetEntryPoint(default)); Assert.False(entryPoint.CanBeReferencedByName); Assert.True(entryPoint.ContainingType.CanBeReferencedByName); Assert.Equal("<Main>$", entryPoint.Name); Assert.Equal("Program", entryPoint.ContainingType.Name); } private static void AssertEntryPointParameter(SynthesizedSimpleProgramEntryPointSymbol entryPoint) { Assert.Equal(1, entryPoint.ParameterCount); ParameterSymbol parameter = entryPoint.Parameters.Single(); Assert.Equal("System.String[] args", parameter.ToTestDisplayString(includeNonNullable: true)); Assert.True(parameter.IsImplicitlyDeclared); Assert.Same(entryPoint, parameter.ContainingSymbol); } [Fact] public void Simple_02() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "hello async main"); } [Fact] public void Simple_03() { var text1 = @" System.Console.Write(""1""); "; var text2 = @" // System.Console.Write(""2""); System.Console.WriteLine(); System.Console.WriteLine(); "; var text3 = @" // // System.Console.Write(""3""); System.Console.WriteLine(); System.Console.WriteLine(); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // System.Console.Write("2"); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "System").WithLocation(3, 1) ); comp = CreateCompilation(new[] { text1, text2, text3 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // System.Console.Write("2"); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "System").WithLocation(3, 1), // (4,1): error CS8802: Only one compilation unit can have top-level statements. // System.Console.Write("3"); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "System").WithLocation(4, 1) ); } [Fact] public void Simple_04() { var text = @" Type.M(); static class Type { public static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Simple_05() { var text1 = @" Type.M(); "; var text2 = @" static class Type { public static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Simple_06_01() { var text1 = @" local(); void local() => System.Console.WriteLine(2); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); verifyModel(comp, comp.SyntaxTrees[0]); comp = CreateCompilation(text1, options: TestOptions.DebugExe.WithNullableContextOptions(NullableContextOptions.Enable), parseOptions: DefaultParseOptions); verifyModel(comp, comp.SyntaxTrees[0], nullableEnabled: true); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1, bool nullableEnabled = false) { Assert.Equal(nullableEnabled, IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); verifyModelForGlobalStatements(tree1, model1); var unit1 = (CompilationUnitSyntax)tree1.GetRoot(); var localRef = unit1.DescendantNodes().OfType<IdentifierNameSyntax>().First(); var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Equal("void local()", refSymbol.ToTestDisplayString()); Assert.Contains(refSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(refSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(refSymbol, model1.LookupSymbols(localRef.SpanStart, name: refSymbol.Name).Single()); var operation1 = model1.GetOperation(localRef.Parent); Assert.NotNull(operation1); Assert.IsAssignableFrom<IInvocationOperation>(operation1); Assert.NotNull(ControlFlowGraph.Create((IMethodBodyOperation)((IBlockOperation)operation1.Parent.Parent).Parent)); model1.VerifyOperationTree(unit1, @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'local(); ... iteLine(2);') BlockBody: IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'local(); ... iteLine(2);') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'local();') Expression: IInvocationOperation (void local()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'local()') Instance Receiver: null Arguments(0) ILocalFunctionOperation (Symbol: void local()) (OperationKind.LocalFunction, Type: null) (Syntax: 'void local( ... iteLine(2);') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '=> System.C ... riteLine(2)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'System.Cons ... riteLine(2)') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(2)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '=> System.C ... riteLine(2)') ReturnedValue: null ExpressionBody: null "); var localDecl = unit1.DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Same(declSymbol.ContainingSymbol, model1.GetDeclaredSymbol(unit1)); Assert.Same(declSymbol.ContainingSymbol, model1.GetDeclaredSymbol((SyntaxNode)unit1)); Assert.Same(refSymbol, declSymbol); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); var operation2 = model1.GetOperation(localDecl); Assert.NotNull(operation2); Assert.IsAssignableFrom<ILocalFunctionOperation>(operation2); static void verifyModelForGlobalStatements(SyntaxTree tree1, SemanticModel model1) { var symbolInfo = model1.GetSymbolInfo(tree1.GetRoot()); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var typeInfo = model1.GetTypeInfo(tree1.GetRoot()); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); foreach (var globalStatement in tree1.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>()) { symbolInfo = model1.GetSymbolInfo(globalStatement); Assert.Null(model1.GetOperation(globalStatement)); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); typeInfo = model1.GetTypeInfo(globalStatement); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } } } } [Fact] public void Simple_06_02() { var text1 = @"local();"; var text2 = @"void local() => System.Console.WriteLine(2);"; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8802: Only one compilation unit can have top-level statements. // void local() => System.Console.WriteLine(2); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(1, 1), // (1,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(1, 1), // (1,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(1, 6) ); verifyModel(comp, comp.SyntaxTrees[0], comp.SyntaxTrees[1]); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8802: Only one compilation unit can have top-level statements. // local(); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "local").WithLocation(1, 1), // (1,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(1, 1), // (1,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(1, 6) ); verifyModel(comp, comp.SyntaxTrees[1], comp.SyntaxTrees[0]); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe.WithNullableContextOptions(NullableContextOptions.Enable), parseOptions: DefaultParseOptions); verifyModel(comp, comp.SyntaxTrees[0], comp.SyntaxTrees[1], nullableEnabled: true); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1, SyntaxTree tree2, bool nullableEnabled = false) { Assert.Equal(nullableEnabled, IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); verifyModelForGlobalStatements(tree1, model1); var unit1 = (CompilationUnitSyntax)tree1.GetRoot(); var localRef = unit1.DescendantNodes().OfType<IdentifierNameSyntax>().Single(); var refSymbol = model1.GetSymbolInfo(localRef).Symbol; var refMethod = model1.GetDeclaredSymbol(unit1); Assert.NotNull(refMethod); Assert.Null(refSymbol); var name = localRef.Identifier.ValueText; Assert.DoesNotContain(name, model1.LookupNames(localRef.SpanStart)); Assert.Empty(model1.LookupSymbols(localRef.SpanStart).Where(s => s.Name == name)); Assert.Empty(model1.LookupSymbols(localRef.SpanStart, name: name)); var operation1 = model1.GetOperation(localRef.Parent); Assert.NotNull(operation1); Assert.IsAssignableFrom<IInvalidOperation>(operation1); Assert.NotNull(ControlFlowGraph.Create((IMethodBodyOperation)((IBlockOperation)operation1.Parent.Parent).Parent)); model1.VerifyOperationTree(unit1, @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'local();') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'local();') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'local();') Expression: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'local()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'local') Children(0) ExpressionBody: null "); SyntaxTreeSemanticModel syntaxTreeModel = ((SyntaxTreeSemanticModel)model1); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit1]; var model2 = comp.GetSemanticModel(tree2); verifyModelForGlobalStatements(tree2, model2); var unit2 = (CompilationUnitSyntax)tree2.GetRoot(); var declMethod = model2.GetDeclaredSymbol(unit2); var localDecl = unit2.DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model2.GetDeclaredSymbol(localDecl); Assert.Equal("void local()", declSymbol.ToTestDisplayString()); Assert.Same(declSymbol.ContainingSymbol, declMethod); Assert.NotEqual(refMethod, declMethod); Assert.Contains(declSymbol.Name, model2.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model2.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model2.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); var operation2 = model2.GetOperation(localDecl); Assert.NotNull(operation2); Assert.IsAssignableFrom<ILocalFunctionOperation>(operation2); Assert.NotNull(ControlFlowGraph.Create((IMethodBodyOperation)((IBlockOperation)operation2.Parent).Parent)); var isInvalid = comp.SyntaxTrees[1] == tree2 ? ", IsInvalid" : ""; model2.VerifyOperationTree(unit2, @" IMethodBodyOperation (OperationKind.MethodBody, Type: null" + isInvalid + @") (Syntax: 'void local( ... iteLine(2);') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null" + isInvalid + @", IsImplicit) (Syntax: 'void local( ... iteLine(2);') ILocalFunctionOperation (Symbol: void local()) (OperationKind.LocalFunction, Type: null" + isInvalid + @") (Syntax: 'void local( ... iteLine(2);') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '=> System.C ... riteLine(2)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'System.Cons ... riteLine(2)') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(2)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '=> System.C ... riteLine(2)') ReturnedValue: null ExpressionBody: null "); static void verifyModelForGlobalStatements(SyntaxTree tree1, SemanticModel model1) { var symbolInfo = model1.GetSymbolInfo(tree1.GetRoot()); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var typeInfo = model1.GetTypeInfo(tree1.GetRoot()); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); foreach (var globalStatement in tree1.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>()) { symbolInfo = model1.GetSymbolInfo(globalStatement); Assert.Null(model1.GetOperation(globalStatement)); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); typeInfo = model1.GetTypeInfo(globalStatement); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } } } } [Fact] public void Simple_07() { var text1 = @" var i = 1; local(); "; var text2 = @" void local() => System.Console.WriteLine(i); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(2, 1), // (2,5): warning CS0219: The variable 'i' is assigned but its value is never used // var i = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(2, 5), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,42): error CS0103: The name 'i' does not exist in the current context // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(2, 42), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1) ); verifyModel(comp, comp.SyntaxTrees[0], comp.SyntaxTrees[1]); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var i = 1; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,5): warning CS0219: The variable 'i' is assigned but its value is never used // var i = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(2, 5), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,42): error CS0103: The name 'i' does not exist in the current context // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(2, 42), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1) ); verifyModel(comp, comp.SyntaxTrees[1], comp.SyntaxTrees[0]); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1, SyntaxTree tree2) { Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); Assert.NotNull(model1.GetOperation(tree1.GetRoot())); var operation1 = model1.GetOperation(localDecl); Assert.NotNull(operation1); Assert.IsAssignableFrom<IVariableDeclaratorOperation>(operation1); var localFuncRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local").Single(); Assert.Contains(declSymbol.Name, model1.LookupNames(localFuncRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart, name: declSymbol.Name).Single()); Assert.DoesNotContain(declSymbol, model1.AnalyzeDataFlow(localDecl.Ancestors().OfType<StatementSyntax>().First()).DataFlowsOut); var model2 = comp.GetSemanticModel(tree2); var localRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").Single(); var refSymbol = model2.GetSymbolInfo(localRef).Symbol; Assert.Null(refSymbol); var name = localRef.Identifier.ValueText; Assert.DoesNotContain(name, model2.LookupNames(localRef.SpanStart)); Assert.Empty(model2.LookupSymbols(localRef.SpanStart).Where(s => s.Name == name)); Assert.Empty(model2.LookupSymbols(localRef.SpanStart, name: name)); Assert.NotNull(model2.GetOperation(tree2.GetRoot())); var operation2 = model2.GetOperation(localRef); Assert.NotNull(operation2); Assert.IsAssignableFrom<IInvalidOperation>(operation2); Assert.DoesNotContain(declSymbol, model2.AnalyzeDataFlow(localRef).DataFlowsIn); } } [Fact] public void Simple_08() { var text1 = @" var i = 1; System.Console.Write(i++); System.Console.Write(i); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "12"); var tree1 = comp.SyntaxTrees[0]; Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); var localRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").ToArray(); Assert.Equal(2, localRefs.Length); foreach (var localRef in localRefs) { var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Same(declSymbol, refSymbol); Assert.Contains(declSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localRef.SpanStart, name: declSymbol.Name).Single()); } } [Fact] public void Simple_09() { var text1 = @" var i = 1; local(); void local() => System.Console.WriteLine(i); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1"); verifyModel(comp, comp.SyntaxTrees[0]); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1) { Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); Assert.NotNull(model1.GetOperation(tree1.GetRoot())); var operation1 = model1.GetOperation(localDecl); Assert.NotNull(operation1); Assert.IsAssignableFrom<IVariableDeclaratorOperation>(operation1); var localFuncRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local").Single(); Assert.Contains(declSymbol.Name, model1.LookupNames(localFuncRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart, name: declSymbol.Name).Single()); Assert.Contains(declSymbol, model1.AnalyzeDataFlow(localDecl.Ancestors().OfType<StatementSyntax>().First()).DataFlowsOut); var localRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").Single(); var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Same(declSymbol, refSymbol); Assert.Contains(refSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(refSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(refSymbol, model1.LookupSymbols(localRef.SpanStart, name: refSymbol.Name).Single()); var operation2 = model1.GetOperation(localRef); Assert.NotNull(operation2); Assert.IsAssignableFrom<ILocalReferenceOperation>(operation2); // The following assert fails due to https://github.com/dotnet/roslyn/issues/41853, enable once the issue is fixed. //Assert.Contains(declSymbol, model1.AnalyzeDataFlow(localRef).DataFlowsIn); } } [Fact] public void LanguageVersion_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (1,1): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, @"System.Console.WriteLine(""Hi!"");").WithArguments("top-level statements", "9.0").WithLocation(1, 1) ); } [Fact] public void WithinType_01() { var text = @" class Test { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, parseOptions: DefaultParseOptions); var expected = new[] { // (4,29): error CS1519: Invalid token '(' in class, record, struct, or interface member declaration // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "(").WithArguments("(").WithLocation(4, 29), // (4,30): error CS1031: Type expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_TypeExpected, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS8124: Tuple must contain at least two elements. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_TupleTooFewElements, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS1026: ) expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_CloseParenExpected, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS1519: Invalid token '"Hi!"' in class, record, struct, or interface member declaration // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, @"""Hi!""").WithArguments(@"""Hi!""").WithLocation(4, 30) }; comp.GetDiagnostics(CompilationStage.Parse, includeEarlierStages: false, cancellationToken: default).Verify(expected); comp.VerifyDiagnostics(expected); } [Fact] public void WithinNamespace_01() { var text = @" namespace Test { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, parseOptions: DefaultParseOptions); var expected = new[] { // (4,20): error CS0116: A namespace cannot directly contain members such as fields or methods // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "WriteLine").WithLocation(4, 20), // (4,30): error CS1026: ) expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_CloseParenExpected, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS1022: Type or namespace definition, or end-of-file expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_EOFExpected, @"""Hi!""").WithLocation(4, 30) }; comp.GetDiagnostics(CompilationStage.Parse, includeEarlierStages: false, cancellationToken: default).Verify(expected); comp.VerifyDiagnostics(expected); } [Fact] public void LocalDeclarationStatement_01() { var text = @" string s = ""Hi!""; System.Console.WriteLine(s); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "s").Single(); var local = model.GetDeclaredSymbol(declarator); Assert.Same(local, model.GetSymbolInfo(reference).Symbol); Assert.Equal("System.String s", local.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, local.Kind); Assert.Equal(SymbolKind.Method, local.ContainingSymbol.Kind); Assert.False(local.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, local.ContainingSymbol.ContainingSymbol.Kind); Assert.Equal("Program", local.ContainingSymbol.ContainingSymbol.Name); Assert.False(local.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)local.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); } [Fact] public void LocalDeclarationStatement_02() { var text = @" new string a = ""Hi!""; System.Console.WriteLine(a); public string b = ""Hi!""; System.Console.WriteLine(b); static string c = ""Hi!""; System.Console.WriteLine(c); readonly string d = ""Hi!""; System.Console.WriteLine(d); volatile string e = ""Hi!""; System.Console.WriteLine(e); [System.Obsolete()] string f = ""Hi!""; System.Console.WriteLine(f); [System.Obsolete()] const string g = ""Hi!""; System.Console.WriteLine(g); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,12): error CS0116: A namespace cannot directly contain members such as fields or methods // new string a = "Hi!"; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "a").WithLocation(2, 12), // (2,12): warning CS0109: The member '<invalid-global-code>.a' does not hide an accessible member. The new keyword is not required. // new string a = "Hi!"; Diagnostic(ErrorCode.WRN_NewNotRequired, "a").WithArguments("<invalid-global-code>.a").WithLocation(2, 12), // (3,26): error CS0103: The name 'a' does not exist in the current context // System.Console.WriteLine(a); Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(3, 26), // (4,15): error CS0116: A namespace cannot directly contain members such as fields or methods // public string b = "Hi!"; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(4, 15), // (5,26): error CS0103: The name 'b' does not exist in the current context // System.Console.WriteLine(b); Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(5, 26), // (6,1): error CS0106: The modifier 'static' is not valid for this item // static string c = "Hi!"; Diagnostic(ErrorCode.ERR_BadMemberFlag, "static").WithArguments("static").WithLocation(6, 1), // (8,1): error CS0106: The modifier 'readonly' is not valid for this item // readonly string d = "Hi!"; Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 1), // (10,1): error CS0106: The modifier 'volatile' is not valid for this item // volatile string e = "Hi!"; Diagnostic(ErrorCode.ERR_BadMemberFlag, "volatile").WithArguments("volatile").WithLocation(10, 1), // (12,1): error CS7014: Attributes are not valid in this context. // [System.Obsolete()] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[System.Obsolete()]").WithLocation(12, 1), // (15,1): error CS7014: Attributes are not valid in this context. // [System.Obsolete()] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[System.Obsolete()]").WithLocation(15, 1) ); } [Fact] public void LocalDeclarationStatement_03() { var text = @" string a = ""1""; string a = ""2""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,8): warning CS0219: The variable 'a' is assigned but its value is never used // string a = "1"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(2, 8), // (3,8): error CS0128: A local variable or function named 'a' is already defined in this scope // string a = "2"; Diagnostic(ErrorCode.ERR_LocalDuplicate, "a").WithArguments("a").WithLocation(3, 8), // (3,8): warning CS0219: The variable 'a' is assigned but its value is never used // string a = "2"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(3, 8) ); } [Fact] public void LocalDeclarationStatement_04() { var text = @" using System; using System.Threading.Tasks; var s = await local(); System.Console.WriteLine(s); async Task<string> local() { await Task.Factory.StartNew(() => 5); return ""Hi!""; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalDeclarationStatement_05() { var text = @" const string s = ""Hi!""; System.Console.WriteLine(s); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalDeclarationStatement_06() { var text = @" a.ToString(); string a = ""2""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0841: Cannot use local variable 'a' before it is declared // a.ToString(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "a").WithArguments("a").WithLocation(2, 1) ); } [Fact] public void LocalDeclarationStatement_07() { var text1 = @" string x = ""1""; System.Console.Write(x); "; var text2 = @" int x = 1; System.Console.Write(x); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // int x = 1; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "int").WithLocation(2, 1) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single()); Assert.Equal("System.String x", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single()).Symbol); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var symbol2 = model2.GetDeclaredSymbol(tree2.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single()); Assert.Equal("System.Int32 x", symbol2.ToTestDisplayString()); Assert.Same(symbol2, model2.GetSymbolInfo(tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single()).Symbol); } [Fact] public void LocalDeclarationStatement_08() { var text = @" int a = 0; int b = 0; int c = -100; ref int d = ref c; d = 300; d = ref local(true, ref a, ref b); d = 100; d = ref local(false, ref a, ref b); d = 200; System.Console.Write(a); System.Console.Write(' '); System.Console.Write(b); System.Console.Write(' '); System.Console.Write(c); ref int local(bool flag, ref int a, ref int b) { return ref flag ? ref a : ref b; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "100 200 300", verify: Verification.Skipped); } [Fact] public void LocalDeclarationStatement_09() { var text = @" using var a = new MyDisposable(); System.Console.Write(1); class MyDisposable : System.IDisposable { public void Dispose() { System.Console.Write(2); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "12", verify: Verification.Skipped); } [Fact] public void LocalDeclarationStatement_10() { string source = @" await using var x = new C(); System.Console.Write(""body ""); class C : System.IAsyncDisposable, System.IDisposable { public System.Threading.Tasks.ValueTask DisposeAsync() { System.Console.Write(""DisposeAsync""); return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask); } public void Dispose() { System.Console.Write(""IGNORED""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body DisposeAsync"); } [Fact] public void LocalDeclarationStatement_11() { var text1 = @" string x = ""1""; System.Console.Write(x); int x = 1; System.Console.Write(x); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,5): error CS0128: A local variable or function named 'x' is already defined in this scope // int x = 1; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(4, 5), // (4,5): warning CS0219: The variable 'x' is assigned but its value is never used // int x = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(4, 5) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First()); Assert.Equal("System.String x", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").First()).Symbol); var symbol2 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Skip(1).Single()); Assert.Equal("System.Int32 x", symbol2.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Skip(1).Single()).Symbol); } [Fact] public void LocalDeclarationStatement_12() { var text = @" (int x, int y) = (1, 2); System.Console.WriteLine(x+y); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void LocalDeclarationStatement_13() { var text = @" var (x, y) = (1, 2); System.Console.WriteLine(x+y); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void LocalDeclarationStatement_14() { var text1 = @" string args = ""1""; System.Console.Write(args); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,8): error CS0136: A local or parameter named 'args' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string args = "1"; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "args").WithArguments("args").WithLocation(2, 8) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First()); Assert.Equal("System.String args", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").Single()).Symbol); } [Fact] public void LocalDeclarationStatement_15() { var text1 = @" using System.Linq; string x = null; _ = from x in new object[0] select x; System.Console.Write(x); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,10): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // _ = from x in new object[0] select x; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(4, 10) ); } [Fact] public void LocalDeclarationStatement_16() { var text = @" System.Console.WriteLine(); string await = ""Hi!""; System.Console.WriteLine(await); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,8): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // string await = "Hi!"; Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(3, 8), // (3,8): warning CS0219: The variable 'await' is assigned but its value is never used // string await = "Hi!"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "await").WithArguments("await").WithLocation(3, 8), // (4,31): error CS1525: Invalid expression term ')' // System.Console.WriteLine(await); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(4, 31) ); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnType.IsErrorType()); AssertEntryPointParameter(entryPoint); } [Fact] public void LocalDeclarationStatement_17() { var text = @" string async = ""Hi!""; System.Console.WriteLine(async); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalDeclarationStatement_18() { var text = @" int c = -100; ref int d = ref c; System.Console.Write(d); await System.Threading.Tasks.Task.Yield(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,9): error CS8177: Async methods cannot have by-reference locals // ref int d = ref c; Diagnostic(ErrorCode.ERR_BadAsyncLocalType, "d").WithLocation(3, 9) ); } [Fact] public void UsingStatement_01() { string source = @" await using (var x = new C()) { System.Console.Write(""body ""); } class C : System.IAsyncDisposable, System.IDisposable { public System.Threading.Tasks.ValueTask DisposeAsync() { System.Console.Write(""DisposeAsync""); return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask); } public void Dispose() { System.Console.Write(""IGNORED""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body DisposeAsync"); } [Fact] public void UsingStatement_02() { string source = @" await using (new C()) { System.Console.Write(""body ""); } class C : System.IAsyncDisposable, System.IDisposable { public System.Threading.Tasks.ValueTask DisposeAsync() { System.Console.Write(""DisposeAsync""); return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask); } public void Dispose() { System.Console.Write(""IGNORED""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body DisposeAsync"); } [Fact] public void UsingStatement_03() { string source = @" using (new C()) { System.Console.Write(""body ""); } class C : System.IDisposable { public void Dispose() { System.Console.Write(""Dispose""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body Dispose"); } [Fact] public void ForeachStatement_01() { string source = @" using System.Threading.Tasks; await foreach (var i in new C()) { } System.Console.Write(""Done""); class C { public Enumerator GetAsyncEnumerator() { return new Enumerator(); } public sealed class Enumerator { public async Task<bool> MoveNextAsync() { System.Console.Write(""MoveNextAsync ""); await Task.Yield(); return false; } public int Current { get => throw null; } public async Task DisposeAsync() { System.Console.Write(""DisposeAsync ""); await Task.Yield(); } } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] public void ForeachStatement_02() { var text = @" int i = 0; foreach (var j in new [] {2, 3}) { i += j; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] public void ForeachStatement_03() { var text = @" int i = 0; foreach (var (j, k) in new [] {(2,200), (3,300)}) { i += j; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] public void LocalUsedBeforeDeclaration_01() { var text1 = @" const string x = y; System.Console.Write(x); "; var text2 = @" const string y = x; System.Console.Write(y); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // const string y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "const").WithLocation(2, 1), // (2,18): error CS0103: The name 'y' does not exist in the current context // const string x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 18), // (2,18): error CS0103: The name 'x' does not exist in the current context // const string y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 18) ); comp = CreateCompilation(new[] { "System.Console.WriteLine();", text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // const string x = y; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "const").WithLocation(2, 1), // (2,1): error CS8802: Only one compilation unit can have top-level statements. // const string y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "const").WithLocation(2, 1), // (2,18): error CS0103: The name 'y' does not exist in the current context // const string x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 18), // (2,18): error CS0103: The name 'x' does not exist in the current context // const string y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 18) ); } [Fact] public void LocalUsedBeforeDeclaration_02() { var text1 = @" var x = y; System.Console.Write(x); "; var text2 = @" var y = x; System.Console.Write(y); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,9): error CS0103: The name 'y' does not exist in the current context // var x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 9), // (2,9): error CS0103: The name 'x' does not exist in the current context // var y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 9) ); comp = CreateCompilation(new[] { "System.Console.WriteLine();", text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var x = y; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,9): error CS0103: The name 'y' does not exist in the current context // var x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 9), // (2,9): error CS0103: The name 'x' does not exist in the current context // var y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 9) ); } [Fact] public void LocalUsedBeforeDeclaration_03() { var text1 = @" string x = ""x""; System.Console.Write(x); "; var text2 = @" class C1 { void Test() { System.Console.Write(x); } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,30): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // System.Console.Write(x); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(6, 30) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); var symbol2 = model2.GetSymbolInfo(nameRef).Symbol; Assert.Equal("System.String x", symbol2.ToTestDisplayString()); Assert.Equal("System.String", model2.GetTypeInfo(nameRef).Type.ToTestDisplayString()); Assert.Null(model2.GetOperation(tree2.GetRoot())); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,30): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // System.Console.Write(x); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(6, 30) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel tree2 = comp.SyntaxTrees[0]; model2 = comp.GetSemanticModel(tree2); nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); symbol2 = model2.GetSymbolInfo(nameRef).Symbol; Assert.Equal("System.String x", symbol2.ToTestDisplayString()); Assert.Equal("System.String", model2.GetTypeInfo(nameRef).Type.ToTestDisplayString()); Assert.Null(model2.GetOperation(tree2.GetRoot())); } [Fact] public void LocalUsedBeforeDeclaration_04() { var text1 = @" string x = ""x""; local(); "; var text2 = @" void local() { System.Console.Write(x); } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // void local() Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(2, 1), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,8): warning CS0219: The variable 'x' is assigned but its value is never used // string x = "x"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(2, 8), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1), // (4,26): error CS0103: The name 'x' does not exist in the current context // System.Console.Write(x); Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(4, 26) ); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // string x = "x"; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "string").WithLocation(2, 1), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,8): warning CS0219: The variable 'x' is assigned but its value is never used // string x = "x"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(2, 8), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1), // (4,26): error CS0103: The name 'x' does not exist in the current context // System.Console.Write(x); Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(4, 26) ); } [Fact] public void FlowAnalysis_01() { var text = @" #nullable enable string a = ""1""; string? b; System.Console.WriteLine(b); string? c = null; c.ToString(); d: System.Console.WriteLine(); string e() => ""1""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,8): warning CS0219: The variable 'a' is assigned but its value is never used // string a = "1"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(3, 8), // (5,26): error CS0165: Use of unassigned local variable 'b' // System.Console.WriteLine(b); Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(5, 26), // (7,1): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(7, 1), // (8,1): warning CS0164: This label has not been referenced // d: System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(8, 1), // (9,8): warning CS8321: The local function 'e' is declared but never used // string e() => "1"; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "e").WithArguments("e").WithLocation(9, 8) ); var tree = comp.SyntaxTrees.Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "c").Single(); var model1 = comp.GetSemanticModel(tree); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model1.GetTypeInfo(reference).Nullability.FlowState); var model2 = comp.GetSemanticModel(tree); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model1.GetTypeInfo(reference).Nullability.FlowState); } [Fact] public void FlowAnalysis_02() { var text = @" System.Console.WriteLine(); if (args.Length == 0) { return 10; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0161: '<top-level-statements-entry-point>': not all code paths return a value // System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_ReturnExpected, @"System.Console.WriteLine(); if (args.Length == 0) { return 10; } ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1) ); } [Fact] public void NullableRewrite_01() { var text1 = @" void local1() { System.Console.WriteLine(""local1 - "" + s); } "; var text2 = @" using System; string s = ""Hello world!""; foreach (var c in s) { Console.Write(c); } goto label1; label1: Console.WriteLine(); local1(); local2(); "; var text3 = @" void local2() { System.Console.WriteLine(""local2 - "" + s); } "; var comp = CreateCompilation(new[] { text1, text2, text3 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var tree = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree); foreach (var id in tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>()) { _ = model1.GetTypeInfo(id).Nullability; } var model2 = comp.GetSemanticModel(tree); foreach (var id in tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>()) { _ = model2.GetTypeInfo(id).Nullability; } } [Fact] public void Scope_01() { var text = @" using alias1 = Test; string Test = ""1""; System.Console.WriteLine(Test); class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 5 Test.ToString(); // 6 Test.EndsWith(null); // 7 _ = nameof(Test); // 8 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20), // (34,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(34, 38), // (35,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(35, 13), // (36,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 13), // (37,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 24) ); var getHashCode = ((Compilation)comp).GetMember("System.Object." + nameof(GetHashCode)); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); Assert.Contains(getHashCode.Name, names); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains(getHashCode, symbols); Assert.Same(getHashCode, model1.LookupSymbols(localDecl.SpanStart, name: getHashCode.Name).Single()); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var nameRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[1]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); names = model.LookupNames(nameRef.SpanStart); Assert.DoesNotContain(getHashCode.Name, names); Assert.Contains("Test", names); symbols = model.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(getHashCode, symbols); Assert.Empty(model.LookupSymbols(nameRef.SpanStart, name: getHashCode.Name)); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[2]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[4]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[8]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[9]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[11]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model, IdentifierNameSyntax nameRef) { var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_02() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using alias1 = Test; class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 5 Test.ToString(); // 6 Test.EndsWith(null); // 7 _ = nameof(Test); // 8 } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20), // (31,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(31, 38), // (32,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(32, 13), // (33,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(33, 13), // (34,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(34, 24) ); var getHashCode = ((Compilation)comp).GetMember("System.Object." + nameof(GetHashCode)); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); Assert.Contains(getHashCode.Name, names); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains(getHashCode, symbols); Assert.Same(getHashCode, model1.LookupSymbols(localDecl.SpanStart, name: getHashCode.Name).Single()); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); Assert.Null(model2.GetDeclaredSymbol((CompilationUnitSyntax)tree2.GetRoot())); var nameRefs = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); names = model2.LookupNames(nameRef.SpanStart); Assert.DoesNotContain(getHashCode.Name, names); Assert.Contains("Test", names); symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(getHashCode, symbols); Assert.Empty(model2.LookupSymbols(nameRef.SpanStart, name: getHashCode.Name)); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[1]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model2.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[3]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[7]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[8]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model2.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[10]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_03() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" class Test {} class Derived : Test { void M() { int Test = 0; System.Console.WriteLine(Test++); } } namespace N1 { class Derived : Test { void M() { int Test = 1; System.Console.WriteLine(Test++); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); Assert.Throws<System.ArgumentException>(() => CreateCompilation(new[] { Parse(text1, filename: "text1", DefaultParseOptions), Parse(text1, filename: "text2", TestOptions.Regular6) }, options: TestOptions.DebugExe)); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (2,1): error CS8107: Feature 'top-level statements' is not available in C# 7.0. Please use language version 9.0 or greater. // string Test = "1"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, @"string Test = ""1"";").WithArguments("top-level statements", "9.0").WithLocation(2, 1) ); } [Fact] public void Scope_04() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20), // (36,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 38), // (37,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 13), // (38,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 13), // (39,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(39, 45), // (41,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(41, 24) ); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test()", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); var nameRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); names = model1.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model1.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[2]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[4]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[9]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[10]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[12]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_05() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using alias1 = Test; class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20), // (33,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(33, 38), // (34,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(34, 13), // (35,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(35, 13), // (36,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 45), // (38,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 24) ); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test()", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var nameRefs = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[1]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[3]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[8]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[9]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[11]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_06() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" class Test {} class Derived : Test { void M() { int Test() => 1; int x = Test() + 1; System.Console.WriteLine(x); } } namespace N1 { class Derived : Test { void M() { int Test() => 1; int x = Test() + 1; System.Console.WriteLine(x); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (2,1): error CS8107: Feature 'top-level statements' is not available in C# 7.0. Please use language version 9.0 or greater. // string Test() => "1"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, @"string Test() => ""1"";").WithArguments("top-level statements", "9.0").WithLocation(2, 1) ); } [Fact] public void Scope_07() { var text = @" using alias1 = Test; goto Test; Test: System.Console.WriteLine(""1""); class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); goto Test; // 1 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); goto Test; // 2 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (15,14): error CS0159: No such label 'Test' within the scope of the goto statement // goto Test; // 1 Diagnostic(ErrorCode.ERR_LabelNotFound, "Test").WithArguments("Test").WithLocation(15, 14), // (30,18): error CS0159: No such label 'Test' within the scope of the goto statement // goto Test; // 2 Diagnostic(ErrorCode.ERR_LabelNotFound, "Test").WithArguments("Test").WithLocation(30, 18) ); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var labelDecl = tree1.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(labelDecl); Assert.Equal("Test", declSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Label, declSymbol.Kind); var names = model1.LookupNames(labelDecl.SpanStart); var symbols = model1.LookupSymbols(labelDecl.SpanStart); Assert.Contains("Test", names); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(labelDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(labelDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(labelDecl.SpanStart, name: "Test").Single()); Assert.Same(declSymbol, model1.LookupLabels(labelDecl.SpanStart).Single()); Assert.Same(declSymbol, model1.LookupLabels(labelDecl.SpanStart, name: "Test").Single()); var nameRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); names = model1.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model1.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); Assert.Empty(model1.LookupLabels(nameRef.SpanStart)); Assert.Empty(model1.LookupLabels(nameRef.SpanStart, name: "Test")); nameRef = nameRefs[1]; Assert.Equal("goto Test;", nameRef.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); names = model1.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model1.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); Assert.Same(declSymbol, model1.LookupLabels(nameRef.SpanStart).Single()); Assert.Same(declSymbol, model1.LookupLabels(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[2]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[4]; Assert.Equal("goto Test;", nameRef.Parent.ToString()); Assert.Null(model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[5]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[6]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[8]; Assert.Null(model1.GetSymbolInfo(nameRef).Symbol); Assert.Equal("goto Test;", nameRef.Parent.ToString()); verifyModel(model1, nameRef); void verifyModel(SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); Assert.Empty(model2.LookupLabels(nameRef.SpanStart)); Assert.Empty(model2.LookupLabels(nameRef.SpanStart, name: "Test")); } } [Fact] public void Scope_08() { var text = @" goto Test; Test: System.Console.WriteLine(""1""); class Test {} class Derived : Test { void M() { goto Test; Test: System.Console.WriteLine(); } } namespace N1 { class Derived : Test { void M() { goto Test; Test: System.Console.WriteLine(); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); } [Fact] public void Scope_09() { var text = @" string Test = ""1""; System.Console.WriteLine(Test); new void M() { int Test = 0; System.Console.WriteLine(Test++); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,10): error CS0116: A namespace cannot directly contain members such as fields or methods // new void M() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "M").WithLocation(5, 10), // (5,10): warning CS0109: The member '<invalid-global-code>.M()' does not hide an accessible member. The new keyword is not required. // new void M() Diagnostic(ErrorCode.WRN_NewNotRequired, "M").WithArguments("<invalid-global-code>.M()").WithLocation(5, 10) ); } [Fact] public void Scope_10() { var text = @" string Test = ""1""; System.Console.WriteLine(Test); new int F = C1.GetInt(out var Test); class C1 { public static int GetInt(out int v) { v = 1; return v; } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,9): error CS0116: A namespace cannot directly contain members such as fields or methods // new int F = C1.GetInt(out var Test); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "F").WithLocation(5, 9), // (5,9): warning CS0109: The member '<invalid-global-code>.F' does not hide an accessible member. The new keyword is not required. // new int F = C1.GetInt(out var Test); Diagnostic(ErrorCode.WRN_NewNotRequired, "F").WithArguments("<invalid-global-code>.F").WithLocation(5, 9) ); } [Fact] public void Scope_11() { var text = @" goto Test; Test: System.Console.WriteLine(); new void M() { goto Test; Test: System.Console.WriteLine(); }"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,10): error CS0116: A namespace cannot directly contain members such as fields or methods // new void M() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "M").WithLocation(5, 10), // (5,10): warning CS0109: The member '<invalid-global-code>.M()' does not hide an accessible member. The new keyword is not required. // new void M() Diagnostic(ErrorCode.WRN_NewNotRequired, "M").WithArguments("<invalid-global-code>.M()").WithLocation(5, 10) ); } [Fact] public void Scope_12() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} struct Derived { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; struct Derived { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20), // (36,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 38), // (37,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 13), // (38,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 13), // (39,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(39, 45), // (41,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(41, 24) ); } [Fact] public void Scope_13() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} interface Derived { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; interface Derived { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20), // (36,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 38), // (37,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 13), // (38,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 13), // (39,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(39, 45), // (41,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(41, 24) ); } [Fact] public void Scope_14() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} delegate Test D(alias1 x); namespace N1 { using alias2 = Test; delegate Test D(alias2 x); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); } [Fact] public void Scope_15() { var text = @" const int Test = 1; System.Console.WriteLine(Test); class Test {} enum E1 { T = Test, } namespace N1 { enum E1 { T = Test, } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (9,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // T = Test, Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(9, 9), // (16,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // T = Test, Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 13) ); } [Fact] public void Scope_16() { var text1 = @" using alias1 = System.String; alias1 x = ""1""; alias2 y = ""1""; System.Console.WriteLine(x); System.Console.WriteLine(y); local(); "; var text2 = @" using alias2 = System.String; void local() { alias1 a = ""2""; alias2 b = ""2""; System.Console.WriteLine(a); System.Console.WriteLine(b); } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // void local() Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(3, 1), // (3,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(3, 6), // (4,1): error CS0246: The type or namespace name 'alias2' could not be found (are you missing a using directive or an assembly reference?) // alias2 y = "1"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias2").WithArguments("alias2").WithLocation(4, 1), // (5,5): error CS0246: The type or namespace name 'alias1' could not be found (are you missing a using directive or an assembly reference?) // alias1 a = "2"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias1").WithArguments("alias1").WithLocation(5, 5), // (7,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(7, 1) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var nameRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias1" && !id.Parent.IsKind(SyntaxKind.NameEquals)).Single(); Assert.NotEmpty(model1.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias1")); Assert.Empty(model1.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias2")); nameRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias2").Single(); model1.GetDiagnostics(nameRef.Ancestors().OfType<StatementSyntax>().First().Span).Verify( // (4,1): error CS0246: The type or namespace name 'alias2' could not be found (are you missing a using directive or an assembly reference?) // alias2 y = "1"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias2").WithArguments("alias2").WithLocation(4, 1) ); model1.GetDiagnostics().Verify( // (4,1): error CS0246: The type or namespace name 'alias2' could not be found (are you missing a using directive or an assembly reference?) // alias2 y = "1"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias2").WithArguments("alias2").WithLocation(4, 1), // (7,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(7, 1) ); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias2" && !id.Parent.IsKind(SyntaxKind.NameEquals)).Single(); Assert.Empty(model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias1")); Assert.NotEmpty(model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias2")); nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias1").Single(); model2.GetDiagnostics(nameRef.Ancestors().OfType<StatementSyntax>().First().Span).Verify( // (5,5): error CS0246: The type or namespace name 'alias1' could not be found (are you missing a using directive or an assembly reference?) // alias1 a = "2"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias1").WithArguments("alias1").WithLocation(5, 5) ); model2.GetDiagnostics().Verify( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // void local() Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(3, 1), // (3,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(3, 6), // (5,5): error CS0246: The type or namespace name 'alias1' could not be found (are you missing a using directive or an assembly reference?) // alias1 a = "2"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias1").WithArguments("alias1").WithLocation(5, 5) ); } [Fact] public void Scope_17() { var text = @" using alias1 = N2.Test; using N2; string Test = ""1""; System.Console.WriteLine(Test); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20) ); } [Fact] public void Scope_18() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using alias1 = N2.Test; using N2; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20) ); } [Fact] public void Scope_19() { var text = @" using alias1 = N2.Test; using N2; string Test() => ""1""; System.Console.WriteLine(Test()); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20) ); } [Fact] public void Scope_20() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using alias1 = N2.Test; using N2; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_21() { var text = @" using Test = N2.Test; string Test = ""1""; System.Console.WriteLine(Test); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20) ); } [Fact] public void Scope_22() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using Test = N2.Test; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20) ); } [Fact] public void Scope_23() { var text = @" using Test = N2.Test; string Test() => ""1""; System.Console.WriteLine(Test()); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20) ); } [Fact] public void Scope_24() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using Test = N2.Test; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_25() { var text = @" using alias1 = N2.Test; using static N2; string Test = ""1""; System.Console.WriteLine(Test); class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20) ); } [Fact] public void Scope_26() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using alias1 = N2.Test; using static N2; class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20) ); } [Fact] public void Scope_27() { var text = @" using alias1 = N2.Test; using static N2; string Test() => ""1""; System.Console.WriteLine(Test()); class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20) ); } [Fact] public void Scope_28() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using alias1 = N2.Test; using static N2; class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_29() { var text = @" using static N2; string Test() => ""1""; System.Console.WriteLine(Test()); class N2 { public static string Test() => null; } class Derived { void M() { System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using static N2; class Derived { void M() { System.Console.WriteLine(Test()); Test().ToString(); Test().EndsWith(null); var d = new System.Func<string>(Test); d(); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using static N2; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N2;").WithLocation(2, 1), // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_30() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using static N2; class N2 { public static string Test() => null; } class Derived { void M() { System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using static N2; class Derived { void M() { System.Console.WriteLine(Test()); Test().ToString(); Test().EndsWith(null); var d = new System.Func<string>(Test); d(); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using static N2; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N2;").WithLocation(2, 1), // (10,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(10, 34), // (11,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(11, 9), // (12,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(12, 9), // (13,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 33), // (15,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 20) ); } [Fact] public void Scope_31() { var text = @" using alias1 = args; System.Console.WriteLine(args); class args {} class Derived : args { void M() { args x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 1 args.ToString(); // 2 args[0].EndsWith(null); // 3 _ = nameof(args); } } namespace N1 { using alias2 = args; class Derived : args { void M() { args x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 4 args.ToString(); // 5 args[0].EndsWith(null); // 6 _ = nameof(args); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (15,34): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 1 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(15, 34), // (16,9): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 2 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(16, 9), // (17,9): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(17, 9), // (33,38): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 4 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(33, 38), // (34,13): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 5 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(34, 13), // (35,13): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 6 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(35, 13) ); var testType = ((Compilation)comp).GetTypeByMetadataName("args"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nameRefs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); nameRef = nameRefs[1]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); var parameter = model.GetSymbolInfo(nameRef).Symbol; Assert.Equal("System.String[] args", parameter.ToTestDisplayString()); Assert.Equal("<top-level-statements-entry-point>", parameter.ContainingSymbol.ToTestDisplayString()); names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); symbols = model.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(parameter, symbols); Assert.Same(parameter, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(parameter, symbols); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "args").Single()); nameRef = nameRefs[2]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[4]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[8]; Assert.Equal("using alias2 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[9]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[11]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model, IdentifierNameSyntax nameRef) { var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "args").Single()); } } [Fact] public void Scope_32() { var text1 = @" System.Console.WriteLine(args); "; var text2 = @" using alias1 = args; class args {} class Derived : args { void M() { args x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 1 args.ToString(); // 2 args[0].EndsWith(null); // 3 _ = nameof(args); } } namespace N1 { using alias2 = args; class Derived : args { void M() { args x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 4 args.ToString(); // 5 args[0].EndsWith(null); // 6 _ = nameof(args); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 1 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(13, 34), // (14,9): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 2 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(14, 9), // (15,9): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(15, 9), // (31,38): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 4 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(31, 38), // (32,13): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 5 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(32, 13), // (33,13): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 6 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(33, 13) ); var testType = ((Compilation)comp).GetTypeByMetadataName("args"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees[1]; var model = comp.GetSemanticModel(tree); var nameRefs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); nameRef = nameRefs[1]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[3]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[7]; Assert.Equal("using alias2 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[8]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[10]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); void verifyModel(SemanticModel model, IdentifierNameSyntax nameRef) { var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "args").Single()); } } [Fact] public void Scope_33() { var text = @" System.Console.WriteLine(args); class Test { void M() { System.Console.WriteLine(args); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,34): error CS0103: The name 'args' does not exist in the current context // System.Console.WriteLine(args); Diagnostic(ErrorCode.ERR_NameNotInContext, "args").WithArguments("args").WithLocation(8, 34) ); } [Fact] public void Scope_34() { var text1 = @" System.Console.WriteLine(args); "; var text2 = @" class Test { void M() { System.Console.WriteLine(args); } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,34): error CS0103: The name 'args' does not exist in the current context // System.Console.WriteLine(args); Diagnostic(ErrorCode.ERR_NameNotInContext, "args").WithArguments("args").WithLocation(6, 34) ); } [Fact] public void LocalFunctionStatement_01() { var text = @" local(); void local() { System.Console.WriteLine(15); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "15"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local").Single(); var local = model.GetDeclaredSymbol(declarator); Assert.Same(local, model.GetSymbolInfo(reference).Symbol); Assert.Equal("void local()", local.ToTestDisplayString()); Assert.Equal(MethodKind.LocalFunction, ((IMethodSymbol)local).MethodKind); Assert.Equal(SymbolKind.Method, local.ContainingSymbol.Kind); Assert.False(local.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, local.ContainingSymbol.ContainingSymbol.Kind); Assert.False(local.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)local.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); VerifyFlowGraph(comp, tree.GetRoot(), @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local()] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'local();') Expression: IInvocationOperation (void local()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'local()') Instance Receiver: null Arguments(0) Next (Regular) Block[B2] Leaving: {R1} { void local() Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... teLine(15);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... iteLine(15)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '15') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 15) (Syntax: '15') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2#0R1] Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact] public void LocalFunctionStatement_02() { var text = @" local(); void local() => System.Console.WriteLine(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalFunctionStatement_03() { var text = @" local(); void I1.local() { System.Console.WriteLine(""Hi!""); } interface I1 { void local(); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 1), // (4,6): error CS0540: '<invalid-global-code>.I1.local()': containing type does not implement interface 'I1' // void I1.local() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("<invalid-global-code>.I1.local()", "I1").WithLocation(4, 6), // (4,9): error CS0116: A namespace cannot directly contain members such as fields or methods // void I1.local() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 9) ); } [Fact] public void LocalFunctionStatement_04() { var text = @" new void localA() => System.Console.WriteLine(); localA(); public void localB() => System.Console.WriteLine(); localB(); virtual void localC() => System.Console.WriteLine(); localC(); sealed void localD() => System.Console.WriteLine(); localD(); override void localE() => System.Console.WriteLine(); localE(); abstract void localF() => System.Console.WriteLine(); localF(); partial void localG() => System.Console.WriteLine(); localG(); extern void localH() => System.Console.WriteLine(); localH(); [System.Obsolete()] void localI() => System.Console.WriteLine(); localI(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,10): error CS0116: A namespace cannot directly contain members such as fields or methods // new void localA() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localA").WithLocation(2, 10), // (2,10): warning CS0109: The member '<invalid-global-code>.localA()' does not hide an accessible member. The new keyword is not required. // new void localA() => System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_NewNotRequired, "localA").WithArguments("<invalid-global-code>.localA()").WithLocation(2, 10), // (3,1): error CS0103: The name 'localA' does not exist in the current context // localA(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localA").WithArguments("localA").WithLocation(3, 1), // (4,1): error CS0106: The modifier 'public' is not valid for this item // public void localB() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(4, 1), // (6,14): error CS0116: A namespace cannot directly contain members such as fields or methods // virtual void localC() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localC").WithLocation(6, 14), // (6,14): error CS0621: '<invalid-global-code>.localC()': virtual or abstract members cannot be private // virtual void localC() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "localC").WithArguments("<invalid-global-code>.localC()").WithLocation(6, 14), // (7,1): error CS0103: The name 'localC' does not exist in the current context // localC(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localC").WithArguments("localC").WithLocation(7, 1), // (8,13): error CS0116: A namespace cannot directly contain members such as fields or methods // sealed void localD() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localD").WithLocation(8, 13), // (8,13): error CS0238: '<invalid-global-code>.localD()' cannot be sealed because it is not an override // sealed void localD() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_SealedNonOverride, "localD").WithArguments("<invalid-global-code>.localD()").WithLocation(8, 13), // (9,1): error CS0103: The name 'localD' does not exist in the current context // localD(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localD").WithArguments("localD").WithLocation(9, 1), // (10,15): error CS0116: A namespace cannot directly contain members such as fields or methods // override void localE() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localE").WithLocation(10, 15), // (10,15): error CS0621: '<invalid-global-code>.localE()': virtual or abstract members cannot be private // override void localE() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "localE").WithArguments("<invalid-global-code>.localE()").WithLocation(10, 15), // (10,15): error CS0115: '<invalid-global-code>.localE()': no suitable method found to override // override void localE() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "localE").WithArguments("<invalid-global-code>.localE()").WithLocation(10, 15), // (11,1): error CS0103: The name 'localE' does not exist in the current context // localE(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localE").WithArguments("localE").WithLocation(11, 1), // (12,15): error CS0116: A namespace cannot directly contain members such as fields or methods // abstract void localF() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localF").WithLocation(12, 15), // (12,15): error CS0500: '<invalid-global-code>.localF()' cannot declare a body because it is marked abstract // abstract void localF() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_AbstractHasBody, "localF").WithArguments("<invalid-global-code>.localF()").WithLocation(12, 15), // (12,15): error CS0621: '<invalid-global-code>.localF()': virtual or abstract members cannot be private // abstract void localF() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "localF").WithArguments("<invalid-global-code>.localF()").WithLocation(12, 15), // (13,1): error CS0103: The name 'localF' does not exist in the current context // localF(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localF").WithArguments("localF").WithLocation(13, 1), // (14,14): error CS0116: A namespace cannot directly contain members such as fields or methods // partial void localG() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localG").WithLocation(14, 14), // (14,14): error CS0759: No defining declaration found for implementing declaration of partial method '<invalid-global-code>.localG()' // partial void localG() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "localG").WithArguments("<invalid-global-code>.localG()").WithLocation(14, 14), // (14,14): error CS0751: A partial method must be declared within a partial type // partial void localG() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "localG").WithLocation(14, 14), // (15,1): error CS0103: The name 'localG' does not exist in the current context // localG(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localG").WithArguments("localG").WithLocation(15, 1), // (16,13): error CS0179: 'localH()' cannot be extern and declare a body // extern void localH() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_ExternHasBody, "localH").WithArguments("localH()").WithLocation(16, 13), // (20,1): warning CS0612: 'localI()' is obsolete // localI(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "localI()").WithArguments("localI()").WithLocation(20, 1) ); } [Fact] public void LocalFunctionStatement_05() { var text = @" void local1() => System.Console.Write(""1""); local1(); void local2() => System.Console.Write(""2""); local2(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "12"); } [Fact] public void LocalFunctionStatement_06() { var text = @" local(); static void local() { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalFunctionStatement_07() { var text1 = @" local1(1); void local1(int x) {} local2(); "; var text2 = @" void local1(byte y) {} void local2() { local1(2); } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // void local1(byte y) Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(2, 1), // (5,1): error CS0103: The name 'local2' does not exist in the current context // local2(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local2").WithArguments("local2").WithLocation(5, 1), // (5,6): warning CS8321: The local function 'local2' is declared but never used // void local2() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local2").WithArguments("local2").WithLocation(5, 6) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single()); Assert.Equal("void local1(System.Int32 x)", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").Single()).Symbol); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var symbol2 = model2.GetDeclaredSymbol(tree2.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().First()); Assert.Equal("void local1(System.Byte y)", symbol2.ToTestDisplayString()); Assert.Same(symbol2, model2.GetSymbolInfo(tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").Single()).Symbol); } [Fact] public void LocalFunctionStatement_08() { var text = @" void local() { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6) ); CompileAndVerify(comp, expectedOutput: ""); } [Fact] public void LocalFunctionStatement_09() { var text1 = @" local1(1); void local1(int x) {} local2(); void local1(byte y) {} void local2() { local1(2); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (7,6): error CS0128: A local variable or function named 'local1' is already defined in this scope // void local1(byte y) Diagnostic(ErrorCode.ERR_LocalDuplicate, "local1").WithArguments("local1").WithLocation(7, 6), // (7,6): warning CS8321: The local function 'local1' is declared but never used // void local1(byte y) Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local1").WithArguments("local1").WithLocation(7, 6) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().First()); Assert.Equal("void local1(System.Int32 x)", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").First()).Symbol); var symbol2 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Skip(1).First()); Assert.Equal("void local1(System.Byte y)", symbol2.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").Skip(1).Single()).Symbol); } [Fact] public void LocalFunctionStatement_10() { var text = @" int i = 1; local(); System.Console.WriteLine(i); void local() { i++; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void LocalFunctionStatement_11() { var text1 = @" args(1); void args(int x) {} "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,6): error CS0136: A local or parameter named 'args' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void args(int x) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "args").WithArguments("args").WithLocation(3, 6) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().First()); Assert.Equal("void args(System.Int32 x)", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").Single()).Symbol); } [Fact] public void LocalFunctionStatement_12() { var text1 = @" local(1); void local<args>(args x) { System.Console.WriteLine(x); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "1"); } [Fact] public void LocalFunctionStatement_13() { var text1 = @" local(); void local() { var args = 2; System.Console.WriteLine(args); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void LocalFunctionStatement_14() { var text1 = @" local(3); void local(int args) { System.Console.WriteLine(args); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void LocalFunctionStatement_15() { var text1 = @" local(); void local() { args(4); void args(int x) { System.Console.WriteLine(x); } } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void LocalFunctionStatement_16() { var text1 = @" using System.Linq; _ = from local in new object[0] select local; local(); void local() {} "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,10): error CS1931: The range variable 'local' conflicts with a previous declaration of 'local' // _ = from local in new object[0] select local; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "local").WithArguments("local").WithLocation(3, 10) ); } [Fact] public void LocalFunctionStatement_17() { var text = @" System.Console.WriteLine(); string await() => ""Hi!""; System.Console.WriteLine(await()); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,8): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // string await() => "Hi!"; Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(3, 8), // (3,8): warning CS8321: The local function 'await' is declared but never used // string await() => "Hi!"; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "await").WithArguments("await").WithLocation(3, 8), // (4,32): error CS1525: Invalid expression term ')' // System.Console.WriteLine(await()); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(4, 32) ); } [Fact] public void LocalFunctionStatement_18() { var text = @" string async() => ""Hi!""; System.Console.WriteLine(async()); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Lambda_01() { var text = @" int i = 1; System.Action l = () => i++; l(); System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void PropertyDeclaration_01() { var text = @" _ = local; int local => 1; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,5): error CS0103: The name 'local' does not exist in the current context // _ = local; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 5), // (4,5): error CS0116: A namespace cannot directly contain members such as fields or methods // int local => 1; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 5) ); } [Fact] public void PropertyDeclaration_02() { var text = @" _ = local; int local { get => 1; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,5): error CS0103: The name 'local' does not exist in the current context // _ = local; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 5), // (4,5): error CS0116: A namespace cannot directly contain members such as fields or methods // int local { get => 1; } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 5) ); } [Fact] public void PropertyDeclaration_03() { var text = @" _ = local; int local { get { return 1; } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,5): error CS0103: The name 'local' does not exist in the current context // _ = local; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 5), // (4,5): error CS0116: A namespace cannot directly contain members such as fields or methods // int local { get { return 1; } } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 5) ); } [Fact] public void EventDeclaration_01() { var text = @" local += null; event System.Action local; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0103: The name 'local' does not exist in the current context // local += null; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 1), // (4,21): error CS0116: A namespace cannot directly contain members such as fields or methods // event System.Action local; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 21) ); } [Fact] public void EventDeclaration_02() { var text = @" local -= null; event System.Action local { add {} remove {} } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0103: The name 'local' does not exist in the current context // local -= null; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 1), // (4,21): error CS0116: A namespace cannot directly contain members such as fields or methods // event System.Action local Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 21) ); } [Fact] public void LabeledStatement_01() { var text = @" goto label1; label1: System.Console.WriteLine(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "label1").Single(); var label = model.GetDeclaredSymbol(declarator); Assert.Same(label, model.GetSymbolInfo(reference).Symbol); Assert.Equal("label1", label.ToTestDisplayString()); Assert.Equal(SymbolKind.Label, label.Kind); Assert.Equal(SymbolKind.Method, label.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, label.ContainingSymbol.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)label.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); } [Fact] public void LabeledStatement_02() { var text = @" goto label1; label1: System.Console.WriteLine(""Hi!""); label1: System.Console.WriteLine(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS0140: The label 'label1' is a duplicate // label1: System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_DuplicateLabel, "label1").WithArguments("label1").WithLocation(4, 1) ); } [Fact] public void LabeledStatement_03() { var text1 = @" goto label1; label1: System.Console.Write(1); "; var text2 = @" label1: System.Console.Write(2); goto label1; "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // label1: System.Console.Write(2); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "label1").WithLocation(2, 1) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single()); Assert.Equal("label1", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "label1").Single()).Symbol); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var symbol2 = model2.GetDeclaredSymbol(tree2.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single()); Assert.Equal("label1", symbol2.ToTestDisplayString()); Assert.NotEqual(symbol1, symbol2); Assert.Same(symbol2, model2.GetSymbolInfo(tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "label1").Single()).Symbol); } [Fact] public void LabeledStatement_04() { var text = @" goto args; args: System.Console.WriteLine(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").Single(); var label = model.GetDeclaredSymbol(declarator); Assert.Same(label, model.GetSymbolInfo(reference).Symbol); Assert.Equal("args", label.ToTestDisplayString()); Assert.Equal(SymbolKind.Label, label.Kind); Assert.Equal(SymbolKind.Method, label.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, label.ContainingSymbol.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)label.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); } [Fact] public void ExplicitMain_01() { var text = @" static void Main() {} System.Console.Write(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,13): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(2, 13), // (2,13): warning CS8321: The local function 'Main' is declared but never used // static void Main() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Main").WithArguments("Main").WithLocation(2, 13) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_02() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); static void Main() { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,13): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(6, 13) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_03() { var text = @" using System; using System.Threading.Tasks; System.Console.Write(""Hi!""); partial class Program { static async Task Main() { Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (9,23): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static async Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(9, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_04() { var text = @" using System; using System.Threading.Tasks; await Task.Factory.StartNew(() => 5); System.Console.Write(""Hi!""); partial class Program { static async Task Main() { Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (10,23): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static async Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(10, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_05() { var text = @" using System; using System.Threading.Tasks; await Task.Factory.StartNew(() => 5); System.Console.Write(""Hi!""); partial class Program { static void Main() { Console.Write(""hello ""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (10,17): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(10, 17) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_06() { var text = @" System.Console.Write(""Hi!""); partial class Program { static void Main() { System.Console.Write(""hello ""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,17): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(6, 17) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_07() { var text = @" using System; using System.Threading.Tasks; System.Console.Write(""Hi!""); class Program2 { static void Main(string[] args) { Console.Write(""hello ""); } static async Task Main() { Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (9,17): warning CS7022: The entry point of the program is global code; ignoring 'Program2.Main(string[])' entry point. // static void Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program2.Main(string[])").WithLocation(9, 17), // (14,23): warning CS7022: The entry point of the program is global code; ignoring 'Program2.Main()' entry point. // static async Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program2.Main()").WithLocation(14, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_08() { var text = @" using System; using System.Threading.Tasks; await Task.Factory.StartNew(() => 5); System.Console.Write(""Hi!""); class Program2 { static void Main() { Console.Write(""hello ""); } static async Task Main(string[] args) { await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (10,17): warning CS7022: The entry point of the program is global code; ignoring 'Program2.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program2.Main()").WithLocation(10, 17), // (15,23): warning CS7022: The entry point of the program is global code; ignoring 'Program2.Main(string[])' entry point. // static async Task Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program2.Main(string[])").WithLocation(15, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_09() { var text1 = @" using System; using System.Threading.Tasks; string s = ""Hello world!""; foreach (var c in s) { await N1.Helpers.Wait(); Console.Write(c); } Console.WriteLine(); namespace N1 { class Helpers { static void Main() { } public static async Task Wait() { await Task.Delay(500); } } }"; var text4 = @" using System.Threading.Tasks; class Helpers { public static async Task Wait() { await Task.Delay(500); } } "; var comp = CreateCompilation(new[] { text1, text4 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (19,21): warning CS7022: The entry point of the program is global code; ignoring 'Helpers.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("N1.Helpers.Main()").WithLocation(19, 21) ); } [Fact] public void ExplicitMain_10() { var text = @" using System.Threading.Tasks; System.Console.Write(""Hi!""); class Program2 { static void Main() { } static async Task Main(string[] args) { await Task.Factory.StartNew(() => 5); } } class Program3 { static void Main(string[] args) { } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithMainTypeName("Program2"), parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // error CS8804: Cannot specify /main if there is a compilation unit with top-level statements. Diagnostic(ErrorCode.ERR_SimpleProgramDisallowsMainType).WithLocation(1, 1), // (12,23): warning CS8892: Method 'Program2.Main(string[])' will not be used as an entry point because a synchronous entry point 'Program2.Main()' was found. // static async Task Main(string[] args) Diagnostic(ErrorCode.WRN_SyncAndAsyncEntryPoints, "Main").WithArguments("Program2.Main(string[])", "Program2.Main()").WithLocation(12, 23) ); } [Fact] public void ExplicitMain_11() { var text = @" using System.Threading.Tasks; System.Console.Write(""Hi!""); partial class Program { static void Main() { } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithMainTypeName(""), parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // error CS7088: Invalid 'MainTypeName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "").WithLocation(1, 1), // error CS8804: Cannot specify /main if there is a compilation unit with top-level statements. Diagnostic(ErrorCode.ERR_SimpleProgramDisallowsMainType).WithLocation(1, 1) ); } [Fact] public void ExplicitMain_12() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); void Main() { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_13() { var text = @" System.Console.Write(""H""); Main(""""); System.Console.Write(""!""); static void Main(string args) { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_14() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); static long Main() { System.Console.Write(""i""); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_15() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); static int Main() { System.Console.Write(""i""); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,12): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static int Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(6, 12) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_16() { var text = @" System.Console.Write(""H""); Main(null); System.Console.Write(""!""); static void Main(string[] args) { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,13): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static void Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(6, 13) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_17() { var text = @" System.Console.Write(""H""); Main(null); System.Console.Write(""!""); static int Main(string[] args) { System.Console.Write(""i""); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,12): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static int Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(6, 12) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_18() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(); System.Console.Write(""!""); async static Task Main() { System.Console.Write(""i""); await Task.Yield(); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,19): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // async static Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(8, 19) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_19() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(); System.Console.Write(""!""); static async Task<int> Main() { System.Console.Write(""i""); await Task.Yield(); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,24): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static async Task<int> Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(8, 24) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_20() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(null); System.Console.Write(""!""); static async Task Main(string[] args) { System.Console.Write(""i""); await Task.Yield(); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,19): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static async Task Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(8, 19) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_21() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(null); System.Console.Write(""!""); static async Task<int> Main(string[] args) { System.Console.Write(""i""); await Task.Yield(); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,24): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static async Task<int> Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(8, 24) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_22() { var text = @" System.Console.Write(""H""); Main<int>(); System.Console.Write(""!""); static void Main<T>() { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_23() { var text = @" System.Console.Write(""H""); local(); System.Console.Write(""!""); static void local() { Main(); static void Main() { System.Console.Write(""i""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_24() { var text = @" System.Console.Write(42); partial class Program { static partial void Main(string[] args); } "; var comp = CreateCompilation(text); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyDiagnostics(); } [Fact] public void Yield_01() { var text = @"yield break;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // yield break; Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield break;").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(1, 1) ); } [Fact] public void Yield_02() { var text = @"{yield return 0;}"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // {yield return 0;} Diagnostic(ErrorCode.ERR_BadIteratorReturn, "{yield return 0;}").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(1, 1) ); } [Fact] public void OutOfOrder_01() { var text = @" class C {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(4, 1) ); } [Fact] public void OutOfOrder_02() { var text = @" System.Console.WriteLine(0); namespace C {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_03() { var text = @" class C {} System.Console.WriteLine(1); System.Console.WriteLine(2); class D {} System.Console.WriteLine(3); System.Console.WriteLine(4); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(4, 1) ); } [Fact] public void OutOfOrder_04() { var text = @" System.Console.WriteLine(0); namespace C {} System.Console.WriteLine(1); System.Console.WriteLine(2); namespace D {} System.Console.WriteLine(3); System.Console.WriteLine(4); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_05() { var text = @" System.Console.WriteLine(0); struct S {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_06() { var text = @" System.Console.WriteLine(0); enum C { V } System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_07() { var text = @" System.Console.WriteLine(0); interface C {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_08() { var text = @" System.Console.WriteLine(0); delegate void D (); System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_09() { var text = @" System.Console.WriteLine(0); using System; Console.WriteLine(1); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // using System; Diagnostic(ErrorCode.ERR_UsingAfterElements, "using System;").WithLocation(4, 1), // (6,1): error CS0103: The name 'Console' does not exist in the current context // Console.WriteLine(1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Console").WithArguments("Console").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_10() { var text = @" System.Console.WriteLine(0); [module: MyAttribute] class MyAttribute : System.Attribute {} "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,2): error CS1730: Assembly and module attributes must precede all other elements defined in a file except using clauses and extern alias declarations // [module: MyAttribute] Diagnostic(ErrorCode.ERR_GlobalAttributesNotFirst, "module").WithLocation(4, 2) ); } [Fact] public void OutOfOrder_11() { var text = @" System.Console.WriteLine(0); extern alias A; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS0439: An extern alias declaration must precede all other elements defined in the namespace // extern alias A; Diagnostic(ErrorCode.ERR_ExternAfterElements, "extern").WithLocation(4, 1) ); } [Fact] public void OutOfOrder_12() { var text = @" extern alias A; using System; [module: MyAttribute] Console.WriteLine(1); class MyAttribute : System.Attribute {} "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): hidden CS8020: Unused extern alias. // extern alias A; Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias A;").WithLocation(2, 1), // (2,14): error CS0430: The extern alias 'A' was not specified in a /reference option // extern alias A; Diagnostic(ErrorCode.ERR_BadExternAlias, "A").WithArguments("A").WithLocation(2, 14) ); } [Fact] public void OutOfOrder_13() { var text = @" local(); class C {} void local() => System.Console.WriteLine(1); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // void local() => System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "void local() => System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void Attributes_01() { var text1 = @" [MyAttribute(i)] const int i = 1; [MyAttribute(i + 1)] System.Console.Write(i); [MyAttribute(i + 2)] int j = i; System.Console.Write(j); [MyAttribute(i + 3)] new MyAttribute(i); [MyAttribute(i + 4)] local(); [MyAttribute(i + 5)] void local() {} class MyAttribute : System.Attribute { public MyAttribute(int x) {} } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i)]").WithLocation(2, 1), // (5,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i + 1)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i + 1)]").WithLocation(5, 1), // (8,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i + 2)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i + 2)]").WithLocation(8, 1), // (12,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i + 3)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i + 3)]").WithLocation(12, 1), // (16,1): error CS0246: The type or namespace name 'local' could not be found (are you missing a using directive or an assembly reference?) // local(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "local").WithArguments("local").WithLocation(16, 1), // (16,6): error CS1001: Identifier expected // local(); Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(16, 6), // (16,6): error CS8112: Local function '()' must declare a body because it is not marked 'static extern'. // local(); Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "").WithArguments("()").WithLocation(16, 6), // (19,6): warning CS8321: The local function 'local' is declared but never used // void local() {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(19, 6) ); var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); var localRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").ToArray(); Assert.Equal(9, localRefs.Length); foreach (var localRef in localRefs) { var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Same(declSymbol, refSymbol); Assert.Contains(declSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localRef.SpanStart, name: declSymbol.Name).Single()); } localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1); declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 j", declSymbol.ToTestDisplayString()); } [Fact] public void Attributes_02() { var source = @" using System.Runtime.CompilerServices; return; #pragma warning disable 8321 // Unreferenced local function [MethodImpl(MethodImplOptions.ForwardRef)] static void forwardRef() { System.Console.WriteLine(0); } [MethodImpl(MethodImplOptions.NoInlining)] static void noInlining() { System.Console.WriteLine(1); } [MethodImpl(MethodImplOptions.NoOptimization)] static void noOptimization() { System.Console.WriteLine(2); } [MethodImpl(MethodImplOptions.Synchronized)] static void synchronized() { System.Console.WriteLine(3); } [MethodImpl(MethodImplOptions.InternalCall)] extern static void internalCallStatic(); "; var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: DefaultParseOptions, assemblyValidator: validateAssembly, verify: Verification.Skipped); var comp = verifier.Compilation; var syntaxTree = comp.SyntaxTrees.Single(); var semanticModel = comp.GetSemanticModel(syntaxTree); var localFunctions = syntaxTree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToList(); checkImplAttributes(localFunctions[0], MethodImplAttributes.ForwardRef); checkImplAttributes(localFunctions[1], MethodImplAttributes.NoInlining); checkImplAttributes(localFunctions[2], MethodImplAttributes.NoOptimization); checkImplAttributes(localFunctions[3], MethodImplAttributes.Synchronized); checkImplAttributes(localFunctions[4], MethodImplAttributes.InternalCall); void checkImplAttributes(LocalFunctionStatementSyntax localFunctionStatement, MethodImplAttributes expectedFlags) { var localFunction = semanticModel.GetDeclaredSymbol(localFunctionStatement).GetSymbol<LocalFunctionSymbol>(); Assert.Equal(expectedFlags, localFunction.ImplementationAttributes); } void validateAssembly(PEAssembly assembly) { var peReader = assembly.GetMetadataReader(); foreach (var methodHandle in peReader.MethodDefinitions) { var methodDef = peReader.GetMethodDefinition(methodHandle); var actualFlags = methodDef.ImplAttributes; var methodName = peReader.GetString(methodDef.Name); var expectedFlags = methodName switch { "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__forwardRef|0_0" => MethodImplAttributes.ForwardRef, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__noInlining|0_1" => MethodImplAttributes.NoInlining, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__noOptimization|0_2" => MethodImplAttributes.NoOptimization, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__synchronized|0_3" => MethodImplAttributes.Synchronized, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__internalCallStatic|0_4" => MethodImplAttributes.InternalCall, ".ctor" => MethodImplAttributes.IL, WellKnownMemberNames.TopLevelStatementsEntryPointMethodName => MethodImplAttributes.IL, _ => throw TestExceptionUtilities.UnexpectedValue(methodName) }; Assert.Equal(expectedFlags, actualFlags); } } } [Fact] public void Attributes_03() { var source = @" using System.Runtime.InteropServices; local1(); [DllImport( ""something.dll"", EntryPoint = ""a"", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true, PreserveSig = false, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] static extern void local1(); "; var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: DefaultParseOptions, symbolValidator: validate, sourceSymbolValidator: validate, verify: Verification.Skipped); var comp = verifier.Compilation; var syntaxTree = comp.SyntaxTrees.Single(); var semanticModel = comp.GetSemanticModel(syntaxTree); var localFunction = semanticModel .GetDeclaredSymbol(syntaxTree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single()) .GetSymbol<LocalFunctionSymbol>(); Assert.Equal(new[] { "DllImportAttribute" }, GetAttributeNames(localFunction.GetAttributes())); validateLocalFunction(localFunction); void validate(ModuleSymbol module) { var fromSource = module is SourceModuleSymbol; var program = module.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName); var programAttributes = GetAttributeNames(program.GetAttributes().As<CSharpAttributeData>()); Assert.False(program.IsImplicitlyDeclared); if (fromSource) { Assert.Empty(programAttributes); } else { Assert.Equal(new[] { "CompilerGeneratedAttribute" }, programAttributes); } MethodSymbol method = program.GetMethod(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName); Assert.Empty(method.GetAttributes()); Assert.False(method.IsImplicitlyDeclared); if (!fromSource) { var localFn1 = program.GetMethod("<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__local1|0_0"); Assert.Equal(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(localFn1.GetAttributes().As<CSharpAttributeData>())); validateLocalFunction(localFn1); } } static void validateLocalFunction(MethodSymbol localFunction) { Assert.True(localFunction.IsExtern); var importData = localFunction.GetDllImportData(); Assert.NotNull(importData); Assert.Equal("something.dll", importData.ModuleName); Assert.Equal("a", importData.EntryPointName); Assert.Equal(CharSet.Ansi, importData.CharacterSet); Assert.True(importData.SetLastError); Assert.True(importData.ExactSpelling); Assert.Equal(MethodImplAttributes.IL, localFunction.ImplementationAttributes); Assert.Equal(CallingConvention.Cdecl, importData.CallingConvention); Assert.False(importData.BestFitMapping); Assert.True(importData.ThrowOnUnmappableCharacter); } } [Fact] public void ModelWithIgnoredAccessibility_01() { var source = @" new A().M(); class A { A M() { return new A(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,9): error CS0122: 'A.M()' is inaccessible due to its protection level // new A().M(); Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("A.M()").WithLocation(2, 9) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree = comp.SyntaxTrees.Single(); var invocation = syntaxTree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var semanticModel = comp.GetSemanticModel(syntaxTree); Assert.Equal("A", semanticModel.GetTypeInfo(invocation).Type.Name); Assert.Null(semanticModel.GetSymbolInfo(invocation).Symbol); Assert.Equal("M", semanticModel.GetSymbolInfo(invocation).CandidateSymbols.Single().Name); Assert.Equal(CandidateReason.Inaccessible, semanticModel.GetSymbolInfo(invocation).CandidateReason); Assert.Empty(semanticModel.LookupSymbols(invocation.SpanStart, container: a, name: "M")); semanticModel = comp.GetSemanticModel(syntaxTree, ignoreAccessibility: true); Assert.Equal("A", semanticModel.GetTypeInfo(invocation).Type.Name); Assert.Equal("M", semanticModel.GetSymbolInfo(invocation).Symbol.Name); Assert.NotEmpty(semanticModel.LookupSymbols(invocation.SpanStart, container: a, name: "M")); } [Fact] public void ModelWithIgnoredAccessibility_02() { var source = @" var x = new A().M(); class A { A M() { x = null; return new A(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,17): error CS0122: 'A.M()' is inaccessible due to its protection level // var x = new A().M(); Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("A.M()").WithLocation(2, 17), // (8,9): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // x = null; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(8, 9) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree = comp.SyntaxTrees.Single(); var localDecl = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var localRef = syntaxTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); var semanticModel = comp.GetSemanticModel(syntaxTree, ignoreAccessibility: true); var x = semanticModel.GetDeclaredSymbol(localDecl); Assert.Same(x, semanticModel.LookupSymbols(localDecl.SpanStart, name: "x").Single()); Assert.Same(x, semanticModel.GetSymbolInfo(localRef).Symbol); Assert.Same(x, semanticModel.LookupSymbols(localRef.SpanStart, name: "x").Single()); } [Fact] public void ModelWithIgnoredAccessibility_03() { var source = @" var x = new B().M(1); class A { public long M(long i) => i; } class B : A { protected int M(int i) { _ = x; return i; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,13): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // _ = x; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(13, 13) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree1 = comp.SyntaxTrees.Single(); var localDecl = syntaxTree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var localRef = syntaxTree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); verifyModel(ignoreAccessibility: true, "System.Int32"); verifyModel(ignoreAccessibility: false, "System.Int64"); void verifyModel(bool ignoreAccessibility, string expectedType) { var semanticModel1 = comp.GetSemanticModel(syntaxTree1, ignoreAccessibility); var xDecl = semanticModel1.GetDeclaredSymbol(localDecl); Assert.Same(xDecl, semanticModel1.LookupSymbols(localDecl.SpanStart, name: "x").Single()); var xRef = semanticModel1.GetSymbolInfo(localRef).Symbol; Assert.Same(xRef, semanticModel1.LookupSymbols(localRef.SpanStart, name: "x").Single()); Assert.Equal(expectedType, ((ILocalSymbol)xRef).Type.ToTestDisplayString()); Assert.Equal(expectedType, ((ILocalSymbol)xDecl).Type.ToTestDisplayString()); Assert.Same(xDecl, xRef); } } [Fact] public void ModelWithIgnoredAccessibility_04() { var source1 = @" var x = new B().M(1); "; var source2 = @" class A { public long M(long i) => i; } class B : A { protected int M(int i) { _ = x; return i; } } "; var comp = CreateCompilation(new[] { source1, source2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (11,13): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // _ = x; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(11, 13) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree1 = comp.SyntaxTrees.First(); var localDecl = syntaxTree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var syntaxTree2 = comp.SyntaxTrees[1]; var localRef = syntaxTree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); verifyModel(ignoreAccessibility: true, "System.Int32"); verifyModel(ignoreAccessibility: false, "System.Int64"); void verifyModel(bool ignoreAccessibility, string expectedType) { var semanticModel1 = comp.GetSemanticModel(syntaxTree1, ignoreAccessibility); var xDecl = semanticModel1.GetDeclaredSymbol(localDecl); Assert.Same(xDecl, semanticModel1.LookupSymbols(localDecl.SpanStart, name: "x").Single()); Assert.Equal(expectedType, ((ILocalSymbol)xDecl).Type.ToTestDisplayString()); var semanticModel2 = comp.GetSemanticModel(syntaxTree2, ignoreAccessibility); var xRef = semanticModel2.GetSymbolInfo(localRef).Symbol; Assert.Same(xRef, semanticModel2.LookupSymbols(localRef.SpanStart, name: "x").Single()); Assert.Equal(expectedType, ((ILocalSymbol)xRef).Type.ToTestDisplayString()); Assert.Same(xDecl, xRef); } } [Fact] public void AnalyzerActions_01() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_01_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(0, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(0, analyzer.FireCount6); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_01_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); } private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.GlobalStatement); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.CompilationUnit); } private void Handle1(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var globalStatement = (GlobalStatementSyntax)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (globalStatement.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(globalStatement.SyntaxTree, context.ContainingSymbol.DeclaringSyntaxReferences.Single().SyntaxTree); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(globalStatement.Parent)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[globalStatement.Parent]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(globalStatement.Statement).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(globalStatement.Statement)); } private void Handle2(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var unit = (CompilationUnitSyntax)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (unit.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref context.ContainingSymbol.Kind == SymbolKind.Namespace ? ref FireCount5 : ref FireCount3); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref context.ContainingSymbol.Kind == SymbolKind.Namespace ? ref FireCount6 : ref FireCount4); break; default: Assert.True(false); break; } switch (context.ContainingSymbol.ToTestDisplayString()) { case "<top-level-statements-entry-point>": Assert.Same(unit.SyntaxTree, context.ContainingSymbol.DeclaringSyntaxReferences.Single().SyntaxTree); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(unit)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(unit).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(unit)); break; case "<global namespace>": break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_02() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_02_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_02_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_02_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.Method); } private void Handle(SymbolAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); switch (context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_03() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_03_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(0, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(0, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_03_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); } private class AnalyzerActions_03_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolStartAction(Handle1, SymbolKind.Method); context.RegisterSymbolStartAction(Handle2, SymbolKind.NamedType); } private void Handle1(SymbolStartAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); switch (context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); context.RegisterSymbolEndAction(Handle3); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); context.RegisterSymbolEndAction(Handle4); break; default: Assert.True(false); break; } } private void Handle2(SymbolStartAnalysisContext context) { Assert.Equal(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount3); context.RegisterSymbolEndAction(Handle5); foreach (var syntaxReference in context.Symbol.DeclaringSyntaxReferences) { switch (syntaxReference.GetSyntax().ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount4); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount5); break; default: Assert.True(false); break; } } } private void Handle3(SymbolAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); Assert.Equal("System.Console.WriteLine(1);", context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); } private void Handle4(SymbolAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); Assert.Equal("System.Console.WriteLine(2);", context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); } private void Handle5(SymbolAnalysisContext context) { Assert.Equal(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); } } [Fact] public void AnalyzerActions_04() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_04_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(0, analyzer.FireCount4); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_04_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationAction(Handle1, OperationKind.Invocation); context.RegisterOperationAction(Handle2, OperationKind.Block); } private void Handle1(OperationAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(context.ContainingSymbol.DeclaringSyntaxReferences.Single().SyntaxTree, context.Operation.Syntax.SyntaxTree); Assert.Equal(SyntaxKind.InvocationExpression, context.Operation.Syntax.Kind()); switch (context.Operation.Syntax.ToString()) { case "System.Console.WriteLine(1)": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2)": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } private void Handle2(OperationAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(context.ContainingSymbol.DeclaringSyntaxReferences.Single().GetSyntax(), context.Operation.Syntax); Assert.Equal(SyntaxKind.CompilationUnit, context.Operation.Syntax.Kind()); switch (context.Operation.Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount3); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_05() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_05_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_05_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockAction(Handle); } private void Handle(OperationBlockAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.OperationBlocks.Single().Syntax.Kind()); switch (context.OperationBlocks.Single().Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_06() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_06_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_06_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_06_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle); } private void Handle(OperationBlockStartAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.OperationBlocks.Single().Syntax.Kind()); switch (context.OperationBlocks.Single().Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_07() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_07_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_07_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(Handle); } private void Handle(CodeBlockAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.CodeBlock.Kind()); switch (context.CodeBlock.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } var model = context.SemanticModel; var unit = (CompilationUnitSyntax)context.CodeBlock; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(unit).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(unit)); } } [Fact] public void AnalyzerActions_08() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_08_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_08_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_08_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(Handle); } private void Handle(CodeBlockStartAnalysisContext<SyntaxKind> context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.CodeBlock.Kind()); switch (context.CodeBlock.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } var model = context.SemanticModel; var unit = (CompilationUnitSyntax)context.CodeBlock; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(unit).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(unit)); } } [Fact] public void AnalyzerActions_09() { var text1 = @" System.Console.WriteLine(""Hi!""); "; var text2 = @" class Test { void M() { M(); } } "; var analyzer = new AnalyzerActions_09_Analyzer(); var comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); analyzer = new AnalyzerActions_09_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(2, analyzer.FireCount4); } private class AnalyzerActions_09_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.InvocationExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.CompilationUnit); } private void Handle1(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var node = (CSharpSyntaxNode)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (node.ToString()) { case @"System.Console.WriteLine(""Hi!"")": Interlocked.Increment(ref FireCount1); Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); break; case "M()": Interlocked.Increment(ref FireCount2); Assert.Equal("void Test.M()", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } var decl = (CSharpSyntaxNode)context.ContainingSymbol.DeclaringSyntaxReferences.Single().GetSyntax(); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(decl)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[decl]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(node).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(node)); } private void Handle2(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var node = (CSharpSyntaxNode)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (context.ContainingSymbol.ToTestDisplayString()) { case @"<top-level-statements-entry-point>": Interlocked.Increment(ref FireCount3); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(node)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[node]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(node).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(node)); break; case "<global namespace>": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_10() { var text1 = @" [assembly: MyAttribute(1)] "; var text2 = @" System.Console.WriteLine(""Hi!""); "; var text3 = @" [MyAttribute(2)] class Test { [MyAttribute(3)] void M() { } } class MyAttribute : System.Attribute { public MyAttribute(int x) {} } "; var analyzer = new AnalyzerActions_10_Analyzer(); var comp = CreateCompilation(text1 + text2 + text3, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); analyzer = new AnalyzerActions_10_Analyzer(); comp = CreateCompilation(new[] { text1, text2, text3 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(3, analyzer.FireCount5); } private class AnalyzerActions_10_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.Attribute); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.CompilationUnit); } private void Handle1(SyntaxNodeAnalysisContext context) { var node = (CSharpSyntaxNode)context.Node; switch (node.ToString()) { case @"MyAttribute(1)": Interlocked.Increment(ref FireCount1); Assert.Equal("<global namespace>", context.ContainingSymbol.ToTestDisplayString()); break; case @"MyAttribute(2)": Interlocked.Increment(ref FireCount2); Assert.Equal("Test", context.ContainingSymbol.ToTestDisplayString()); break; case @"MyAttribute(3)": Interlocked.Increment(ref FireCount3); Assert.Equal("void Test.M()", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } } private void Handle2(SyntaxNodeAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case @"<top-level-statements-entry-point>": Interlocked.Increment(ref FireCount4); break; case @"<global namespace>": Interlocked.Increment(ref FireCount5); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_11() { var text1 = @" System.Console.WriteLine(""Hi!""); "; var text2 = @" namespace N1 {} class C1 {} "; var analyzer = new AnalyzerActions_11_Analyzer(); var comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); analyzer = new AnalyzerActions_11_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_11_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle1, SymbolKind.Method); context.RegisterSymbolAction(Handle2, SymbolKind.Namespace); context.RegisterSymbolAction(Handle3, SymbolKind.NamedType); } private void Handle1(SymbolAnalysisContext context) { Interlocked.Increment(ref FireCount1); Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); } private void Handle2(SymbolAnalysisContext context) { Interlocked.Increment(ref FireCount2); Assert.Equal("N1", context.Symbol.ToTestDisplayString()); } private void Handle3(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "C1": Interlocked.Increment(ref FireCount3); break; case WellKnownMemberNames.TopLevelStatementsEntryPointTypeName: Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_12() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_12_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_12_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(2, analyzer.FireCount3); } private class AnalyzerActions_12_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle1); } private void Handle1(OperationBlockStartAnalysisContext context) { Interlocked.Increment(ref FireCount3); context.RegisterOperationBlockEndAction(Handle2); } private void Handle2(OperationBlockAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.OperationBlocks.Single().Syntax.Kind()); switch (context.OperationBlocks.Single().Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_13() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_13_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_13_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(2, analyzer.FireCount3); } private class AnalyzerActions_13_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle1); } private void Handle1(OperationBlockStartAnalysisContext context) { Interlocked.Increment(ref FireCount3); context.RegisterOperationAction(Handle2, OperationKind.Block); } private void Handle2(OperationAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(context.ContainingSymbol.DeclaringSyntaxReferences.Single().GetSyntax(), context.Operation.Syntax); Assert.Equal(SyntaxKind.CompilationUnit, context.Operation.Syntax.Kind()); switch (context.Operation.Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void MissingTypes_01() { var text = @"return;"; var comp = CreateEmptyCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (1,1): error CS0518: Predefined type 'System.Object' is not defined or imported // return; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "return").WithArguments("System.Object").WithLocation(1, 1), // error CS0518: Predefined type 'System.Void' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Void").WithLocation(1, 1), // error CS0518: Predefined type 'System.String' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.String").WithLocation(1, 1), // (1,1): error CS1729: 'object' does not contain a constructor that takes 0 arguments // return; Diagnostic(ErrorCode.ERR_BadCtorArgCount, "return").WithArguments("object", "0").WithLocation(1, 1) ); } [Fact] public void MissingTypes_02() { var text = @"await Test();"; var comp = CreateCompilation(text, targetFramework: TargetFramework.Minimal, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Threading.Tasks.Task' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Threading.Tasks.Task").WithLocation(1, 1), // (1,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await Test(); Diagnostic(ErrorCode.WRN_InvalidMainSig, "await Test();").WithArguments("<top-level-statements-entry-point>").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (1,7): error CS0103: The name 'Test' does not exist in the current context // await Test(); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(1, 7) ); } [Fact] public void MissingTypes_03() { var text = @" System.Console.WriteLine(""Hi!""); return 10; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_Int32); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32[missing]", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Int32' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Int32").WithLocation(1, 1), // (3,8): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 10; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "10").WithArguments("System.Int32").WithLocation(3, 8) ); } [Fact] public void MissingTypes_04() { var text = @" await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_Int32); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32[missing]>", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Int32' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Int32").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (2,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.WRN_InvalidMainSig, @"await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); return 11; ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Int32' is not defined or imported // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await System.Threading.Tasks.Task.Factory.StartNew(() => 5L);").WithArguments("System.Int32").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Int32' is not defined or imported // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await System.Threading.Tasks.Task.Factory.StartNew(() => 5L);").WithArguments("System.Int32").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Int32' is not defined or imported // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await System.Threading.Tasks.Task.Factory.StartNew(() => 5L);").WithArguments("System.Int32").WithLocation(2, 1), // (3,8): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 11; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "11").WithArguments("System.Int32").WithLocation(3, 8) ); } [Fact] public void MissingTypes_05() { var text = @" await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(WellKnownType.System_Threading_Tasks_Task_T); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32>[missing]", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Threading.Tasks.Task`1' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Threading.Tasks.Task`1").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (2,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await System.Threading.Tasks.Task.Factory.StartNew(() => "5"); Diagnostic(ErrorCode.WRN_InvalidMainSig, @"await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1) ); } [Fact] public void MissingTypes_06() { var text = @" await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_Int32); comp.MakeTypeMissing(WellKnownType.System_Threading_Tasks_Task_T); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32[missing]>[missing]", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Threading.Tasks.Task`1' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Threading.Tasks.Task`1").WithLocation(1, 1), // error CS0518: Predefined type 'System.Int32' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Int32").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (2,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await System.Threading.Tasks.Task.Factory.StartNew(() => "5"); Diagnostic(ErrorCode.WRN_InvalidMainSig, @"await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1), // (3,8): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 11; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "11").WithArguments("System.Int32").WithLocation(3, 8) ); } [Fact] public void MissingTypes_07() { var text = @" System.Console.WriteLine(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_String); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.String[missing][] args", entryPoint.Parameters.Single().ToTestDisplayString()); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.String' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.String").WithLocation(1, 1) ); } [Fact] public void Return_01() { var text = @" System.Console.WriteLine(args[0]); return; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Return_01", args: new[] { "Return_01" }); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" name=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2"" startColumn=""1"" endLine=""2"" endColumn=""35"" document=""1"" /> <entry offset=""0x9"" startLine=""3"" startColumn=""1"" endLine=""3"" endColumn=""8"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } private static string EscapeForXML(string toEscape) { return toEscape.Replace("<", "&lt;").Replace(">", "&gt;"); } [Fact] public void Return_02() { var text = @" System.Console.WriteLine(args[0]); return 10; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Return_02", args: new[] { "Return_02" }, expectedReturnCode: 10); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" name=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2"" startColumn=""1"" endLine=""2"" endColumn=""35"" document=""1"" /> <entry offset=""0x9"" startLine=""3"" startColumn=""1"" endLine=""3"" endColumn=""11"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } [Fact] public void Return_03() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(args[0]); return; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "hello Return_03", args: new[] { "Return_03" }); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "+<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">d__0.MoveNext", @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""&lt;Main&gt;"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;&gt;c"" methodName=""&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;b__0_0"" /> <encLocalSlotMap> <slot kind=""27"" offset=""2"" /> <slot kind=""33"" offset=""76"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""5"" startColumn=""1"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x19"" startLine=""6"" startColumn=""1"" endLine=""6"" endColumn=""38"" document=""1"" /> <entry offset=""0x48"" hidden=""true"" document=""1"" /> <entry offset=""0x99"" startLine=""7"" startColumn=""1"" endLine=""7"" endColumn=""24"" document=""1"" /> <entry offset=""0xa7"" startLine=""8"" startColumn=""1"" endLine=""8"" endColumn=""8"" document=""1"" /> <entry offset=""0xa9"" hidden=""true"" document=""1"" /> <entry offset=""0xc1"" hidden=""true"" document=""1"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0xa9"" /> <kickoffMethod declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <await yield=""0x5a"" resume=""0x75"" declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } [Fact] public void Return_04() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(args[0]); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32>", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "hello Return_04", args: new[] { "Return_04" }, expectedReturnCode: 11); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "+<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">d__0.MoveNext", @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""&lt;Main&gt;"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;&gt;c"" methodName=""&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;b__0_0"" /> <encLocalSlotMap> <slot kind=""27"" offset=""2"" /> <slot kind=""20"" offset=""2"" /> <slot kind=""33"" offset=""76"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""5"" startColumn=""1"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x19"" startLine=""6"" startColumn=""1"" endLine=""6"" endColumn=""38"" document=""1"" /> <entry offset=""0x48"" hidden=""true"" document=""1"" /> <entry offset=""0x99"" startLine=""7"" startColumn=""1"" endLine=""7"" endColumn=""24"" document=""1"" /> <entry offset=""0xa7"" startLine=""8"" startColumn=""1"" endLine=""8"" endColumn=""11"" document=""1"" /> <entry offset=""0xac"" hidden=""true"" document=""1"" /> <entry offset=""0xc6"" hidden=""true"" document=""1"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0xac"" /> <kickoffMethod declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <await yield=""0x5a"" resume=""0x75"" declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } [Fact] public void Return_05() { var text = @" System.Console.WriteLine(""Hi!""); return ""error""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyDiagnostics( // (3,8): error CS0029: Cannot implicitly convert type 'string' to 'int' // return "error"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""error""").WithArguments("string", "int").WithLocation(3, 8) ); } [Fact] public void Return_06() { var text = @" System.Func<int, int> d = n => { System.Console.WriteLine(""Hi!""); return n; }; d(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_07() { var text = @" System.Func<int, int> d = delegate(int n) { System.Console.WriteLine(""Hi!""); return n; }; d(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_08() { var text = @" System.Func<int, int> d = (n) => { System.Console.WriteLine(""Hi!""); return n; }; d(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_09() { var text = @" int local(int n) { System.Console.WriteLine(""Hi!""); return n; } local(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_10() { var text = @" bool b = true; if (b) return 0; else return; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyDiagnostics( // (6,5): error CS0126: An object of a type convertible to 'int' is required // return; Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("int").WithLocation(6, 5) ); } [Fact] public void Return_11() { var text = @" bool b = true; if (b) return; else return 0; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyDiagnostics( // (4,5): error CS0126: An object of a type convertible to 'int' is required // return; Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("int").WithLocation(4, 5) ); } [Fact] public void Return_12() { var text = @" System.Console.WriteLine(1); return; System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "1").VerifyDiagnostics( // (4,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(4, 1) ); } [Fact] public void Return_13() { var text = @" System.Console.WriteLine(1); return 13; System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "1", expectedReturnCode: 13).VerifyDiagnostics( // (4,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(4, 1) ); } [Fact] public void Return_14() { var text = @" System.Console.WriteLine(""Hi!""); return default; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!", expectedReturnCode: 0); } [Fact] public void Return_15() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); return default; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32>", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "hello async main", expectedReturnCode: 0); } [Fact] public void Dll_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugDll, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (1,1): error CS8805: Program using top-level statements must be an executable. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, @"System.Console.WriteLine(""Hi!"");").WithLocation(1, 1) ); } [Fact] public void NetModule_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.ReleaseModule, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (1,1): error CS8805: Program using top-level statements must be an executable. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, @"System.Console.WriteLine(""Hi!"");").WithLocation(1, 1) ); } [Fact] public void ExpressionStatement_01() { // Await expression is covered in other tests var text = @" new Test(0); // ObjectCreationExpression: Test x; x = new Test(1); // SimpleAssignmentExpression: x += 1; // AddAssignmentExpression: x -= 2; // SubtractAssignmentExpression: x *= 3; // MultiplyAssignmentExpression: x /= 4; // DivideAssignmentExpression: x %= 5; // ModuloAssignmentExpression: x &= 6; // AndAssignmentExpression: x |= 7; // OrAssignmentExpression: x ^= 8; // ExclusiveOrAssignmentExpression: x <<= 9; // LeftShiftAssignmentExpression: x >>= 10; // RightShiftAssignmentExpression: x++; // PostIncrementExpression: x--; // PostDecrementExpression: ++x; // PreIncrementExpression: --x; // PreDecrementExpression: System.Console.WriteLine(x.Count); // InvocationExpression: x?.WhenNotNull(); // ConditionalAccessExpression: x = null; x ??= new Test(-1); // CoalesceAssignmentExpression: System.Console.WriteLine(x.Count); // InvocationExpression: class Test { public readonly int Count; public Test(int count) { Count = count; if (count == 0) { System.Console.WriteLine(""Test..ctor""); } } public static Test operator +(Test x, int y) { return new Test(x.Count + 1); } public static Test operator -(Test x, int y) { return new Test(x.Count + 1); } public static Test operator *(Test x, int y) { return new Test(x.Count + 1); } public static Test operator /(Test x, int y) { return new Test(x.Count + 1); } public static Test operator %(Test x, int y) { return new Test(x.Count + 1); } public static Test operator &(Test x, int y) { return new Test(x.Count + 1); } public static Test operator |(Test x, int y) { return new Test(x.Count + 1); } public static Test operator ^(Test x, int y) { return new Test(x.Count + 1); } public static Test operator <<(Test x, int y) { return new Test(x.Count + 1); } public static Test operator >>(Test x, int y) { return new Test(x.Count + 1); } public static Test operator ++(Test x) { return new Test(x.Count + 1); } public static Test operator --(Test x) { return new Test(x.Count + 1); } public void WhenNotNull() { System.Console.WriteLine(""WhenNotNull""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: @"Test..ctor 15 WhenNotNull -1 "); } [Fact] public void Block_01() { var text = @" { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatement_01() { var text = @" ; System.Console.WriteLine(""Hi!""); ; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void BreakStatement_01() { var text = @"break;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS0139: No enclosing loop out of which to break or continue // break; Diagnostic(ErrorCode.ERR_NoBreakOrCont, "break;").WithLocation(1, 1) ); } [Fact] public void ContinueStatement_01() { var text = @"continue;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS0139: No enclosing loop out of which to break or continue // continue; Diagnostic(ErrorCode.ERR_NoBreakOrCont, "continue;").WithLocation(1, 1) ); } [Fact] public void ThrowStatement_01() { var text = @"throw;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause // throw; Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(1, 1) ); } [Fact] public void ThrowStatement_02() { var text = @"throw null;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp).VerifyIL("<top-level-statements-entry-point>", sequencePoints: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, source: text, expectedIL: @" { // Code size 2 (0x2) .maxstack 1 // sequence point: throw null; IL_0000: ldnull IL_0001: throw } "); } [Fact] public void DoStatement_01() { var text = @" int i = 1; do { i++; } while (i < 4); System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void WhileStatement_01() { var text = @" int i = 1; while (i < 4) { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void ForStatement_01() { var text = @" int i = 1; for (;i < 4;) { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void CheckedStatement_01() { var text = @" int i = 1; i++; checked { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "3").VerifyIL("<top-level-statements-entry-point>", sequencePoints: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, source: text, expectedIL: @" { // Code size 20 (0x14) .maxstack 2 .locals init (int V_0) //i // sequence point: int i = 1; IL_0000: ldc.i4.1 IL_0001: stloc.0 // sequence point: i++; IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: add IL_0005: stloc.0 // sequence point: { IL_0006: nop // sequence point: i++; IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: add.ovf IL_000a: stloc.0 // sequence point: } IL_000b: nop // sequence point: System.Console.WriteLine(i); IL_000c: ldloc.0 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: nop IL_0013: ret } "); } [Fact] public void UncheckedStatement_01() { var text = @" int i = 1; i++; unchecked { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithOverflowChecks(true), parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "3").VerifyIL("<top-level-statements-entry-point>", sequencePoints: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, source: text, expectedIL: @" { // Code size 20 (0x14) .maxstack 2 .locals init (int V_0) //i // sequence point: int i = 1; IL_0000: ldc.i4.1 IL_0001: stloc.0 // sequence point: i++; IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: add.ovf IL_0005: stloc.0 // sequence point: { IL_0006: nop // sequence point: i++; IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: add IL_000a: stloc.0 // sequence point: } IL_000b: nop // sequence point: System.Console.WriteLine(i); IL_000c: ldloc.0 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: nop IL_0013: ret } "); } [Fact] public void UnsafeStatement_01() { var text = @" unsafe { int* p = (int*)0; p++; System.Console.WriteLine((int)p); } "; var comp = CreateCompilation(text, options: TestOptions.UnsafeDebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "4", verify: Verification.Skipped); } [Fact] public void FixedStatement_01() { var text = @" fixed(int *p = &new C().i) {} class C { public int i = 2; } "; var comp = CreateCompilation(text, options: TestOptions.UnsafeDebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (2,1): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed(int *p = &new C().i) {} Diagnostic(ErrorCode.ERR_UnsafeNeeded, "fixed(int *p = &new C().i) {}").WithLocation(2, 1), // (2,7): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed(int *p = &new C().i) {} Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int *").WithLocation(2, 7), // (2,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed(int *p = &new C().i) {} Diagnostic(ErrorCode.ERR_UnsafeNeeded, "&new C().i").WithLocation(2, 16) ); } [Fact] public void LockStatement_01() { var text = @" int i = 1; lock (new object()) { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void IfStatement_01() { var text = @" int i = 1; if (i == 1) { i++; } else { i--; } if (i != 2) { i--; } else { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void SwitchStatement_01() { var text = @" int i = 1; switch (i) { case 1: i++; break; default: i--; break; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void TryStatement_01() { var text = @" try { System.Console.Write(1); throw null; } catch { System.Console.Write(2); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "12"); } [Fact] public void Args_01() { var text = @" #nullable enable System.Console.WriteLine(args.Length == 0 ? 0 : -args[0].Length); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "0").VerifyDiagnostics(); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); AssertEntryPointParameter(entryPoint); } [Fact] public void Args_02() { var text1 = @" using System.Linq; _ = from args in new object[0] select args; "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,10): error CS1931: The range variable 'args' conflicts with a previous declaration of 'args' // _ = from args in new object[0] select args; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "args").WithArguments("args").WithLocation(3, 10) ); } [Fact] public void Args_03() { var text = @" local(); void local() { System.Console.WriteLine(args[0]); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Args_03", args: new[] { "Args_03" }).VerifyDiagnostics(); } [Fact] public void Args_04() { var text = @" System.Action lambda = () => System.Console.WriteLine(args[0]); lambda(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Args_04", args: new[] { "Args_04" }).VerifyDiagnostics(); } [Fact] public void Span_01() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; Span<int> span = default; _ = new { Span = span }; ", options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,11): error CS0828: Cannot assign 'Span<int>' to anonymous type property // _ = new { Span = span }; Diagnostic(ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, "Span = span").WithArguments("System.Span<int>").WithLocation(5, 11) ); } [Fact] public void Span_02() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; Span<int> outer; for (Span<int> inner = stackalloc int[10];; inner = outer) { outer = inner; } ", options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (7,13): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // outer = inner; Diagnostic(ErrorCode.ERR_EscapeLocal, "inner").WithArguments("inner").WithLocation(7, 13) ); } [Fact] [WorkItem(1179569, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1179569")] public void Issue1179569() { var text1 = @"Task v0123456789012345678901234567() { Console.Write(""start v0123456789012345678901234567""); await Task.Delay(2 * 1000); Console.Write(""end v0123456789012345678901234567""); } Task On01234567890123456() { return v0123456789012345678901234567(); } string return Task.WhenAll( Task.WhenAll(this.c01234567890123456789012345678.Select(v01234567 => On01234567890123456(v01234567))), Task.WhenAll(this.c01234567890123456789.Select(v01234567 => v01234567.U0123456789012345678901234()))); "; var oldTree = Parse(text: text1, options: TestOptions.RegularDefault); var text2 = @"Task v0123456789012345678901234567() { Console.Write(""start v0123456789012345678901234567""); await Task.Delay(2 * 1000); Console.Write(""end v0123456789012345678901234567""); } Task On01234567890123456() { return v0123456789012345678901234567(); } string[ return Task.WhenAll( Task.WhenAll(this.c01234567890123456789012345678.Select(v01234567 => On01234567890123456(v01234567))), Task.WhenAll(this.c01234567890123456789.Select(v01234567 => v01234567.U0123456789012345678901234()))); "; var newText = Microsoft.CodeAnalysis.Text.StringText.From(text2, System.Text.Encoding.UTF8); using var lexer = new Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.Lexer(newText, TestOptions.RegularDefault); using var parser = new Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LanguageParser(lexer, (CSharpSyntaxNode)oldTree.GetRoot(), new[] { new Microsoft.CodeAnalysis.Text.TextChangeRange(new Microsoft.CodeAnalysis.Text.TextSpan(282, 0), 1) }); var compilationUnit = (CompilationUnitSyntax)parser.ParseCompilationUnit().CreateRed(); var tree = CSharpSyntaxTree.Create(compilationUnit, TestOptions.RegularDefault, encoding: System.Text.Encoding.UTF8); Assert.Equal(text2, tree.GetText().ToString()); tree.VerifySource(); var fullParseTree = Parse(text: text2, options: TestOptions.RegularDefault); var nodes1 = tree.GetRoot().DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToArray(); var nodes2 = fullParseTree.GetRoot().DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToArray(); Assert.Equal(nodes1.Length, nodes2.Length); for (int i = 0; i < nodes1.Length; i++) { var node1 = nodes1[i]; var node2 = nodes2[i]; Assert.Equal(node1.RawKind, node2.RawKind); Assert.Equal(node1.Span, node2.Span); Assert.Equal(node1.FullSpan, node2.FullSpan); Assert.Equal(node1.ToString(), node2.ToString()); Assert.Equal(node1.ToFullString(), node2.ToFullString()); } } [Fact] public void TopLevelLocalReferencedInClass_IOperation() { var comp = CreateCompilation(@" int i = 1; class C { void M() /*<bind>*/{ _ = i; }/*</bind>*/ } ", options: TestOptions.ReleaseExe); var diagnostics = new[] { // (2,5): warning CS0219: The variable 'i' is assigned but its value is never used // int i = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(2, 5), // (7,13): error CS8801: Cannot use local variable or local function 'i' declared in a top-level statement in this context. // _ = i; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "i").WithArguments("i").WithLocation(7, 13) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = i') Left: IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'i') ", diagnostics); VerifyFlowGraphForTest<BlockSyntax>(comp, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = i') Left: IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'i') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact] public void TopLevelLocalFunctionReferencedInClass_IOperation() { var comp = CreateCompilation(@" _ = """"; static void M1() {} void M2() {} class C { void M() /*<bind>*/{ M1(); M2(); }/*</bind>*/ } ", options: TestOptions.ReleaseExe); var diagnostics = new[] { // (3,13): warning CS8321: The local function 'M1' is declared but never used // static void M1() {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "M1").WithArguments("M1").WithLocation(3, 13), // (4,6): warning CS8321: The local function 'M2' is declared but never used // void M2() {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "M2").WithArguments("M2").WithLocation(4, 6), // (9,9): error CS8801: Cannot use local variable or local function 'M1' declared in a top-level statement in this context. // M1(); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "M1").WithArguments("M1").WithLocation(9, 9), // (10,9): error CS8801: Cannot use local variable or local function 'M2' declared in a top-level statement in this context. // M2(); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "M2").WithArguments("M2").WithLocation(10, 9) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @" IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M1();') Expression: IInvocationOperation (void M1()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M1()') Instance Receiver: null Arguments(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M2();') Expression: IInvocationOperation (void M2()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) ", diagnostics); VerifyFlowGraphForTest<BlockSyntax>(comp, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M1();') Expression: IInvocationOperation (void M1()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M1()') Instance Receiver: null Arguments(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M2();') Expression: IInvocationOperation (void M2()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact] public void EmptyStatements_01() { var text = @";"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8937: At least one top-level statement must be non-empty. // ; Diagnostic(ErrorCode.ERR_SimpleProgramIsEmpty, ";").WithLocation(1, 1) ); } [Fact] public void EmptyStatements_02() { var text = @";; ;; ;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8937: At least one top-level statement must be non-empty. // ;; Diagnostic(ErrorCode.ERR_SimpleProgramIsEmpty, ";").WithLocation(1, 1) ); } [Fact] public void EmptyStatements_03() { var text = @" System.Console.WriteLine(""Hi!""); ;; ; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatements_04() { var text = @" ;; ; System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatements_05() { var text = @" ; System.Console.WriteLine(""Hi!""); ; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatements_06() { var text = @" using System; ; class Program2 { static void Main(String[] args) {} } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8937: At least one top-level statement must be non-empty. // ; Diagnostic(ErrorCode.ERR_SimpleProgramIsEmpty, ";").WithLocation(3, 1), // (7,17): warning CS7022: The entry point of the program is global code; ignoring 'Program2.Main(string[])' entry point. // static void Main(String[] args) {} Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program2.Main(string[])").WithLocation(7, 17) ); } [Fact] public void SpeakableEntryPoint() { var text = @" System.Console.WriteLine(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All)); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Hi!", sourceSymbolValidator: validate, symbolValidator: validate); Assert.Same(entryPoint, comp.GetEntryPoint(default)); Assert.False(entryPoint.CanBeReferencedByName); Assert.True(entryPoint.ContainingType.CanBeReferencedByName); Assert.Equal("<Main>$", entryPoint.Name); Assert.Equal("Program", entryPoint.ContainingType.Name); Assert.Equal(Accessibility.Internal, entryPoint.ContainingType.DeclaredAccessibility); Assert.Equal(Accessibility.Private, entryPoint.DeclaredAccessibility); void validate(ModuleSymbol module) { bool fromSource = module is SourceModuleSymbol; var program = module.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName); Assert.False(program.IsImplicitlyDeclared); if (fromSource) { Assert.Empty(program.GetAttributes().As<CSharpAttributeData>()); } else { Assert.Equal(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(program.GetAttributes().As<CSharpAttributeData>())); } Assert.Empty(program.GetMethod(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName).GetAttributes()); if (fromSource) { Assert.Equal(new[] { "<top-level-statements-entry-point>", "Program..ctor()" }, program.GetMembers().ToTestDisplayStrings()); } else { Assert.Equal(new[] { "void Program.<Main>$(System.String[] args)", "Program..ctor()" }, program.GetMembers().ToTestDisplayStrings()); } } } [Fact] public void SpeakableEntryPoint_ProgramIsPartial() { var text = @" M(); public partial class Program { private static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All)); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Hi!", sourceSymbolValidator: validate, symbolValidator: validate); Assert.Same(entryPoint, comp.GetEntryPoint(default)); Assert.False(entryPoint.CanBeReferencedByName); Assert.True(entryPoint.ContainingType.CanBeReferencedByName); Assert.Equal("<Main>$", entryPoint.Name); Assert.Equal("Program", entryPoint.ContainingType.Name); Assert.Equal(Accessibility.Public, entryPoint.ContainingType.DeclaredAccessibility); Assert.Equal(Accessibility.Private, entryPoint.DeclaredAccessibility); void validate(ModuleSymbol module) { var program = module.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName); Assert.Empty(program.GetAttributes().As<CSharpAttributeData>()); Assert.False(program.IsImplicitlyDeclared); Assert.Empty(program.GetMethod(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName).GetAttributes().As<CSharpAttributeData>()); } } [Fact] public void SpeakableEntryPoint_ProgramIsNotPartial() { var text = @" M(); public class Program { private static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,14): error CS0260: Missing partial modifier on declaration of type 'Program'; another partial declaration of this type exists // public class Program Diagnostic(ErrorCode.ERR_MissingPartial, "Program").WithArguments("Program").WithLocation(4, 14) ); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); Assert.Same(entryPoint, comp.GetEntryPoint(default)); Assert.False(entryPoint.CanBeReferencedByName); Assert.True(entryPoint.ContainingType.CanBeReferencedByName); Assert.Equal("<Main>$", entryPoint.Name); Assert.Equal("Program", entryPoint.ContainingType.Name); Assert.Equal(Accessibility.Public, entryPoint.ContainingType.DeclaredAccessibility); Assert.Equal(Accessibility.Private, entryPoint.DeclaredAccessibility); } [Fact] public void SpeakableEntryPoint_ProgramIsInternal() { var text = @" M(); internal partial class Program { private static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(text); CompileAndVerify(comp, expectedOutput: "Hi!"); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal(Accessibility.Internal, entryPoint.ContainingType.DeclaredAccessibility); Assert.Equal(Accessibility.Private, entryPoint.DeclaredAccessibility); } [Fact] public void SpeakableEntryPoint_ProgramWithoutDeclaredAccessibility() { var text = @" M(); partial class Program { private static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(text); CompileAndVerify(comp, expectedOutput: "Hi!"); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal(Accessibility.Internal, entryPoint.ContainingType.DeclaredAccessibility); Assert.Equal(Accessibility.Private, entryPoint.DeclaredAccessibility); } [Fact] public void SpeakableEntryPoint_ProgramIsStruct() { var text = @" M(); partial struct Program { private static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,1): error CS0261: Partial declarations of 'Program' must be all classes, all record classes, all structs, all record structs, or all interfaces // M(); Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "M").WithArguments("Program").WithLocation(2, 1), // (2,1): error CS0103: The name 'M' does not exist in the current context // M(); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(2, 1) ); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal(Accessibility.Internal, entryPoint.ContainingType.DeclaredAccessibility); Assert.Equal(Accessibility.Private, entryPoint.DeclaredAccessibility); Assert.True(entryPoint.ContainingType.IsReferenceType); } [Fact] public void SpeakableEntryPoint_ProgramIsRecord() { var text = @" M(); partial record Program { private static void M() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,1): error CS0261: Partial declarations of 'Program' must be all classes, all record classes, all structs, all record structs, or all interfaces // M(); Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "M").WithArguments("Program").WithLocation(2, 1), // (2,1): error CS0103: The name 'M' does not exist in the current context // M(); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(2, 1) ); } [Fact] public void SpeakableEntryPoint_ProgramIsInterface() { var text = @" System.Console.Write(42); partial interface Program { } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,1): error CS0261: Partial declarations of 'Program' must be all classes, all record classes, all structs, all record structs, or all interfaces // System.Console.Write(42); Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "System").WithArguments("Program").WithLocation(2, 1) ); } [Fact] public void SpeakableEntryPoint_ProgramCallsMain() { var text = @" M(args); partial class Program { private static void M(string[] args) { Main(); } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (8,9): error CS0103: The name 'Main' does not exist in the current context // Main(); Diagnostic(ErrorCode.ERR_NameNotInContext, "Main").WithArguments("Main").WithLocation(8, 9) ); } [Fact] public void SpeakableEntryPoint_ProgramHasBaseList() { var text = @" new Program().M(); class Base { public void M() { System.Console.Write(42); } } partial class Program : Base { } "; var comp = CreateCompilation(text); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyDiagnostics(); var entryPoint = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal(Accessibility.Private, entryPoint.DeclaredAccessibility); Assert.True(entryPoint.IsStatic); Assert.Equal("Base", entryPoint.ContainingType.BaseType().ToTestDisplayString()); Assert.Equal(Accessibility.Internal, entryPoint.ContainingType.DeclaredAccessibility); Assert.False(entryPoint.ContainingType.IsStatic); } [Fact] public void SpeakableEntryPoint_ProgramImplementsInterface() { var text = @" ((Interface)new Program()).M(); interface Interface { void M(); } partial class Program : Interface { void Interface.M() { System.Console.Write(42); } } "; var comp = CreateCompilation(text); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyDiagnostics(); } [Fact] public void SpeakableEntryPoint_ProgramIsAbstractPartial() { var text = @" System.Console.Write(42); abstract partial class Program { } "; var comp = CreateCompilation(text); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyDiagnostics(); } [Fact] public void SpeakableEntryPoint_ProgramIsSealedPartial() { var text = @" System.Console.Write(42); sealed partial class Program { } "; var comp = CreateCompilation(text); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyDiagnostics(); } [Fact] public void SpeakableEntryPoint_ProgramIsStaticPartial() { var text = @" System.Console.Write(42); static partial class Program { } "; var comp = CreateCompilation(text); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyDiagnostics(); } [Fact] public void SpeakableEntryPoint_ProgramIsObsolete() { var text = @" System.Console.Write(42); [System.Obsolete(""error"")] public partial class Program { } public class C { public Program f; } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (11,12): warning CS0618: 'Program' is obsolete: 'error' // public Program f; Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "Program").WithArguments("Program", "error").WithLocation(11, 12) ); } [Fact] public void SpeakableEntryPoint_ProgramIsObsolete_UsedWithinProgram() { var text = @" Program p = new Program(); [System.Obsolete(""error"")] public partial class Program { } "; var comp = CreateCompilation(text); comp.VerifyEmitDiagnostics(); } [Fact] public void SpeakableEntryPoint_ProgramHasMain() { var text = @" System.Console.Write(42); partial class Program { public static void Main(string[] args) { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,24): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main(string[])' entry point. // public static void Main(string[] args) { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main(string[])").WithLocation(6, 24) ); } [Fact] public void SpeakableEntryPoint_ProgramHasMain_DifferentSignature() { var text = @" System.Console.Write(42); partial class Program { public static void Main() { } } "; var comp = CreateCompilation(text); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyDiagnostics( // (6,24): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // public static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(6, 24) ); } [Fact] public void SpeakableEntryPoint_ProgramHasBackingField() { var text = @" System.Console.Write(42); partial class Program { public int Property { get; set; } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All)); CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate); comp.VerifyEmitDiagnostics(); void validate(ModuleSymbol module) { bool fromSource = module is SourceModuleSymbol; var field = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").GetField("<Property>k__BackingField"); Assert.False(field.ContainingType.IsImplicitlyDeclared); var fieldAttributes = GetAttributeNames(field.GetAttributes().As<CSharpAttributeData>()); if (fromSource) { Assert.Empty(fieldAttributes); Assert.Equal(new[] { "<top-level-statements-entry-point>", "System.Int32 Program.<Property>k__BackingField", "System.Int32 Program.Property { get; set; }", "System.Int32 Program.Property.get", "void Program.Property.set", "Program..ctor()" }, field.ContainingType.GetMembers().ToTestDisplayStrings()); } else { Assert.Equal(new[] { "CompilerGeneratedAttribute", "DebuggerBrowsableAttribute" }, fieldAttributes); Assert.Equal(new[] { "System.Int32 Program.<Property>k__BackingField", "void Program.<Main>$(System.String[] args)", "System.Int32 Program.Property.get", "void Program.Property.set", "Program..ctor()", "System.Int32 Program.Property { get; set; }" }, field.ContainingType.GetMembers().ToTestDisplayStrings()); } } } [Fact] public void SpeakableEntryPoint_XmlDoc() { var src = @" System.Console.Write(42); "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("Program"); Assert.Equal("", cMember.GetDocumentationCommentXml()); } [Fact] public void SpeakableEntryPoint_XmlDoc_ProgramIsPartial() { var src = @" System.Console.Write(42); /// <summary>Summary</summary> public partial class Program { } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("Program"); Assert.Equal( @"<member name=""T:Program""> <summary>Summary</summary> </member> ", cMember.GetDocumentationCommentXml()); } [Fact] public void SpeakableEntryPoint_XmlDoc_ProgramIsPartial_NotCommented() { var src = @" System.Console.Write(42); public partial class Program { } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (4,22): warning CS1591: Missing XML comment for publicly visible type or member 'Program' // public partial class Program { } Diagnostic(ErrorCode.WRN_MissingXMLComment, "Program").WithArguments("Program").WithLocation(4, 22) ); var cMember = comp.GetMember<NamedTypeSymbol>("Program"); Assert.Equal("", cMember.GetDocumentationCommentXml()); } [Fact] public void SpeakableEntryPoint_TypeOf() { var src = @" C.M(); public class C { public static void M() { System.Console.Write(typeof(Program)); } } "; var comp = CreateCompilation(src); var verifier = CompileAndVerify(comp, expectedOutput: "Program"); verifier.VerifyDiagnostics(); } [Fact] public void Ordering_InFileScopedNamespace_01() { var src = @" namespace NS; System.Console.Write(42); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,16): error CS0116: A namespace cannot directly contain members such as fields, methods or statements // System.Console.Write(42); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Write").WithLocation(3, 16), // (3,22): error CS1026: ) expected // System.Console.Write(42); Diagnostic(ErrorCode.ERR_CloseParenExpected, "42").WithLocation(3, 22), // (3,22): error CS1022: Type or namespace definition, or end-of-file expected // System.Console.Write(42); Diagnostic(ErrorCode.ERR_EOFExpected, "42").WithLocation(3, 22) ); } [Fact] public void Ordering_InFileScopedNamespace_02() { var src = @" namespace NS; var x = 1; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,1): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // var x = 1; Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(3, 1), // (3,5): error CS0116: A namespace cannot directly contain members such as fields, methods or statements // var x = 1; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x").WithLocation(3, 5) ); } [Fact] public void Ordering_AfterNamespace() { var src = @" namespace NS { } var x = 1; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // var x = 1; Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "var x = 1;").WithLocation(6, 1), // (6,5): warning CS0219: The variable 'x' is assigned but its value is never used // var x = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 5) ); } } }
-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/CodeModel/ExternalElements/ExternalCodeClass.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.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeClass))] public sealed class ExternalCodeClass : AbstractExternalCodeType, EnvDTE80.CodeClass2, EnvDTE.CodeClass, EnvDTE.CodeType, EnvDTE.CodeElement, EnvDTE80.CodeElement2 { internal static EnvDTE.CodeClass Create(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) { var newElement = new ExternalCodeClass(state, projectId, typeSymbol); return (EnvDTE.CodeClass)ComAggregate.CreateAggregatedObject(newElement); } private ExternalCodeClass(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) : base(state, projectId, typeSymbol) { } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementClass; } } public EnvDTE80.vsCMClassKind ClassKind { get { return EnvDTE80.vsCMClassKind.vsCMClassKindMainClass; } set { throw Exceptions.ThrowEFail(); } } public EnvDTE80.vsCMDataTypeKind DataTypeKind { get { return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain; } set { throw Exceptions.ThrowEFail(); } } public override EnvDTE.CodeElements ImplementedInterfaces { get { return ExternalTypeCollection.Create(this.State, this, this.ProjectId, TypeSymbol.AllInterfaces); } } public EnvDTE80.vsCMInheritanceKind InheritanceKind { get { if (IsAbstract) { return EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract; } else if (IsSealed) { return EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed; } else { return EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone; } } set { throw Exceptions.ThrowEFail(); } } public new bool IsAbstract { get { return base.IsAbstract; } set { throw new NotImplementedException(); } } public bool IsGeneric { get { return TypeSymbol is INamedTypeSymbol && ((INamedTypeSymbol)TypeSymbol).IsGenericType; } } public EnvDTE.CodeElements PartialClasses { get { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeElements Parts { get { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access, object location) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeInterface AddImplementedInterface(object @base, object position) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeProperty AddProperty(string getterName, string putterName, object type, object position, EnvDTE.vsCMAccess access, object location) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access, object location) => throw Exceptions.ThrowEFail(); public EnvDTE80.CodeEvent AddEvent(string name, string fullDelegateName, bool createPropertyStyleEvent, object location, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public void RemoveInterface(object element) => throw Exceptions.ThrowEFail(); } }
// 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.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeClass))] public sealed class ExternalCodeClass : AbstractExternalCodeType, EnvDTE80.CodeClass2, EnvDTE.CodeClass, EnvDTE.CodeType, EnvDTE.CodeElement, EnvDTE80.CodeElement2 { internal static EnvDTE.CodeClass Create(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) { var newElement = new ExternalCodeClass(state, projectId, typeSymbol); return (EnvDTE.CodeClass)ComAggregate.CreateAggregatedObject(newElement); } private ExternalCodeClass(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) : base(state, projectId, typeSymbol) { } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementClass; } } public EnvDTE80.vsCMClassKind ClassKind { get { return EnvDTE80.vsCMClassKind.vsCMClassKindMainClass; } set { throw Exceptions.ThrowEFail(); } } public EnvDTE80.vsCMDataTypeKind DataTypeKind { get { return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain; } set { throw Exceptions.ThrowEFail(); } } public override EnvDTE.CodeElements ImplementedInterfaces { get { return ExternalTypeCollection.Create(this.State, this, this.ProjectId, TypeSymbol.AllInterfaces); } } public EnvDTE80.vsCMInheritanceKind InheritanceKind { get { if (IsAbstract) { return EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract; } else if (IsSealed) { return EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed; } else { return EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone; } } set { throw Exceptions.ThrowEFail(); } } public new bool IsAbstract { get { return base.IsAbstract; } set { throw new NotImplementedException(); } } public bool IsGeneric { get { return TypeSymbol is INamedTypeSymbol && ((INamedTypeSymbol)TypeSymbol).IsGenericType; } } public EnvDTE.CodeElements PartialClasses { get { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeElements Parts { get { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access, object location) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeInterface AddImplementedInterface(object @base, object position) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeProperty AddProperty(string getterName, string putterName, object type, object position, EnvDTE.vsCMAccess access, object location) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access, object location) => throw Exceptions.ThrowEFail(); public EnvDTE80.CodeEvent AddEvent(string name, string fullDelegateName, bool createPropertyStyleEvent, object location, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public void RemoveInterface(object element) => throw Exceptions.ThrowEFail(); } }
-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/xlf/CompilerExtensionsResources.fr.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../CompilerExtensionsResources.resx"> <body> <trans-unit id="Absolute_path_expected"> <source>Absolute path expected.</source> <target state="translated">Chemin d'accès absolu attendu.</target> <note /> </trans-unit> <trans-unit id="Abstract_Method"> <source>Abstract Method</source> <target state="translated">Méthode abstraite</target> <note>{locked: abstract}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note> </trans-unit> <trans-unit id="An_element_with_the_same_key_but_a_different_value_already_exists"> <source>An element with the same key but a different value already exists.</source> <target state="translated">Il existe déjà un élément utilisant la même clé mais une autre valeur.</target> <note /> </trans-unit> <trans-unit id="Begins_with_I"> <source>Begins with I</source> <target state="translated">Commence par I</target> <note>{locked:I}</note> </trans-unit> <trans-unit id="Class"> <source>Class</source> <target state="new">Class</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Delegate"> <source>Delegate</source> <target state="new">Delegate</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Enum"> <source>Enum</source> <target state="new">Enum</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Event"> <source>Event</source> <target state="new">Event</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Cast_is_redundant"> <source>Cast is redundant.</source> <target state="translated">Cast est redondant.</target> <note /> </trans-unit> <trans-unit id="Expression_level_preferences"> <source>Expression-level preferences</source> <target state="translated">Préférences de niveau expression</target> <note /> </trans-unit> <trans-unit id="Field_preferences"> <source>Field preferences</source> <target state="translated">Préférences de champ</target> <note /> </trans-unit> <trans-unit id="Interface"> <source>Interface</source> <target state="new">Interface</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Language_keywords_vs_BCL_types_preferences"> <source>Language keywords vs BCL types preferences</source> <target state="translated">Préférences des mots clés de langage par rapport aux types BCL</target> <note /> </trans-unit> <trans-unit id="Method"> <source>Method</source> <target state="translated">méthode</target> <note>{locked:method} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Missing_prefix_colon_0"> <source>Missing prefix: '{0}'</source> <target state="translated">Préfixe manquant : '{0}'</target> <note /> </trans-unit> <trans-unit id="Missing_suffix_colon_0"> <source>Missing suffix: '{0}'</source> <target state="translated">Suffixe manquant : '{0}'</target> <note /> </trans-unit> <trans-unit id="Modifier_preferences"> <source>Modifier preferences</source> <target state="translated">Préférences de modificateur</target> <note /> </trans-unit> <trans-unit id="Naming_rules"> <source>Naming rules</source> <target state="translated">Règles de nommage</target> <note /> </trans-unit> <trans-unit id="Naming_styles"> <source>Naming styles</source> <target state="translated">Styles de nommage</target> <note /> </trans-unit> <trans-unit id="New_line_preferences"> <source>New line preferences</source> <target state="translated">Préférences de nouvelle ligne</target> <note /> </trans-unit> <trans-unit id="Non_Field_Members"> <source>Non-Field Members</source> <target state="translated">Membres autres que des champs</target> <note>{locked:field}</note> </trans-unit> <trans-unit id="Organize_usings"> <source>Organize usings</source> <target state="translated">Organiser les instructions Using</target> <note /> </trans-unit> <trans-unit id="Parameter_preferences"> <source>Parameter preferences</source> <target state="translated">Préférences de paramètre</target> <note /> </trans-unit> <trans-unit id="Parentheses_preferences"> <source>Parentheses preferences</source> <target state="translated">Préférences de parenthèses</target> <note /> </trans-unit> <trans-unit id="Pascal_Case"> <source>Pascal Case</source> <target state="translated">Casse Pascal</target> <note /> </trans-unit> <trans-unit id="Prefix_0_does_not_match_expected_prefix_1"> <source>Prefix '{0}' does not match expected prefix '{1}'</source> <target state="translated">Le préfixe « {0} » ne correspond pas au préfixe attendu « {1} »</target> <note /> </trans-unit> <trans-unit id="Prefix_0_is_not_expected"> <source>Prefix '{0}' is not expected</source> <target state="translated">Le préfixe « {0} » n'est pas attendu</target> <note /> </trans-unit> <trans-unit id="Private_Method"> <source>Private Method</source> <target state="translated">Méthode privée</target> <note>{locked: private}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note> </trans-unit> <trans-unit id="Private_or_Internal_Field"> <source>Private or Internal Field</source> <target state="translated">Champ privé ou interne</target> <note>{locked: private}{locked: internal}{locked:field}</note> </trans-unit> <trans-unit id="Private_or_Internal_Static_Field"> <source>Private or Internal Static Field</source> <target state="translated">Champ statique privé ou interne</target> <note>{locked: private}{locked: internal}{locked:static}{locked:field}</note> </trans-unit> <trans-unit id="Property"> <source>Property</source> <target state="new">Property</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Public_or_Protected_Field"> <source>Public or Protected Field</source> <target state="translated">Champ public ou protégé</target> <note>{locked: public}{locked: protected}{locked:field}</note> </trans-unit> <trans-unit id="Segment_size_must_be_power_of_2_greater_than_1"> <source>Segment size must be power of 2 greater than 1</source> <target state="translated">La taille du segment doit être une puissance de 2 supérieure à 1</target> <note /> </trans-unit> <trans-unit id="Specified_sequence_has_duplicate_items"> <source>Specified sequence has duplicate items</source> <target state="translated">La séquence spécifiée comporte des éléments dupliqués</target> <note /> </trans-unit> <trans-unit id="Static_Field"> <source>Static Field</source> <target state="translated">Champ statique</target> <note>{locked:static}{locked:field} (unless the capitalization should be handled differently)</note> </trans-unit> <trans-unit id="Static_Method"> <source>Static Method</source> <target state="translated">Méthode statique</target> <note>{locked: static}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note> </trans-unit> <trans-unit id="Struct"> <source>Struct</source> <target state="new">Struct</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Suppression_preferences"> <source>Suppression preferences</source> <target state="translated">Préférences de suppression</target> <note /> </trans-unit> <trans-unit id="Symbol_specifications"> <source>Symbol specifications</source> <target state="translated">Spécifications de symboles</target> <note /> </trans-unit> <trans-unit id="The_first_word_0_must_begin_with_a_lower_case_character"> <source>The first word, '{0}', must begin with a lower case character</source> <target state="translated">Le premier mot, '{0}', doit commencer par une lettre minuscule</target> <note /> </trans-unit> <trans-unit id="The_first_word_0_must_begin_with_an_upper_case_character"> <source>The first word, '{0}', must begin with an upper case character</source> <target state="translated">Le premier mot, '{0}', doit commencer par une lettre majuscule</target> <note /> </trans-unit> <trans-unit id="These_non_leading_words_must_begin_with_a_lowercase_letter_colon_0"> <source>These non-leading words must begin with a lowercase letter: {0}</source> <target state="translated">Les mots suivants, non placés au début, doivent commencer par une lettre minuscule : {0}</target> <note /> </trans-unit> <trans-unit id="These_non_leading_words_must_begin_with_an_upper_case_letter_colon_0"> <source>These non-leading words must begin with an upper case letter: {0}</source> <target state="translated">Les mots suivants, non placés au début, doivent commencer par une lettre majuscule : {0}</target> <note /> </trans-unit> <trans-unit id="These_words_cannot_contain_lower_case_characters_colon_0"> <source>These words cannot contain lower case characters: {0}</source> <target state="translated">Les mots suivants ne peuvent pas contenir de lettres minuscules : {0}</target> <note /> </trans-unit> <trans-unit id="These_words_cannot_contain_upper_case_characters_colon_0"> <source>These words cannot contain upper case characters: {0}</source> <target state="translated">Les mots suivants ne peuvent pas contenir de lettres majuscules : {0}</target> <note /> </trans-unit> <trans-unit id="These_words_must_begin_with_upper_case_characters_colon_0"> <source>These words must begin with upper case characters: {0}</source> <target state="translated">Les mots suivants doivent commencer par des lettres majuscules : {0}</target> <note /> </trans-unit> <trans-unit id="Types"> <source>Types</source> <target state="translated">Types</target> <note>{locked:types} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="this_dot_and_Me_dot_preferences"> <source>this. and Me. preferences</source> <target state="translated">Préférences de this. et Me.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../CompilerExtensionsResources.resx"> <body> <trans-unit id="Absolute_path_expected"> <source>Absolute path expected.</source> <target state="translated">Chemin d'accès absolu attendu.</target> <note /> </trans-unit> <trans-unit id="Abstract_Method"> <source>Abstract Method</source> <target state="translated">Méthode abstraite</target> <note>{locked: abstract}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note> </trans-unit> <trans-unit id="An_element_with_the_same_key_but_a_different_value_already_exists"> <source>An element with the same key but a different value already exists.</source> <target state="translated">Il existe déjà un élément utilisant la même clé mais une autre valeur.</target> <note /> </trans-unit> <trans-unit id="Begins_with_I"> <source>Begins with I</source> <target state="translated">Commence par I</target> <note>{locked:I}</note> </trans-unit> <trans-unit id="Class"> <source>Class</source> <target state="new">Class</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Delegate"> <source>Delegate</source> <target state="new">Delegate</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Enum"> <source>Enum</source> <target state="new">Enum</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Event"> <source>Event</source> <target state="new">Event</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Cast_is_redundant"> <source>Cast is redundant.</source> <target state="translated">Cast est redondant.</target> <note /> </trans-unit> <trans-unit id="Expression_level_preferences"> <source>Expression-level preferences</source> <target state="translated">Préférences de niveau expression</target> <note /> </trans-unit> <trans-unit id="Field_preferences"> <source>Field preferences</source> <target state="translated">Préférences de champ</target> <note /> </trans-unit> <trans-unit id="Interface"> <source>Interface</source> <target state="new">Interface</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Language_keywords_vs_BCL_types_preferences"> <source>Language keywords vs BCL types preferences</source> <target state="translated">Préférences des mots clés de langage par rapport aux types BCL</target> <note /> </trans-unit> <trans-unit id="Method"> <source>Method</source> <target state="translated">méthode</target> <note>{locked:method} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Missing_prefix_colon_0"> <source>Missing prefix: '{0}'</source> <target state="translated">Préfixe manquant : '{0}'</target> <note /> </trans-unit> <trans-unit id="Missing_suffix_colon_0"> <source>Missing suffix: '{0}'</source> <target state="translated">Suffixe manquant : '{0}'</target> <note /> </trans-unit> <trans-unit id="Modifier_preferences"> <source>Modifier preferences</source> <target state="translated">Préférences de modificateur</target> <note /> </trans-unit> <trans-unit id="Naming_rules"> <source>Naming rules</source> <target state="translated">Règles de nommage</target> <note /> </trans-unit> <trans-unit id="Naming_styles"> <source>Naming styles</source> <target state="translated">Styles de nommage</target> <note /> </trans-unit> <trans-unit id="New_line_preferences"> <source>New line preferences</source> <target state="translated">Préférences de nouvelle ligne</target> <note /> </trans-unit> <trans-unit id="Non_Field_Members"> <source>Non-Field Members</source> <target state="translated">Membres autres que des champs</target> <note>{locked:field}</note> </trans-unit> <trans-unit id="Organize_usings"> <source>Organize usings</source> <target state="translated">Organiser les instructions Using</target> <note /> </trans-unit> <trans-unit id="Parameter_preferences"> <source>Parameter preferences</source> <target state="translated">Préférences de paramètre</target> <note /> </trans-unit> <trans-unit id="Parentheses_preferences"> <source>Parentheses preferences</source> <target state="translated">Préférences de parenthèses</target> <note /> </trans-unit> <trans-unit id="Pascal_Case"> <source>Pascal Case</source> <target state="translated">Casse Pascal</target> <note /> </trans-unit> <trans-unit id="Prefix_0_does_not_match_expected_prefix_1"> <source>Prefix '{0}' does not match expected prefix '{1}'</source> <target state="translated">Le préfixe « {0} » ne correspond pas au préfixe attendu « {1} »</target> <note /> </trans-unit> <trans-unit id="Prefix_0_is_not_expected"> <source>Prefix '{0}' is not expected</source> <target state="translated">Le préfixe « {0} » n'est pas attendu</target> <note /> </trans-unit> <trans-unit id="Private_Method"> <source>Private Method</source> <target state="translated">Méthode privée</target> <note>{locked: private}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note> </trans-unit> <trans-unit id="Private_or_Internal_Field"> <source>Private or Internal Field</source> <target state="translated">Champ privé ou interne</target> <note>{locked: private}{locked: internal}{locked:field}</note> </trans-unit> <trans-unit id="Private_or_Internal_Static_Field"> <source>Private or Internal Static Field</source> <target state="translated">Champ statique privé ou interne</target> <note>{locked: private}{locked: internal}{locked:static}{locked:field}</note> </trans-unit> <trans-unit id="Property"> <source>Property</source> <target state="new">Property</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Public_or_Protected_Field"> <source>Public or Protected Field</source> <target state="translated">Champ public ou protégé</target> <note>{locked: public}{locked: protected}{locked:field}</note> </trans-unit> <trans-unit id="Segment_size_must_be_power_of_2_greater_than_1"> <source>Segment size must be power of 2 greater than 1</source> <target state="translated">La taille du segment doit être une puissance de 2 supérieure à 1</target> <note /> </trans-unit> <trans-unit id="Specified_sequence_has_duplicate_items"> <source>Specified sequence has duplicate items</source> <target state="translated">La séquence spécifiée comporte des éléments dupliqués</target> <note /> </trans-unit> <trans-unit id="Static_Field"> <source>Static Field</source> <target state="translated">Champ statique</target> <note>{locked:static}{locked:field} (unless the capitalization should be handled differently)</note> </trans-unit> <trans-unit id="Static_Method"> <source>Static Method</source> <target state="translated">Méthode statique</target> <note>{locked: static}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note> </trans-unit> <trans-unit id="Struct"> <source>Struct</source> <target state="new">Struct</target> <note>{locked} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="Suppression_preferences"> <source>Suppression preferences</source> <target state="translated">Préférences de suppression</target> <note /> </trans-unit> <trans-unit id="Symbol_specifications"> <source>Symbol specifications</source> <target state="translated">Spécifications de symboles</target> <note /> </trans-unit> <trans-unit id="The_first_word_0_must_begin_with_a_lower_case_character"> <source>The first word, '{0}', must begin with a lower case character</source> <target state="translated">Le premier mot, '{0}', doit commencer par une lettre minuscule</target> <note /> </trans-unit> <trans-unit id="The_first_word_0_must_begin_with_an_upper_case_character"> <source>The first word, '{0}', must begin with an upper case character</source> <target state="translated">Le premier mot, '{0}', doit commencer par une lettre majuscule</target> <note /> </trans-unit> <trans-unit id="These_non_leading_words_must_begin_with_a_lowercase_letter_colon_0"> <source>These non-leading words must begin with a lowercase letter: {0}</source> <target state="translated">Les mots suivants, non placés au début, doivent commencer par une lettre minuscule : {0}</target> <note /> </trans-unit> <trans-unit id="These_non_leading_words_must_begin_with_an_upper_case_letter_colon_0"> <source>These non-leading words must begin with an upper case letter: {0}</source> <target state="translated">Les mots suivants, non placés au début, doivent commencer par une lettre majuscule : {0}</target> <note /> </trans-unit> <trans-unit id="These_words_cannot_contain_lower_case_characters_colon_0"> <source>These words cannot contain lower case characters: {0}</source> <target state="translated">Les mots suivants ne peuvent pas contenir de lettres minuscules : {0}</target> <note /> </trans-unit> <trans-unit id="These_words_cannot_contain_upper_case_characters_colon_0"> <source>These words cannot contain upper case characters: {0}</source> <target state="translated">Les mots suivants ne peuvent pas contenir de lettres majuscules : {0}</target> <note /> </trans-unit> <trans-unit id="These_words_must_begin_with_upper_case_characters_colon_0"> <source>These words must begin with upper case characters: {0}</source> <target state="translated">Les mots suivants doivent commencer par des lettres majuscules : {0}</target> <note /> </trans-unit> <trans-unit id="Types"> <source>Types</source> <target state="translated">Types</target> <note>{locked:types} unless the capitalization should be handled differently</note> </trans-unit> <trans-unit id="this_dot_and_Me_dot_preferences"> <source>this. and Me. preferences</source> <target state="translated">Préférences de this. et Me.</target> <note /> </trans-unit> </body> </file> </xliff>
-1