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,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/LiveShare/Impl/Client/Projects/IRemoteProjectInfoProvider.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Projects { internal interface IRemoteProjectInfoProvider { Task<ImmutableArray<ProjectInfo>> GetRemoteProjectInfosAsync(CancellationToken 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.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Projects { internal interface IRemoteProjectInfoProvider { Task<ImmutableArray<ProjectInfo>> GetRemoteProjectInfosAsync(CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Xaml/Impl/xlf/Resources.zh-Hant.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="zh-Hant" original="../Resources.resx"> <body> <trans-unit id="RemoveAndSortNamespacesWithAccelerator"> <source>Remove &amp;and Sort Namespaces</source> <target state="translated">移除並排序命名空間(&amp;A)</target> <note /> </trans-unit> <trans-unit id="RemoveUnnecessaryNamespaces"> <source>Remove Unnecessary Namespaces</source> <target state="translated">移除不需要的命名空間</target> <note /> </trans-unit> <trans-unit id="Sort_Namespaces"> <source>&amp;Sort Namespaces</source> <target state="translated">排序 Namespace(&amp;S)</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="zh-Hant" original="../Resources.resx"> <body> <trans-unit id="RemoveAndSortNamespacesWithAccelerator"> <source>Remove &amp;and Sort Namespaces</source> <target state="translated">移除並排序命名空間(&amp;A)</target> <note /> </trans-unit> <trans-unit id="RemoveUnnecessaryNamespaces"> <source>Remove Unnecessary Namespaces</source> <target state="translated">移除不需要的命名空間</target> <note /> </trans-unit> <trans-unit id="Sort_Namespaces"> <source>&amp;Sort Namespaces</source> <target state="translated">排序 Namespace(&amp;S)</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicExtractMethod.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; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; 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 BasicExtractMethod : AbstractEditorTest { private const string TestSource = @" Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine(""Hello VB!"") End Sub Function F() As Integer Dim a As Integer Dim b As Integer a = 5 b = 5 Dim result = a * b Return result End Function End Module"; protected override string LanguageName => LanguageNames.VisualBasic; public BasicExtractMethod(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicExtractMethod)) { } [WpfFact] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] public void SimpleExtractMethod() { VisualStudio.Editor.SetText(TestSource); VisualStudio.Editor.PlaceCaret("Console", charsOffset: -1); VisualStudio.Editor.PlaceCaret("Hello VB!", charsOffset: 3, extendSelection: true); VisualStudio.ExecuteCommand(WellKnownCommandNames.Refactor_ExtractMethod); var expectedMarkup = @" Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) [|NewMethod|]() End Sub Private Sub [|NewMethod|]() Console.WriteLine(""Hello VB!"") End Sub Function F() As Integer Dim a As Integer Dim b As Integer a = 5 b = 5 Dim result = a * b Return result End Function End Module"; MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out ImmutableArray<TextSpan> spans); VisualStudio.Editor.Verify.TextContains(expectedText); AssertEx.SetEqual(spans, VisualStudio.Editor.GetTagSpans(VisualStudio.InlineRenameDialog.ValidRenameTag)); VisualStudio.Editor.SendKeys("SayHello", VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@" Private Sub SayHello() Console.WriteLine(""Hello VB!"") End Sub"); } [WpfFact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public void ExtractViaCodeAction() { VisualStudio.Editor.SetText(TestSource); VisualStudio.Editor.PlaceCaret("a = 5", charsOffset: -1); VisualStudio.Editor.PlaceCaret("a * b", charsOffset: 1, extendSelection: true); VisualStudio.Editor.Verify.CodeAction("Extract method", applyFix: true, blockUntilComplete: true); var expectedMarkup = @" Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine(""Hello VB!"") End Sub Function F() As Integer Dim a As Integer Dim b As Integer Dim result As Integer = Nothing [|NewMethod|](a, b, result) Return result End Function Private Sub [|NewMethod|](ByRef a As Integer, ByRef b As Integer, ByRef result As Integer) a = 5 b = 5 result = a * b End Sub End Module"; MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out ImmutableArray<TextSpan> spans); Assert.Equal(expectedText, VisualStudio.Editor.GetText()); AssertEx.SetEqual(spans, VisualStudio.Editor.GetTagSpans(VisualStudio.InlineRenameDialog.ValidRenameTag)); } } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; 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 BasicExtractMethod : AbstractEditorTest { private const string TestSource = @" Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine(""Hello VB!"") End Sub Function F() As Integer Dim a As Integer Dim b As Integer a = 5 b = 5 Dim result = a * b Return result End Function End Module"; protected override string LanguageName => LanguageNames.VisualBasic; public BasicExtractMethod(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicExtractMethod)) { } [WpfFact] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] public void SimpleExtractMethod() { VisualStudio.Editor.SetText(TestSource); VisualStudio.Editor.PlaceCaret("Console", charsOffset: -1); VisualStudio.Editor.PlaceCaret("Hello VB!", charsOffset: 3, extendSelection: true); VisualStudio.ExecuteCommand(WellKnownCommandNames.Refactor_ExtractMethod); var expectedMarkup = @" Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) [|NewMethod|]() End Sub Private Sub [|NewMethod|]() Console.WriteLine(""Hello VB!"") End Sub Function F() As Integer Dim a As Integer Dim b As Integer a = 5 b = 5 Dim result = a * b Return result End Function End Module"; MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out ImmutableArray<TextSpan> spans); VisualStudio.Editor.Verify.TextContains(expectedText); AssertEx.SetEqual(spans, VisualStudio.Editor.GetTagSpans(VisualStudio.InlineRenameDialog.ValidRenameTag)); VisualStudio.Editor.SendKeys("SayHello", VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@" Private Sub SayHello() Console.WriteLine(""Hello VB!"") End Sub"); } [WpfFact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public void ExtractViaCodeAction() { VisualStudio.Editor.SetText(TestSource); VisualStudio.Editor.PlaceCaret("a = 5", charsOffset: -1); VisualStudio.Editor.PlaceCaret("a * b", charsOffset: 1, extendSelection: true); VisualStudio.Editor.Verify.CodeAction("Extract method", applyFix: true, blockUntilComplete: true); var expectedMarkup = @" Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine(""Hello VB!"") End Sub Function F() As Integer Dim a As Integer Dim b As Integer Dim result As Integer = Nothing [|NewMethod|](a, b, result) Return result End Function Private Sub [|NewMethod|](ByRef a As Integer, ByRef b As Integer, ByRef result As Integer) a = 5 b = 5 result = a * b End Sub End Module"; MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out ImmutableArray<TextSpan> spans); Assert.Equal(expectedText, VisualStudio.Editor.GetText()); AssertEx.SetEqual(spans, VisualStudio.Editor.GetTagSpans(VisualStudio.InlineRenameDialog.ValidRenameTag)); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Test/Core/TempFiles/TempFile.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.Immutable; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using System.Text; using System.Diagnostics; using Roslyn.Utilities; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Test.Utilities { public class TempFile { private readonly string _path; internal TempFile(string path) { Debug.Assert(PathUtilities.IsAbsolute(path)); _path = path; } internal TempFile(string prefix, string extension, string directory, string callerSourcePath, int callerLineNumber) { while (true) { if (prefix == null) { prefix = System.IO.Path.GetFileName(callerSourcePath) + "_" + callerLineNumber.ToString() + "_"; } _path = System.IO.Path.Combine(directory ?? TempRoot.Root, prefix + Guid.NewGuid() + (extension ?? ".tmp")); try { TempRoot.CreateStream(_path, FileMode.CreateNew); break; } catch (PathTooLongException) { throw; } catch (DirectoryNotFoundException) { throw; } catch (IOException) { // retry } } } public FileStream Open(FileAccess access = FileAccess.ReadWrite) { return new FileStream(_path, FileMode.Open, access); } public string Path { get { return _path; } } public TempFile WriteAllText(string content, Encoding encoding) { File.WriteAllText(_path, content, encoding); return this; } public TempFile WriteAllText(string content) { File.WriteAllText(_path, content); return this; } public async Task<TempFile> WriteAllTextAsync(string content, Encoding encoding) { using (var sw = new StreamWriter(File.Create(_path), encoding)) { await sw.WriteAsync(content).ConfigureAwait(false); } return this; } public Task<TempFile> WriteAllTextAsync(string content) { return WriteAllTextAsync(content, Encoding.UTF8); } public TempFile WriteAllBytes(byte[] content) { File.WriteAllBytes(_path, content); return this; } public TempFile WriteAllBytes(ImmutableArray<byte> content) { content.WriteToFile(_path); return this; } public string ReadAllText() { return File.ReadAllText(_path); } public byte[] ReadAllBytes() { return File.ReadAllBytes(_path); } public TempFile CopyContentFrom(string path) { return WriteAllBytes(File.ReadAllBytes(path)); } public override string ToString() { return _path; } } }
// Licensed to the .NET Foundation under one or more 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.Immutable; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using System.Text; using System.Diagnostics; using Roslyn.Utilities; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Test.Utilities { public class TempFile { private readonly string _path; internal TempFile(string path) { Debug.Assert(PathUtilities.IsAbsolute(path)); _path = path; } internal TempFile(string prefix, string extension, string directory, string callerSourcePath, int callerLineNumber) { while (true) { if (prefix == null) { prefix = System.IO.Path.GetFileName(callerSourcePath) + "_" + callerLineNumber.ToString() + "_"; } _path = System.IO.Path.Combine(directory ?? TempRoot.Root, prefix + Guid.NewGuid() + (extension ?? ".tmp")); try { TempRoot.CreateStream(_path, FileMode.CreateNew); break; } catch (PathTooLongException) { throw; } catch (DirectoryNotFoundException) { throw; } catch (IOException) { // retry } } } public FileStream Open(FileAccess access = FileAccess.ReadWrite) { return new FileStream(_path, FileMode.Open, access); } public string Path { get { return _path; } } public TempFile WriteAllText(string content, Encoding encoding) { File.WriteAllText(_path, content, encoding); return this; } public TempFile WriteAllText(string content) { File.WriteAllText(_path, content); return this; } public async Task<TempFile> WriteAllTextAsync(string content, Encoding encoding) { using (var sw = new StreamWriter(File.Create(_path), encoding)) { await sw.WriteAsync(content).ConfigureAwait(false); } return this; } public Task<TempFile> WriteAllTextAsync(string content) { return WriteAllTextAsync(content, Encoding.UTF8); } public TempFile WriteAllBytes(byte[] content) { File.WriteAllBytes(_path, content); return this; } public TempFile WriteAllBytes(ImmutableArray<byte> content) { content.WriteToFile(_path); return this; } public string ReadAllText() { return File.ReadAllText(_path); } public byte[] ReadAllBytes() { return File.ReadAllBytes(_path); } public TempFile CopyContentFrom(string path) { return WriteAllBytes(File.ReadAllBytes(path)); } public override string ToString() { return _path; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicSquigglesDesktop.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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicSquigglesDesktop : BasicSquigglesCommon { public BasicSquigglesDesktop(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.ClassLibrary) { } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public override void VerifySyntaxErrorSquiggles() { base.VerifySyntaxErrorSquiggles(); } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public override void VerifySemanticErrorSquiggles() { base.VerifySemanticErrorSquiggles(); } } }
// Licensed to the .NET Foundation under one or more 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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicSquigglesDesktop : BasicSquigglesCommon { public BasicSquigglesDesktop(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.ClassLibrary) { } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public override void VerifySyntaxErrorSquiggles() { base.VerifySyntaxErrorSquiggles(); } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] public override void VerifySemanticErrorSquiggles() { base.VerifySemanticErrorSquiggles(); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/VisualBasic/Portable/GoToDefinition/VisualBasicGoToDefinitionSymbolService.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.GoToDefinition Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.GoToDefinition <ExportLanguageService(GetType(IGoToDefinitionSymbolService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicGoToDefinitionSymbolService Inherits AbstractGoToDefinitionSymbolService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function FindRelatedExplicitlyDeclaredSymbol(symbol As ISymbol, compilation As Compilation) As ISymbol Return symbol.FindRelatedExplicitlyDeclaredSymbol(compilation) End Function Protected Overrides Function GetTargetPositionIfControlFlow(semanticModel As SemanticModel, token As SyntaxToken) As Integer? Dim node = token.GetRequiredParent() If token.IsKind(SyntaxKind.ReturnKeyword, SyntaxKind.YieldKeyword) Then Return FindContainingReturnableConstruct(node).GetFirstToken().Span.Start End If Dim continueTarget = TryGetContinueTarget(node) If continueTarget IsNot Nothing Then Return continueTarget.GetFirstToken().Span.Start End If Dim exitTarget = TryGetExitTarget(node) If exitTarget IsNot Nothing Then Select Case node.Kind() Case SyntaxKind.ExitSubStatement Case SyntaxKind.ExitFunctionStatement Case SyntaxKind.ExitPropertyStatement Dim Symbol = semanticModel.GetDeclaredSymbol(exitTarget) Return Symbol.Locations.FirstOrNone().SourceSpan.Start End Select ' Exit Select, Exit While, Exit For, Exit ForEach, ... Return exitTarget.GetLastToken().Span.End End If Return Nothing End Function Private Shared Function TryGetExitTarget(node As SyntaxNode) As SyntaxNode Select Case node.Kind() Case SyntaxKind.ExitSelectStatement Return FindContainingSelect(node) Case SyntaxKind.ExitWhileStatement Return FindContainingWhile(node) Case SyntaxKind.ExitForStatement Return FindContainingFor(node) Case SyntaxKind.ExitDoStatement Return FindContainingDoLoop(node) Case SyntaxKind.ExitTryStatement Return FindContainingTry(node) Case SyntaxKind.ExitPropertyStatement Return FindContainingReturnableConstruct(node) Case SyntaxKind.ExitSubStatement Return FindContainingReturnableConstruct(node) Case SyntaxKind.ExitFunctionStatement Return FindContainingReturnableConstruct(node) End Select Return Nothing End Function Private Shared Function TryGetContinueTarget(node As SyntaxNode) As SyntaxNode Select Case node.Kind() Case SyntaxKind.ContinueWhileStatement Return FindContainingWhile(node) Case SyntaxKind.ContinueForStatement Return FindContainingFor(node) Case SyntaxKind.ContinueDoStatement Return FindContainingDoLoop(node) End Select Return Nothing End Function Private Shared Function FindContainingSelect(node As SyntaxNode) As SyntaxNode While node IsNot Nothing AndAlso Not node.IsKind(SyntaxKind.SelectBlock) node = node.Parent If node.IsReturnableConstruct() Then Return Nothing End If End While Return node End Function Private Shared Function FindContainingWhile(node As SyntaxNode) As SyntaxNode While node IsNot Nothing AndAlso Not node.IsKind(SyntaxKind.WhileBlock) node = node.Parent If node.IsReturnableConstruct() Then Return Nothing End If End While Return node End Function Private Shared Function FindContainingFor(node As SyntaxNode) As SyntaxNode While node IsNot Nothing AndAlso Not node.IsKind(SyntaxKind.ForBlock, SyntaxKind.ForEachBlock) node = node.Parent If node.IsReturnableConstruct() Then Return Nothing End If End While Return node End Function Private Shared Function FindContainingDoLoop(node As SyntaxNode) As SyntaxNode While node IsNot Nothing AndAlso Not node.IsKind(SyntaxKind.DoLoopUntilBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoWhileLoopBlock) node = node.Parent If node.IsReturnableConstruct() Then Return Nothing End If End While Return node End Function Private Shared Function FindContainingTry(node As SyntaxNode) As SyntaxNode While node IsNot Nothing AndAlso Not node.IsKind(SyntaxKind.TryBlock) node = node.Parent If node.IsReturnableConstruct() Then Return Nothing End If End While Return node End Function Private Shared Function FindContainingReturnableConstruct(node As SyntaxNode) As SyntaxNode While node IsNot Nothing AndAlso Not node.IsReturnableConstruct() node = node.Parent If node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock) Then Return Nothing End If End While Return node 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.Composition Imports Microsoft.CodeAnalysis.GoToDefinition Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.GoToDefinition <ExportLanguageService(GetType(IGoToDefinitionSymbolService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicGoToDefinitionSymbolService Inherits AbstractGoToDefinitionSymbolService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function FindRelatedExplicitlyDeclaredSymbol(symbol As ISymbol, compilation As Compilation) As ISymbol Return symbol.FindRelatedExplicitlyDeclaredSymbol(compilation) End Function Protected Overrides Function GetTargetPositionIfControlFlow(semanticModel As SemanticModel, token As SyntaxToken) As Integer? Dim node = token.GetRequiredParent() If token.IsKind(SyntaxKind.ReturnKeyword, SyntaxKind.YieldKeyword) Then Return FindContainingReturnableConstruct(node).GetFirstToken().Span.Start End If Dim continueTarget = TryGetContinueTarget(node) If continueTarget IsNot Nothing Then Return continueTarget.GetFirstToken().Span.Start End If Dim exitTarget = TryGetExitTarget(node) If exitTarget IsNot Nothing Then Select Case node.Kind() Case SyntaxKind.ExitSubStatement Case SyntaxKind.ExitFunctionStatement Case SyntaxKind.ExitPropertyStatement Dim Symbol = semanticModel.GetDeclaredSymbol(exitTarget) Return Symbol.Locations.FirstOrNone().SourceSpan.Start End Select ' Exit Select, Exit While, Exit For, Exit ForEach, ... Return exitTarget.GetLastToken().Span.End End If Return Nothing End Function Private Shared Function TryGetExitTarget(node As SyntaxNode) As SyntaxNode Select Case node.Kind() Case SyntaxKind.ExitSelectStatement Return FindContainingSelect(node) Case SyntaxKind.ExitWhileStatement Return FindContainingWhile(node) Case SyntaxKind.ExitForStatement Return FindContainingFor(node) Case SyntaxKind.ExitDoStatement Return FindContainingDoLoop(node) Case SyntaxKind.ExitTryStatement Return FindContainingTry(node) Case SyntaxKind.ExitPropertyStatement Return FindContainingReturnableConstruct(node) Case SyntaxKind.ExitSubStatement Return FindContainingReturnableConstruct(node) Case SyntaxKind.ExitFunctionStatement Return FindContainingReturnableConstruct(node) End Select Return Nothing End Function Private Shared Function TryGetContinueTarget(node As SyntaxNode) As SyntaxNode Select Case node.Kind() Case SyntaxKind.ContinueWhileStatement Return FindContainingWhile(node) Case SyntaxKind.ContinueForStatement Return FindContainingFor(node) Case SyntaxKind.ContinueDoStatement Return FindContainingDoLoop(node) End Select Return Nothing End Function Private Shared Function FindContainingSelect(node As SyntaxNode) As SyntaxNode While node IsNot Nothing AndAlso Not node.IsKind(SyntaxKind.SelectBlock) node = node.Parent If node.IsReturnableConstruct() Then Return Nothing End If End While Return node End Function Private Shared Function FindContainingWhile(node As SyntaxNode) As SyntaxNode While node IsNot Nothing AndAlso Not node.IsKind(SyntaxKind.WhileBlock) node = node.Parent If node.IsReturnableConstruct() Then Return Nothing End If End While Return node End Function Private Shared Function FindContainingFor(node As SyntaxNode) As SyntaxNode While node IsNot Nothing AndAlso Not node.IsKind(SyntaxKind.ForBlock, SyntaxKind.ForEachBlock) node = node.Parent If node.IsReturnableConstruct() Then Return Nothing End If End While Return node End Function Private Shared Function FindContainingDoLoop(node As SyntaxNode) As SyntaxNode While node IsNot Nothing AndAlso Not node.IsKind(SyntaxKind.DoLoopUntilBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoWhileLoopBlock) node = node.Parent If node.IsReturnableConstruct() Then Return Nothing End If End While Return node End Function Private Shared Function FindContainingTry(node As SyntaxNode) As SyntaxNode While node IsNot Nothing AndAlso Not node.IsKind(SyntaxKind.TryBlock) node = node.Parent If node.IsReturnableConstruct() Then Return Nothing End If End While Return node End Function Private Shared Function FindContainingReturnableConstruct(node As SyntaxNode) As SyntaxNode While node IsNot Nothing AndAlso Not node.IsReturnableConstruct() node = node.Parent If node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock) Then Return Nothing End If End While Return node End Function End Class End Namespace
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Def/Implementation/Extensions/SnapshotSpanExtensions.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.Editor.Shared.Extensions; using Microsoft.VisualStudio.Text; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Extensions { internal static class SnapshotSpanExtensions { public static VsTextSpan ToVsTextSpan(this SnapshotSpan snapshotSpan) { snapshotSpan.GetLinesAndCharacters(out var startLine, out var startCharacterIndex, out var endLine, out var endCharacterIndex); return new VsTextSpan() { iStartLine = startLine, iStartIndex = startCharacterIndex, iEndLine = endLine, iEndIndex = endCharacterIndex }; } } }
// Licensed to the .NET Foundation under one or more 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.Editor.Shared.Extensions; using Microsoft.VisualStudio.Text; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Extensions { internal static class SnapshotSpanExtensions { public static VsTextSpan ToVsTextSpan(this SnapshotSpan snapshotSpan) { snapshotSpan.GetLinesAndCharacters(out var startLine, out var startCharacterIndex, out var endLine, out var endCharacterIndex); return new VsTextSpan() { iStartLine = startLine, iStartIndex = startCharacterIndex, iEndLine = endLine, iEndIndex = endCharacterIndex }; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Dependencies/Collections/ImmutableSegmentedList`1+ValueBuilder.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; using System.Collections.Generic; using Microsoft.CodeAnalysis.Collections.Internal; namespace Microsoft.CodeAnalysis.Collections { internal partial struct ImmutableSegmentedList<T> { private struct ValueBuilder : IList<T>, IReadOnlyList<T>, IList { /// <summary> /// The immutable collection this builder is based on. /// </summary> private ImmutableSegmentedList<T> _list; /// <summary> /// The current mutable collection this builder is operating on. This field is initialized to a copy of /// <see cref="_list"/> the first time a change is made. /// </summary> private SegmentedList<T>? _mutableList; internal ValueBuilder(ImmutableSegmentedList<T> list) { _list = list; _mutableList = null; } public int Count => ReadOnlyList.Count; private SegmentedList<T> ReadOnlyList => _mutableList ?? _list._list; bool ICollection<T>.IsReadOnly => false; bool IList.IsFixedSize => false; bool IList.IsReadOnly => false; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => throw new NotSupportedException(); public T this[int index] { get => ReadOnlyList[index]; set => GetOrCreateMutableList()[index] = value; } object? IList.this[int index] { get => ((IList)ReadOnlyList)[index]; set => ((IList)GetOrCreateMutableList())[index] = value; } public ref readonly T ItemRef(int index) { // Following trick can reduce the range check by one if ((uint)index >= (uint)ReadOnlyList.Count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return ref ReadOnlyList._items[index]; } private SegmentedList<T> GetOrCreateMutableList() { if (_mutableList is null) { var originalList = RoslynImmutableInterlocked.InterlockedExchange(ref _list, default); if (originalList.IsDefault) throw new InvalidOperationException($"Unexpected concurrent access to {GetType()}"); _mutableList = new SegmentedList<T>(originalList._list); } return _mutableList; } public void Add(T item) => GetOrCreateMutableList().Add(item); public void AddRange(IEnumerable<T> items) { if (items is null) throw new ArgumentNullException(nameof(items)); GetOrCreateMutableList().AddRange(items); } public int BinarySearch(T item) => ReadOnlyList.BinarySearch(item); public int BinarySearch(T item, IComparer<T>? comparer) => ReadOnlyList.BinarySearch(item, comparer); public int BinarySearch(int index, int count, T item, IComparer<T>? comparer) => ReadOnlyList.BinarySearch(index, count, item, comparer); public void Clear() { if (ReadOnlyList.Count != 0) { if (_mutableList is null) { _mutableList = new SegmentedList<T>(); _list = default; } else { _mutableList.Clear(); } } } public bool Contains(T item) => ReadOnlyList.Contains(item); public ImmutableSegmentedList<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter) => new ImmutableSegmentedList<TOutput>(ReadOnlyList.ConvertAll(converter)); public void CopyTo(T[] array) => ReadOnlyList.CopyTo(array); public void CopyTo(T[] array, int arrayIndex) => ReadOnlyList.CopyTo(array, arrayIndex); public void CopyTo(int index, T[] array, int arrayIndex, int count) => ReadOnlyList.CopyTo(index, array, arrayIndex, count); public bool Exists(Predicate<T> match) => ReadOnlyList.Exists(match); public T? Find(Predicate<T> match) => ReadOnlyList.Find(match); public ImmutableSegmentedList<T> FindAll(Predicate<T> match) => new ImmutableSegmentedList<T>(ReadOnlyList.FindAll(match)); public int FindIndex(Predicate<T> match) => ReadOnlyList.FindIndex(match); public int FindIndex(int startIndex, Predicate<T> match) => ReadOnlyList.FindIndex(startIndex, match); public int FindIndex(int startIndex, int count, Predicate<T> match) => ReadOnlyList.FindIndex(startIndex, count, match); public T? FindLast(Predicate<T> match) => ReadOnlyList.FindLast(match); public int FindLastIndex(Predicate<T> match) => ReadOnlyList.FindLastIndex(match); public int FindLastIndex(int startIndex, Predicate<T> match) { if (startIndex == 0 && Count == 0) { // SegmentedList<T> doesn't allow starting at index 0 for an empty list, but IImmutableList<T> does. // Handle it explicitly to avoid an exception. return -1; } return ReadOnlyList.FindLastIndex(startIndex, match); } public int FindLastIndex(int startIndex, int count, Predicate<T> match) { if (count == 0 && startIndex == 0 && Count == 0) { // SegmentedList<T> doesn't allow starting at index 0 for an empty list, but IImmutableList<T> does. // Handle it explicitly to avoid an exception. return -1; } return ReadOnlyList.FindLastIndex(startIndex, count, match); } public void ForEach(Action<T> action) => ReadOnlyList.ForEach(action); public Enumerator GetEnumerator() => new Enumerator(GetOrCreateMutableList()); public ImmutableSegmentedList<T> GetRange(int index, int count) { if (index == 0 && count == Count) return ToImmutable(); return new ImmutableSegmentedList<T>(ReadOnlyList.GetRange(index, count)); } public int IndexOf(T item) => ReadOnlyList.IndexOf(item); public int IndexOf(T item, int index) => ReadOnlyList.IndexOf(item, index); public int IndexOf(T item, int index, int count) => ReadOnlyList.IndexOf(item, index, count); public int IndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer) => ReadOnlyList.IndexOf(item, index, count, equalityComparer); public void Insert(int index, T item) => GetOrCreateMutableList().Insert(index, item); public void InsertRange(int index, IEnumerable<T> items) => GetOrCreateMutableList().InsertRange(index, items); public int LastIndexOf(T item) => ReadOnlyList.LastIndexOf(item); public int LastIndexOf(T item, int startIndex) { if (startIndex == 0 && Count == 0) { // SegmentedList<T> doesn't allow starting at index 0 for an empty list, but IImmutableList<T> does. // Handle it explicitly to avoid an exception. return -1; } return ReadOnlyList.LastIndexOf(item, startIndex); } public int LastIndexOf(T item, int startIndex, int count) { if (count == 0 && startIndex == 0 && Count == 0) { // SegmentedList<T> doesn't allow starting at index 0 for an empty list, but IImmutableList<T> does. // Handle it explicitly to avoid an exception. return -1; } return ReadOnlyList.LastIndexOf(item, startIndex, count); } public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer) { if (startIndex < 0) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); if (count < 0 || count > Count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); if (startIndex - count + 1 < 0) throw new ArgumentException(); return ReadOnlyList.LastIndexOf(item, startIndex, count, equalityComparer); } public bool Remove(T item) { if (_mutableList is null) { var index = IndexOf(item); if (index < 0) return false; RemoveAt(index); return true; } else { return _mutableList.Remove(item); } } public int RemoveAll(Predicate<T> match) => GetOrCreateMutableList().RemoveAll(match); public void RemoveAt(int index) => GetOrCreateMutableList().RemoveAt(index); public void RemoveRange(int index, int count) => GetOrCreateMutableList().RemoveRange(index, count); public void Reverse() { if (Count < 2) return; GetOrCreateMutableList().Reverse(); } public void Reverse(int index, int count) => GetOrCreateMutableList().Reverse(index, count); public void Sort() { if (Count < 2) return; GetOrCreateMutableList().Sort(); } public void Sort(IComparer<T>? comparer) { if (Count < 2) return; GetOrCreateMutableList().Sort(comparer); } public void Sort(Comparison<T> comparison) { if (comparison == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } if (Count < 2) return; GetOrCreateMutableList().Sort(comparison); } public void Sort(int index, int count, IComparer<T>? comparer) => GetOrCreateMutableList().Sort(index, count, comparer); public ImmutableSegmentedList<T> ToImmutable() { _list = new ImmutableSegmentedList<T>(ReadOnlyList); _mutableList = null; return _list; } public bool TrueForAll(Predicate<T> match) => ReadOnlyList.TrueForAll(match); IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); int IList.Add(object? value) => ((IList)GetOrCreateMutableList()).Add(value); bool IList.Contains(object? value) => ((IList)ReadOnlyList).Contains(value); int IList.IndexOf(object? value) => ((IList)ReadOnlyList).IndexOf(value); void IList.Insert(int index, object? value) => ((IList)GetOrCreateMutableList()).Insert(index, value); void IList.Remove(object? value) => ((IList)GetOrCreateMutableList()).Remove(value); void ICollection.CopyTo(Array array, int index) => ((ICollection)ReadOnlyList).CopyTo(array, index); } } }
// Licensed to the .NET Foundation under one or more 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; using System.Collections.Generic; using Microsoft.CodeAnalysis.Collections.Internal; namespace Microsoft.CodeAnalysis.Collections { internal partial struct ImmutableSegmentedList<T> { private struct ValueBuilder : IList<T>, IReadOnlyList<T>, IList { /// <summary> /// The immutable collection this builder is based on. /// </summary> private ImmutableSegmentedList<T> _list; /// <summary> /// The current mutable collection this builder is operating on. This field is initialized to a copy of /// <see cref="_list"/> the first time a change is made. /// </summary> private SegmentedList<T>? _mutableList; internal ValueBuilder(ImmutableSegmentedList<T> list) { _list = list; _mutableList = null; } public int Count => ReadOnlyList.Count; private SegmentedList<T> ReadOnlyList => _mutableList ?? _list._list; bool ICollection<T>.IsReadOnly => false; bool IList.IsFixedSize => false; bool IList.IsReadOnly => false; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => throw new NotSupportedException(); public T this[int index] { get => ReadOnlyList[index]; set => GetOrCreateMutableList()[index] = value; } object? IList.this[int index] { get => ((IList)ReadOnlyList)[index]; set => ((IList)GetOrCreateMutableList())[index] = value; } public ref readonly T ItemRef(int index) { // Following trick can reduce the range check by one if ((uint)index >= (uint)ReadOnlyList.Count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return ref ReadOnlyList._items[index]; } private SegmentedList<T> GetOrCreateMutableList() { if (_mutableList is null) { var originalList = RoslynImmutableInterlocked.InterlockedExchange(ref _list, default); if (originalList.IsDefault) throw new InvalidOperationException($"Unexpected concurrent access to {GetType()}"); _mutableList = new SegmentedList<T>(originalList._list); } return _mutableList; } public void Add(T item) => GetOrCreateMutableList().Add(item); public void AddRange(IEnumerable<T> items) { if (items is null) throw new ArgumentNullException(nameof(items)); GetOrCreateMutableList().AddRange(items); } public int BinarySearch(T item) => ReadOnlyList.BinarySearch(item); public int BinarySearch(T item, IComparer<T>? comparer) => ReadOnlyList.BinarySearch(item, comparer); public int BinarySearch(int index, int count, T item, IComparer<T>? comparer) => ReadOnlyList.BinarySearch(index, count, item, comparer); public void Clear() { if (ReadOnlyList.Count != 0) { if (_mutableList is null) { _mutableList = new SegmentedList<T>(); _list = default; } else { _mutableList.Clear(); } } } public bool Contains(T item) => ReadOnlyList.Contains(item); public ImmutableSegmentedList<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter) => new ImmutableSegmentedList<TOutput>(ReadOnlyList.ConvertAll(converter)); public void CopyTo(T[] array) => ReadOnlyList.CopyTo(array); public void CopyTo(T[] array, int arrayIndex) => ReadOnlyList.CopyTo(array, arrayIndex); public void CopyTo(int index, T[] array, int arrayIndex, int count) => ReadOnlyList.CopyTo(index, array, arrayIndex, count); public bool Exists(Predicate<T> match) => ReadOnlyList.Exists(match); public T? Find(Predicate<T> match) => ReadOnlyList.Find(match); public ImmutableSegmentedList<T> FindAll(Predicate<T> match) => new ImmutableSegmentedList<T>(ReadOnlyList.FindAll(match)); public int FindIndex(Predicate<T> match) => ReadOnlyList.FindIndex(match); public int FindIndex(int startIndex, Predicate<T> match) => ReadOnlyList.FindIndex(startIndex, match); public int FindIndex(int startIndex, int count, Predicate<T> match) => ReadOnlyList.FindIndex(startIndex, count, match); public T? FindLast(Predicate<T> match) => ReadOnlyList.FindLast(match); public int FindLastIndex(Predicate<T> match) => ReadOnlyList.FindLastIndex(match); public int FindLastIndex(int startIndex, Predicate<T> match) { if (startIndex == 0 && Count == 0) { // SegmentedList<T> doesn't allow starting at index 0 for an empty list, but IImmutableList<T> does. // Handle it explicitly to avoid an exception. return -1; } return ReadOnlyList.FindLastIndex(startIndex, match); } public int FindLastIndex(int startIndex, int count, Predicate<T> match) { if (count == 0 && startIndex == 0 && Count == 0) { // SegmentedList<T> doesn't allow starting at index 0 for an empty list, but IImmutableList<T> does. // Handle it explicitly to avoid an exception. return -1; } return ReadOnlyList.FindLastIndex(startIndex, count, match); } public void ForEach(Action<T> action) => ReadOnlyList.ForEach(action); public Enumerator GetEnumerator() => new Enumerator(GetOrCreateMutableList()); public ImmutableSegmentedList<T> GetRange(int index, int count) { if (index == 0 && count == Count) return ToImmutable(); return new ImmutableSegmentedList<T>(ReadOnlyList.GetRange(index, count)); } public int IndexOf(T item) => ReadOnlyList.IndexOf(item); public int IndexOf(T item, int index) => ReadOnlyList.IndexOf(item, index); public int IndexOf(T item, int index, int count) => ReadOnlyList.IndexOf(item, index, count); public int IndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer) => ReadOnlyList.IndexOf(item, index, count, equalityComparer); public void Insert(int index, T item) => GetOrCreateMutableList().Insert(index, item); public void InsertRange(int index, IEnumerable<T> items) => GetOrCreateMutableList().InsertRange(index, items); public int LastIndexOf(T item) => ReadOnlyList.LastIndexOf(item); public int LastIndexOf(T item, int startIndex) { if (startIndex == 0 && Count == 0) { // SegmentedList<T> doesn't allow starting at index 0 for an empty list, but IImmutableList<T> does. // Handle it explicitly to avoid an exception. return -1; } return ReadOnlyList.LastIndexOf(item, startIndex); } public int LastIndexOf(T item, int startIndex, int count) { if (count == 0 && startIndex == 0 && Count == 0) { // SegmentedList<T> doesn't allow starting at index 0 for an empty list, but IImmutableList<T> does. // Handle it explicitly to avoid an exception. return -1; } return ReadOnlyList.LastIndexOf(item, startIndex, count); } public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer) { if (startIndex < 0) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); if (count < 0 || count > Count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); if (startIndex - count + 1 < 0) throw new ArgumentException(); return ReadOnlyList.LastIndexOf(item, startIndex, count, equalityComparer); } public bool Remove(T item) { if (_mutableList is null) { var index = IndexOf(item); if (index < 0) return false; RemoveAt(index); return true; } else { return _mutableList.Remove(item); } } public int RemoveAll(Predicate<T> match) => GetOrCreateMutableList().RemoveAll(match); public void RemoveAt(int index) => GetOrCreateMutableList().RemoveAt(index); public void RemoveRange(int index, int count) => GetOrCreateMutableList().RemoveRange(index, count); public void Reverse() { if (Count < 2) return; GetOrCreateMutableList().Reverse(); } public void Reverse(int index, int count) => GetOrCreateMutableList().Reverse(index, count); public void Sort() { if (Count < 2) return; GetOrCreateMutableList().Sort(); } public void Sort(IComparer<T>? comparer) { if (Count < 2) return; GetOrCreateMutableList().Sort(comparer); } public void Sort(Comparison<T> comparison) { if (comparison == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } if (Count < 2) return; GetOrCreateMutableList().Sort(comparison); } public void Sort(int index, int count, IComparer<T>? comparer) => GetOrCreateMutableList().Sort(index, count, comparer); public ImmutableSegmentedList<T> ToImmutable() { _list = new ImmutableSegmentedList<T>(ReadOnlyList); _mutableList = null; return _list; } public bool TrueForAll(Predicate<T> match) => ReadOnlyList.TrueForAll(match); IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); int IList.Add(object? value) => ((IList)GetOrCreateMutableList()).Add(value); bool IList.Contains(object? value) => ((IList)ReadOnlyList).Contains(value); int IList.IndexOf(object? value) => ((IList)ReadOnlyList).IndexOf(value); void IList.Insert(int index, object? value) => ((IList)GetOrCreateMutableList()).Insert(index, value); void IList.Remove(object? value) => ((IList)GetOrCreateMutableList()).Remove(value); void ICollection.CopyTo(Array array, int index) => ((ICollection)ReadOnlyList).CopyTo(array, index); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Core/MSBuild/MSBuild/Logging/MSBuildDiagnosticLogger.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 Roslyn.Utilities; using MSB = Microsoft.Build; namespace Microsoft.CodeAnalysis.MSBuild.Logging { internal class MSBuildDiagnosticLogger : MSB.Framework.ILogger { private string? _projectFilePath; private DiagnosticLog? _log; private MSB.Framework.IEventSource? _eventSource; public string? Parameters { get; set; } public MSB.Framework.LoggerVerbosity Verbosity { get; set; } public void SetProjectAndLog(string projectFilePath, DiagnosticLog log) { _projectFilePath = projectFilePath; _log = log; } private void OnErrorRaised(object sender, MSB.Framework.BuildErrorEventArgs e) { RoslynDebug.AssertNotNull(_projectFilePath); _log?.Add(new MSBuildDiagnosticLogItem(WorkspaceDiagnosticKind.Failure, _projectFilePath, e.Message, e.File, e.LineNumber, e.ColumnNumber)); } private void OnWarningRaised(object sender, MSB.Framework.BuildWarningEventArgs e) { RoslynDebug.AssertNotNull(_projectFilePath); _log?.Add(new MSBuildDiagnosticLogItem(WorkspaceDiagnosticKind.Warning, _projectFilePath, e.Message, e.File, e.LineNumber, e.ColumnNumber)); } public void Initialize(MSB.Framework.IEventSource eventSource) { Debug.Assert(_eventSource == null); _eventSource = eventSource; _eventSource.ErrorRaised += OnErrorRaised; _eventSource.WarningRaised += OnWarningRaised; } public void Shutdown() { if (_eventSource != null) { _eventSource.ErrorRaised -= OnErrorRaised; _eventSource.WarningRaised -= OnWarningRaised; _eventSource = null; _projectFilePath = null; _log = 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.Diagnostics; using Roslyn.Utilities; using MSB = Microsoft.Build; namespace Microsoft.CodeAnalysis.MSBuild.Logging { internal class MSBuildDiagnosticLogger : MSB.Framework.ILogger { private string? _projectFilePath; private DiagnosticLog? _log; private MSB.Framework.IEventSource? _eventSource; public string? Parameters { get; set; } public MSB.Framework.LoggerVerbosity Verbosity { get; set; } public void SetProjectAndLog(string projectFilePath, DiagnosticLog log) { _projectFilePath = projectFilePath; _log = log; } private void OnErrorRaised(object sender, MSB.Framework.BuildErrorEventArgs e) { RoslynDebug.AssertNotNull(_projectFilePath); _log?.Add(new MSBuildDiagnosticLogItem(WorkspaceDiagnosticKind.Failure, _projectFilePath, e.Message, e.File, e.LineNumber, e.ColumnNumber)); } private void OnWarningRaised(object sender, MSB.Framework.BuildWarningEventArgs e) { RoslynDebug.AssertNotNull(_projectFilePath); _log?.Add(new MSBuildDiagnosticLogItem(WorkspaceDiagnosticKind.Warning, _projectFilePath, e.Message, e.File, e.LineNumber, e.ColumnNumber)); } public void Initialize(MSB.Framework.IEventSource eventSource) { Debug.Assert(_eventSource == null); _eventSource = eventSource; _eventSource.ErrorRaised += OnErrorRaised; _eventSource.WarningRaised += OnWarningRaised; } public void Shutdown() { if (_eventSource != null) { _eventSource.ErrorRaised -= OnErrorRaised; _eventSource.WarningRaised -= OnWarningRaised; _eventSource = null; _projectFilePath = null; _log = null; } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/Core.Wpf/QuickInfo/ContentControlService.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.Immutable; using System.Composition; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.QuickInfo { [ExportWorkspaceService(typeof(IContentControlService), layer: ServiceLayer.Editor), Shared] internal partial class ContentControlService : IContentControlService { private readonly IThreadingContext _threadingContext; private readonly ITextEditorFactoryService _textEditorFactoryService; private readonly IContentTypeRegistryService _contentTypeRegistryService; private readonly IProjectionBufferFactoryService _projectionBufferFactoryService; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ContentControlService( IThreadingContext threadingContext, ITextEditorFactoryService textEditorFactoryService, IContentTypeRegistryService contentTypeRegistryService, IProjectionBufferFactoryService projectionBufferFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService) { _threadingContext = threadingContext; _textEditorFactoryService = textEditorFactoryService; _contentTypeRegistryService = contentTypeRegistryService; _projectionBufferFactoryService = projectionBufferFactoryService; _editorOptionsFactoryService = editorOptionsFactoryService; } public void AttachToolTipToControl(FrameworkElement element, Func<DisposableToolTip> createToolTip) => LazyToolTip.AttachTo(element, _threadingContext, createToolTip); public DisposableToolTip CreateDisposableToolTip(Document document, ITextBuffer textBuffer, Span contentSpan, object backgroundResourceKey) { var control = CreateViewHostingControl(textBuffer, contentSpan); // Create the actual tooltip around the region of that text buffer we want to show. var toolTip = new ToolTip { Content = control, Background = (Brush)Application.Current.Resources[backgroundResourceKey] }; // Create a preview workspace for this text buffer and open it's corresponding // document. // // our underlying preview tagger and mechanism to attach tagger to associated buffer of // opened document will light up automatically var workspace = new PreviewWorkspace(document.Project.Solution); workspace.OpenDocument(document.Id, textBuffer.AsTextContainer()); return new DisposableToolTip(toolTip, workspace); } public DisposableToolTip CreateDisposableToolTip(ITextBuffer textBuffer, object backgroundResourceKey) { var control = CreateViewHostingControl(textBuffer, textBuffer.CurrentSnapshot.GetFullSpan().Span); // Create the actual tooltip around the region of that text buffer we want to show. var toolTip = new ToolTip { Content = control, Background = (Brush)Application.Current.Resources[backgroundResourceKey] }; // we have stand alone view that is not associated with roslyn solution return new DisposableToolTip(toolTip, workspaceOpt: null); } public ViewHostingControl CreateViewHostingControl(ITextBuffer textBuffer, Span contentSpan) { var snapshotSpan = textBuffer.CurrentSnapshot.GetSpan(contentSpan); var contentType = _contentTypeRegistryService.GetContentType( IProjectionBufferFactoryServiceExtensions.RoslynPreviewContentType); var roleSet = _textEditorFactoryService.CreateTextViewRoleSet( TextViewRoles.PreviewRole, PredefinedTextViewRoles.Analyzable, PredefinedTextViewRoles.Document, PredefinedTextViewRoles.Editable); var contentControl = ProjectionBufferContent.Create( _threadingContext, ImmutableArray.Create(snapshotSpan), _projectionBufferFactoryService, _editorOptionsFactoryService, _textEditorFactoryService, contentType, roleSet); return contentControl; } } }
// Licensed to the .NET Foundation under one or more 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.Immutable; using System.Composition; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.QuickInfo { [ExportWorkspaceService(typeof(IContentControlService), layer: ServiceLayer.Editor), Shared] internal partial class ContentControlService : IContentControlService { private readonly IThreadingContext _threadingContext; private readonly ITextEditorFactoryService _textEditorFactoryService; private readonly IContentTypeRegistryService _contentTypeRegistryService; private readonly IProjectionBufferFactoryService _projectionBufferFactoryService; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ContentControlService( IThreadingContext threadingContext, ITextEditorFactoryService textEditorFactoryService, IContentTypeRegistryService contentTypeRegistryService, IProjectionBufferFactoryService projectionBufferFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService) { _threadingContext = threadingContext; _textEditorFactoryService = textEditorFactoryService; _contentTypeRegistryService = contentTypeRegistryService; _projectionBufferFactoryService = projectionBufferFactoryService; _editorOptionsFactoryService = editorOptionsFactoryService; } public void AttachToolTipToControl(FrameworkElement element, Func<DisposableToolTip> createToolTip) => LazyToolTip.AttachTo(element, _threadingContext, createToolTip); public DisposableToolTip CreateDisposableToolTip(Document document, ITextBuffer textBuffer, Span contentSpan, object backgroundResourceKey) { var control = CreateViewHostingControl(textBuffer, contentSpan); // Create the actual tooltip around the region of that text buffer we want to show. var toolTip = new ToolTip { Content = control, Background = (Brush)Application.Current.Resources[backgroundResourceKey] }; // Create a preview workspace for this text buffer and open it's corresponding // document. // // our underlying preview tagger and mechanism to attach tagger to associated buffer of // opened document will light up automatically var workspace = new PreviewWorkspace(document.Project.Solution); workspace.OpenDocument(document.Id, textBuffer.AsTextContainer()); return new DisposableToolTip(toolTip, workspace); } public DisposableToolTip CreateDisposableToolTip(ITextBuffer textBuffer, object backgroundResourceKey) { var control = CreateViewHostingControl(textBuffer, textBuffer.CurrentSnapshot.GetFullSpan().Span); // Create the actual tooltip around the region of that text buffer we want to show. var toolTip = new ToolTip { Content = control, Background = (Brush)Application.Current.Resources[backgroundResourceKey] }; // we have stand alone view that is not associated with roslyn solution return new DisposableToolTip(toolTip, workspaceOpt: null); } public ViewHostingControl CreateViewHostingControl(ITextBuffer textBuffer, Span contentSpan) { var snapshotSpan = textBuffer.CurrentSnapshot.GetSpan(contentSpan); var contentType = _contentTypeRegistryService.GetContentType( IProjectionBufferFactoryServiceExtensions.RoslynPreviewContentType); var roleSet = _textEditorFactoryService.CreateTextViewRoleSet( TextViewRoles.PreviewRole, PredefinedTextViewRoles.Analyzable, PredefinedTextViewRoles.Document, PredefinedTextViewRoles.Editable); var contentControl = ProjectionBufferContent.Create( _threadingContext, ImmutableArray.Create(snapshotSpan), _projectionBufferFactoryService, _editorOptionsFactoryService, _textEditorFactoryService, contentType, roleSet); return contentControl; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Test/Resources/Core/SymbolsTests/MissingTypes/MissingTypesEquality1.dll
MZ@ !L!This program cannot be run in DOS mode. $PELL! # @@ `@D#W@  H.text  `.reloc @@B#HX ( *BSJB v4.0.30319l#~#Strings#US#GUID,#BlobG %3 8  ++P FFFFF"F'FF R[fq|<Module>SystemObject.ctorMissingType1MissingType2MissingTypesEquality1.dllmscorlibMDTestLib1MDTestLib2MDTestLib3MDTestLib4CM1M2M3M4M5M6M7M8MissingTypesEquality1 ,A?mj z\V4        l## #_CorDllMainmscoree.dll% @ 3
MZ@ !L!This program cannot be run in DOS mode. $PELL! # @@ `@D#W@  H.text  `.reloc @@B#HX ( *BSJB v4.0.30319l#~#Strings#US#GUID,#BlobG %3 8  ++P FFFFF"F'FF R[fq|<Module>SystemObject.ctorMissingType1MissingType2MissingTypesEquality1.dllmscorlibMDTestLib1MDTestLib2MDTestLib3MDTestLib4CM1M2M3M4M5M6M7M8MissingTypesEquality1 ,A?mj z\V4        l## #_CorDllMainmscoree.dll% @ 3
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/Core/Implementation/RenameTracking/IRenameTrackingLanguageHeuristicsService.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.Host; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { internal interface IRenameTrackingLanguageHeuristicsService : ILanguageService { bool IsIdentifierValidForRenameTracking(string name); } }
// Licensed to the .NET Foundation under one or more 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.Host; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { internal interface IRenameTrackingLanguageHeuristicsService : ILanguageService { bool IsIdentifierValidForRenameTracking(string name); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/Telemetry/TelemetryPanel.xaml
<UserControl x:Class="Roslyn.VisualStudio.DiagnosticsWindow.Telemetry.TelemetryPanel" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:Roslyn.VisualStudio.DiagnosticsWindow.Telemetry" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <ScrollViewer Grid.Row="0" VerticalScrollBarVisibility="Visible" > <StackPanel Orientation="Vertical" > <ProgressBar x:Name="GenerationProgresBar" IsIndeterminate="False" /> <TextBox x:Name="Result" IsReadOnly="True" TextWrapping="Wrap" /> </StackPanel> </ScrollViewer> <StackPanel Grid.Row="1" Orientation="Horizontal"> <Label Content="Telemetry Info" /> <Button Content="Dump" x:Name="DumpButton" Click="OnDump"/> <Label Content="Copy To Clipboard" /> <Button Content="Copy" x:Name="CopyButton" Click="OnCopy"/> </StackPanel> </Grid> </UserControl>
<UserControl x:Class="Roslyn.VisualStudio.DiagnosticsWindow.Telemetry.TelemetryPanel" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:Roslyn.VisualStudio.DiagnosticsWindow.Telemetry" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <ScrollViewer Grid.Row="0" VerticalScrollBarVisibility="Visible" > <StackPanel Orientation="Vertical" > <ProgressBar x:Name="GenerationProgresBar" IsIndeterminate="False" /> <TextBox x:Name="Result" IsReadOnly="True" TextWrapping="Wrap" /> </StackPanel> </ScrollViewer> <StackPanel Grid.Row="1" Orientation="Horizontal"> <Label Content="Telemetry Info" /> <Button Content="Dump" x:Name="DumpButton" Click="OnDump"/> <Label Content="Copy To Clipboard" /> <Button Content="Copy" x:Name="CopyButton" Click="OnCopy"/> </StackPanel> </Grid> </UserControl>
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/VisualBasic/Portable/Parser/BlockContexts/EnumDeclarationBlockContext.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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------- ' Contains the definition of the BlockContext '----------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend NotInheritable Class EnumDeclarationBlockContext Inherits DeclarationContext Friend Sub New(statement As StatementSyntax, prevContext As BlockContext) MyBase.New(SyntaxKind.EnumBlock, statement, prevContext) End Sub Friend Overrides Function CreateBlockSyntax(endStmt As StatementSyntax) As VisualBasicSyntaxNode Debug.Assert(BeginStatement IsNot Nothing) Dim beginBlock As EnumStatementSyntax = Nothing Dim endBlock As EndBlockStatementSyntax = DirectCast(endStmt, EndBlockStatementSyntax) GetBeginEndStatements(beginBlock, endBlock) Dim result = SyntaxFactory.EnumBlock(beginBlock, Body(), endBlock) FreeStatements() Return result End Function Friend Overrides Function ProcessSyntax(node As VisualBasicSyntaxNode) As BlockContext Select Case node.Kind Case SyntaxKind.EnumMemberDeclaration Add(node) Case Else If IsExecutableStatementOrItsPart(node) Then ' do not end the block - an executable statement can't be handled outside of a method Add(Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideEnum)) Else ' End the current block and add the block to the context above which should be able to handle this kind of statement. Dim outerContext = EndBlock(Nothing) Return outerContext.ProcessSyntax(Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideEndsEnum)) End If End Select Return Me End Function Friend Overrides Function TryLinkSyntax(node As VisualBasicSyntaxNode, ByRef newContext As BlockContext) As LinkResult newContext = Nothing Select Case node.Kind Case SyntaxKind.EnumMemberDeclaration Return UseSyntax(node, newContext) Case SyntaxKind.NamespaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.EnumBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.SubBlock, SyntaxKind.ConstructorBlock, SyntaxKind.FunctionBlock, SyntaxKind.OperatorBlock, SyntaxKind.PropertyBlock, SyntaxKind.EventBlock ' These blocks need to be crumbled so that the error is correctly reported on ' the statement that begins the block. If they aren't crumbled the block is added and ' the error will be on the block. This list must be kept in sync with the blocks ' handled by the declaration context. newContext = Me Return LinkResult.Crumble Case Else Return MyBase.TryLinkSyntax(node, newContext) End Select 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------- ' Contains the definition of the BlockContext '----------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend NotInheritable Class EnumDeclarationBlockContext Inherits DeclarationContext Friend Sub New(statement As StatementSyntax, prevContext As BlockContext) MyBase.New(SyntaxKind.EnumBlock, statement, prevContext) End Sub Friend Overrides Function CreateBlockSyntax(endStmt As StatementSyntax) As VisualBasicSyntaxNode Debug.Assert(BeginStatement IsNot Nothing) Dim beginBlock As EnumStatementSyntax = Nothing Dim endBlock As EndBlockStatementSyntax = DirectCast(endStmt, EndBlockStatementSyntax) GetBeginEndStatements(beginBlock, endBlock) Dim result = SyntaxFactory.EnumBlock(beginBlock, Body(), endBlock) FreeStatements() Return result End Function Friend Overrides Function ProcessSyntax(node As VisualBasicSyntaxNode) As BlockContext Select Case node.Kind Case SyntaxKind.EnumMemberDeclaration Add(node) Case Else If IsExecutableStatementOrItsPart(node) Then ' do not end the block - an executable statement can't be handled outside of a method Add(Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideEnum)) Else ' End the current block and add the block to the context above which should be able to handle this kind of statement. Dim outerContext = EndBlock(Nothing) Return outerContext.ProcessSyntax(Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideEndsEnum)) End If End Select Return Me End Function Friend Overrides Function TryLinkSyntax(node As VisualBasicSyntaxNode, ByRef newContext As BlockContext) As LinkResult newContext = Nothing Select Case node.Kind Case SyntaxKind.EnumMemberDeclaration Return UseSyntax(node, newContext) Case SyntaxKind.NamespaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.EnumBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.SubBlock, SyntaxKind.ConstructorBlock, SyntaxKind.FunctionBlock, SyntaxKind.OperatorBlock, SyntaxKind.PropertyBlock, SyntaxKind.EventBlock ' These blocks need to be crumbled so that the error is correctly reported on ' the statement that begins the block. If they aren't crumbled the block is added and ' the error will be on the block. This list must be kept in sync with the blocks ' handled by the declaration context. newContext = Me Return LinkResult.Crumble Case Else Return MyBase.TryLinkSyntax(node, newContext) End Select End Function End Class End Namespace
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.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.IO Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.MetadataUtilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class EditAndContinueTests Inherits EditAndContinueTestBase <Fact> Public Sub SemanticErrors_MethodBody() Dim source0 = MarkedSource(" Class C Shared Sub E() Dim x As Integer = 1 System.Console.WriteLine(x) End Sub Shared Sub G() System.Console.WriteLine(1) End Sub End Class ") Dim source1 = MarkedSource(" Class C Shared Sub E() Dim x = Unknown(2) System.Console.WriteLine(x) End Sub Shared Sub G() System.Console.WriteLine(2) End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim e0 = compilation0.GetMember(Of MethodSymbol)("C.E") Dim e1 = compilation1.GetMember(Of MethodSymbol)("C.E") Dim g0 = compilation0.GetMember(Of MethodSymbol)("C.G") Dim g1 = compilation1.GetMember(Of MethodSymbol)("C.G") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) ' Semantic errors are reported only for the bodies of members being emitted. Dim diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diffError.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_NameNotDeclared1, "Unknown").WithArguments("Unknown").WithLocation(4, 17)) Dim diffGood = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diffGood.EmitResult.Diagnostics.Verify() diffGood.VerifyIL("C.G", " { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.2 IL_0002: call ""Sub System.Console.WriteLine(Integer)"" IL_0007: nop IL_0008: ret }") End Sub <Fact> Public Sub SemanticErrors_Declaration() Dim source0 = MarkedSource(" Class C Sub G() System.Console.WriteLine(1) End Sub End Class ") Dim source1 = MarkedSource(" Class C Sub G() System.Console.WriteLine(1) End Sub End Class Class Bad Inherits Bad End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim g0 = compilation0.GetMember(Of MethodSymbol)("C.G") Dim g1 = compilation1.GetMember(Of MethodSymbol)("C.G") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_TypeInItsInheritsClause1, "Bad").WithArguments("Bad").WithLocation(9, 12)) End Sub <Fact> Public Sub ModifyMethod_WithTuples() Dim source0 = " Class C Shared Sub Main End Sub Shared Function F() As (Integer, Integer) Return (1, 2) End Function End Class " Dim source1 = " Class C Shared Sub Main End Sub Shared Function F() As (Integer, Integer) Return (2, 3) End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugExe, references:={ValueTupleRef, SystemRuntimeFacadeRef}) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) ' Verify delta metadata contains expected rows. Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} EncValidation.VerifyModuleMvid(1, reader0, reader1) CheckNames(readers, reader1.GetTypeDefNames()) CheckNames(readers, reader1.GetMethodDefNames(), "F") CheckNames(readers, reader1.GetMemberRefNames(), ".ctor") ' System.ValueTuple ctor CheckEncLog(reader1, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) ' C.F CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.TypeSpec), Handle(3, TableIndex.AssemblyRef), Handle(4, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact> Public Sub ModifyMethod_RenameParameter() Dim source0 = " Class C Shared Function F(i As Integer) As Integer Return i End Function End Class " Dim source1 = " Class C Shared Function F(x As Integer) As Integer Return x End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll, references:={ValueTupleRef, SystemRuntimeFacadeRef}) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) CheckNames(reader0, reader0.GetParameterDefNames(), "i") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) ' Verify delta metadata contains expected rows. Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} EncValidation.VerifyModuleMvid(1, reader0, reader1) CheckNames(readers, reader1.GetTypeDefNames()) CheckNames(readers, reader1.GetMethodDefNames(), "F") CheckNames(readers, reader1.GetParameterDefNames(), "x") CheckEncLogDefinitions(reader1, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)) CheckEncMapDefinitions(reader1, Handle(2, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.StandAloneSig)) End Using End Using End Sub <WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")> <Fact> Public Sub PartialMethod() Dim source = <compilation> <file name="a.vb"> Partial Class C Private Shared Partial Sub M1() End Sub Private Shared Partial Sub M2() End Sub Private Shared Partial Sub M3() End Sub Private Shared Sub M1() End Sub Private Shared Sub M2() End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "M1", "M2") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M2").PartialImplementationPart Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M2").PartialImplementationPart Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) Dim methods = diff1.TestData.GetMethodsByName() Assert.Equal(methods.Count, 1) Assert.True(methods.ContainsKey("C.M2()")) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetMethodDefNames(), "M2") CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact> Public Sub AddThenModifyExplicitImplementation() Dim source0 = <compilation> <file name="a.vb"> Interface I(Of T) Sub M() End Interface </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Interface I(Of T) Sub M() End Interface Class A Implements I(Of Integer), I(Of Object) Public Sub New() End Sub Sub M() Implements I(Of Integer).M, I(Of Object).M End Sub End Class </file> </compilation> Dim source2 = source1 Dim source3 = <compilation> <file name="a.vb"> Interface I(Of T) Sub M() End Interface Class A Implements I(Of Integer), I(Of Object) Public Sub New() End Sub Sub M() Implements I(Of Integer).M, I(Of Object).M End Sub End Class Class B Implements I(Of Object) Public Sub New() End Sub Sub M() Implements I(Of Object).M End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim compilation2 = compilation1.WithSource(source2) Dim compilation3 = compilation2.WithSource(source3) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim type1 = compilation1.GetMember(Of NamedTypeSymbol)("A") Dim method1 = compilation1.GetMember(Of MethodSymbol)("A.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, type1))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetMethodDefNames(), ".ctor", "M") CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(4, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(2, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(5, TableIndex.TypeRef), Handle(3, TableIndex.TypeDef), Handle(2, TableIndex.MethodDef), Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.InterfaceImpl), Handle(2, TableIndex.InterfaceImpl), Handle(4, TableIndex.MemberRef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(1, TableIndex.MethodImpl), Handle(2, TableIndex.MethodImpl), Handle(1, TableIndex.TypeSpec), Handle(2, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)) Dim generation1 = diff1.NextGeneration Dim method2 = compilation2.GetMember(Of MethodSymbol)("A.M") Dim diff2 = compilation2.EmitDifference( generation1, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2))) Using md2 = diff2.GetMetadata() Dim reader2 = md2.Reader readers = {reader0, reader1, reader2} CheckNames(readers, reader2.GetMethodDefNames(), "M") CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader2, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(3, TableIndex.TypeSpec), Handle(4, TableIndex.TypeSpec), Handle(3, TableIndex.AssemblyRef)) Dim generation2 = diff2.NextGeneration Dim type3 = compilation3.GetMember(Of NamedTypeSymbol)("B") Dim diff3 = compilation3.EmitDifference( generation1, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, type3))) Using md3 = diff3.GetMetadata() Dim reader3 = md3.Reader readers = {reader0, reader1, reader3} CheckNames(readers, reader3.GetMethodDefNames(), ".ctor", "M") CheckEncLog(reader3, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(3, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)) CheckEncMap(reader3, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(3, TableIndex.InterfaceImpl), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(3, TableIndex.MethodImpl), Handle(3, TableIndex.TypeSpec), Handle(3, TableIndex.AssemblyRef)) End Using End Using End Using End Using End Sub <Fact, WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")> Public Sub ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation() Dim source = <compilation> <file name="a.vb"> Interface I Sub M1() Sub M2() End Interface Class C Implements I Public Sub New() End Sub Sub M() Implements I.M1, I.M2 End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of NamedTypeSymbol)("C").InstanceConstructors.Single() Dim method1 = compilation1.GetMember(Of NamedTypeSymbol)("C").InstanceConstructors.Single() Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetTypeDefNames()) CheckNames(readers, reader1.GetMethodDefNames(), ".ctor") CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact> Public Sub NamespacesAndOverloads() Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(options:=TestOptions.DebugDll, source:= <compilation> <file name="a.vb"><![CDATA[ Class C End Class Namespace N Class C End Class End Namespace Namespace M Class C Sub M1(o As N.C) End Sub Sub M1(o As M.C) End Sub Sub M2(a As N.C, b As M.C, c As Global.C) M1(a) End Sub End Class End Namespace ]]></file> </compilation>) Dim bytes = compilation0.EmitToArray() Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes), EmptyLocalsProvider) Dim compilation1 = compilation0.WithSource( <compilation> <file name="a.vb"><![CDATA[ Class C End Class Namespace N Class C End Class End Namespace Namespace M Class C Sub M1(o As N.C) End Sub Sub M1(o As M.C) End Sub Sub M1(o As Global.C) End Sub Sub M2(a As N.C, b As M.C, c As Global.C) M1(a) M1(b) End Sub End Class End Namespace ]]></file> </compilation>) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, compilation1.GetMembers("M.C.M1")(2)), New SemanticEdit(SemanticEditKind.Update, compilation0.GetMembers("M.C.M2")(0), compilation1.GetMembers("M.C.M2")(0)))) diff1.VerifyIL(" { // Code size 18 (0x12) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000004 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000005 IL_0010: nop IL_0011: ret } { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } ") Dim compilation2 = compilation1.WithSource( <compilation> <file name="a.vb"><![CDATA[ Class C End Class Namespace N Class C End Class End Namespace Namespace M Class C Sub M1(o As N.C) End Sub Sub M1(o As M.C) End Sub Sub M1(o As Global.C) End Sub Sub M2(a As N.C, b As M.C, c As Global.C) M1(a) M1(b) M1(c) End Sub End Class End Namespace ]]></file> </compilation>) Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, compilation1.GetMembers("M.C.M2")(0), compilation2.GetMembers("M.C.M2")(0)))) diff2.VerifyIL(" { // Code size 26 (0x1a) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000004 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000005 IL_0010: nop IL_0011: ldarg.0 IL_0012: ldarg.3 IL_0013: call 0x06000007 IL_0018: nop IL_0019: ret } ") End Sub <WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")> <Fact()> Public Sub PrivateImplementationDetails_ArrayInitializer_FromMetadata() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim a As Integer() = {1, 2, 3} System.Console.Write(a(0)) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim a As Integer() = {1, 2, 3} System.Console.Write(a(1)) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(sources0, TestOptions.DebugDll.WithModuleName("MODULE")) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.M") methodData0.VerifyIL(" { // Code size 29 (0x1d) .maxstack 3 .locals init (Integer() V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""Integer"" IL_0007: dup IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000d: call ""Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: ldelem.i4 IL_0016: call ""Sub System.Console.Write(Integer)"" IL_001b: nop IL_001c: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider) Dim testData1 = New CompilationTestData() Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 30 (0x1e) .maxstack 4 .locals init (Integer() V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""Integer"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: ldelem.i4 IL_0017: call ""Sub System.Console.Write(Integer)"" IL_001c: nop IL_001d: ret } ") End Sub ''' <summary> ''' Should not generate method for string switch since ''' the CLR only allows adding private members. ''' </summary> <WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")> <Fact()> Public Sub PrivateImplementationDetails_ComputeStringHash() Dim sources = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F(s As String) Select Case s Case "1" Return 1 Case "2" Return 2 Case "3" Return 3 Case "4" Return 4 Case "5" Return 5 Case "6" Return 6 Case "7" Return 7 Case Else Return 0 End Select End Function End Class ]]></file> </compilation> Const ComputeStringHashName As String = "ComputeStringHash" Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(sources, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.F") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider) ' Should have generated call to ComputeStringHash and ' added the method to <PrivateImplementationDetails>. Dim actualIL0 = methodData0.GetMethodIL() Assert.True(actualIL0.Contains(ComputeStringHashName)) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "F", ComputeStringHashName) Dim testData1 = New CompilationTestData() Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) ' Should not have generated call to ComputeStringHash nor ' added the method to <PrivateImplementationDetails>. Dim actualIL1 = diff1.GetMethodIL("C.F") Assert.False(actualIL1.Contains(ComputeStringHashName)) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetMethodDefNames(), "F") End Using End Using End Sub ''' <summary> ''' Avoid adding references from method bodies ''' other than the changed methods. ''' </summary> <Fact> Public Sub ReferencesInIL() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Module M Sub F() System.Console.WriteLine(1) End Sub Sub G() System.Console.WriteLine(2) End Sub End Module ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Module M Sub F() System.Console.WriteLine(1) End Sub Sub G() System.Console.Write(2) End Sub End Module ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(sources0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) ' Verify full metadata contains expected rows. Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "M") CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G") CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", ".ctor", "WriteLine") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, compilation1.GetMember("M.G")))) ' "Write" should be included in string table, but "WriteLine" should not. Assert.True(diff1.MetadataDelta.IsIncluded("Write")) Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine")) End Using End Sub <Fact> Public Sub ExceptionFilters() Dim source0 = MarkedSource(" Imports System Imports System.IO Class C Shared Function filter(e As Exception) Return True End Function Shared Sub F() Try Throw New InvalidOperationException() <N:0>Catch e As IOException <N:1>When filter(e)</N:1></N:0> Console.WriteLine() <N:2>Catch e As Exception <N:3>When filter(e)</N:3></N:2> Console.WriteLine() End Try End Sub End Class ") Dim source1 = MarkedSource(" Imports System Imports System.IO Class C Shared Function filter(e As Exception) Return True End Function Shared Sub F() Try Throw New InvalidOperationException() <N:0>Catch e As IOException <N:1>When filter(e)</N:1></N:0> Console.WriteLine() <N:2>Catch e As Exception <N:3>When filter(e)</N:3></N:2> Console.WriteLine() End Try Console.WriteLine() End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib45AndVBRuntime({source0.Tree}, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 118 (0x76) .maxstack 2 .locals init (System.IO.IOException V_0, //e Boolean V_1, System.Exception V_2, //e Boolean V_3) IL_0000: nop .try { IL_0001: nop IL_0002: newobj ""Sub System.InvalidOperationException..ctor()"" IL_0007: throw } filter { IL_0008: isinst ""System.IO.IOException"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_002b IL_0014: dup IL_0015: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_001a: stloc.0 IL_001b: ldloc.0 IL_001c: call ""Function C.filter(System.Exception) As Object"" IL_0021: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"" IL_0026: stloc.1 IL_0027: ldloc.1 IL_0028: ldc.i4.0 IL_0029: cgt.un IL_002b: endfilter } // end filter { // handler IL_002d: pop IL_002e: call ""Sub System.Console.WriteLine()"" IL_0033: nop IL_0034: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_0039: leave.s IL_006e } filter { IL_003b: isinst ""System.Exception"" IL_0040: dup IL_0041: brtrue.s IL_0047 IL_0043: pop IL_0044: ldc.i4.0 IL_0045: br.s IL_005e IL_0047: dup IL_0048: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_004d: stloc.2 IL_004e: ldloc.2 IL_004f: call ""Function C.filter(System.Exception) As Object"" IL_0054: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"" IL_0059: stloc.3 IL_005a: ldloc.3 IL_005b: ldc.i4.0 IL_005c: cgt.un IL_005e: endfilter } // end filter { // handler IL_0060: pop IL_0061: call ""Sub System.Console.WriteLine()"" IL_0066: nop IL_0067: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_006c: leave.s IL_006e } IL_006e: nop IL_006f: call ""Sub System.Console.WriteLine()"" IL_0074: nop IL_0075: ret } ") End Sub <Fact> Public Sub SymbolMatcher_TypeArguments() Dim source = <compilation> <file name="c.vb"><![CDATA[ Class A(Of T) Class B(Of U) Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of Object).S) As A(Of V) Return Nothing End Function Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of V).S) As A(Of V) Return Nothing End Function End Class Structure S End Structure End Class ]]> </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim matcher = CreateMatcher(compilation1, compilation0) Dim members = compilation1.GetMember(Of NamedTypeSymbol)("A.B").GetMembers("M") Assert.Equal(members.Length, 2) For Each member In members Dim other = DirectCast(matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IMethodDefinition)).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) Next End Sub <Fact> Public Sub SymbolMatcher_Constraints() Dim source = <compilation> <file name="c.vb"><![CDATA[ Interface I(Of T As I(Of T)) End Interface Class C Shared Sub M(Of T As I(Of T))(o As I(Of T)) End Sub End Class ]]> </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim matcher = CreateMatcher(compilation1, compilation0) Dim member = compilation1.GetMember(Of MethodSymbol)("C.M") Dim other = DirectCast(matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IMethodDefinition)).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) End Sub <Fact> Public Sub SymbolMatcher_CustomModifiers() Dim ilSource = <![CDATA[ .class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F() { } } ]]>.Value Dim source = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits A Public Overrides Function F() As Object() Return Nothing End Function End Class ]]> </file> </compilation> Dim metadata = CompileIL(ilSource) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, {metadata}, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim member1 = compilation1.GetMember(Of MethodSymbol)("B.F") Const nModifiers As Integer = 1 Assert.Equal(nModifiers, DirectCast(member1.ReturnType, ArrayTypeSymbol).CustomModifiers.Length) Dim matcher = CreateMatcher(compilation1, compilation0) Dim other = DirectCast(matcher.MapDefinition(DirectCast(member1.GetCciAdapter(), Cci.IMethodDefinition)).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) Assert.Equal(nModifiers, DirectCast(other.ReturnType, ArrayTypeSymbol).CustomModifiers.Length) End Sub <WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")> <Fact()> Public Sub MethodSignatureWithNoPIAType() Dim sourcesPIA = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib("_.dll")> <Assembly: Guid("35DB1A6B-D635-4320-A062-28D42920F2A3")> <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2A4")> Public Interface I End Interface ]]></file> </compilation> Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M(x As I) Dim y As I = Nothing M(Nothing) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M(x As I) Dim y As I = Nothing M(x) End Sub End Class ]]></file> </compilation> Dim compilationPIA = CreateCompilationWithMscorlib40AndVBRuntime(sourcesPIA) compilationPIA.AssertTheseDiagnostics() Dim referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes:=True) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, options:=TestOptions.DebugDll, references:={referencePIA}) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.M") Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.VerifyIL("C.M", <![CDATA[ { // Code size 11 (0xb) .maxstack 1 .locals init ([unchanged] V_0, I V_1) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: ldarg.0 IL_0004: call "Sub C.M(I)" IL_0009: nop IL_000a: ret } ]]>.Value) End Using End Sub ''' <summary> ''' Disallow edits that require NoPIA references. ''' </summary> <Fact()> Public Sub NoPIAReferences() Dim sourcesPIA = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib("_.dll")> <Assembly: Guid("35DB1A6B-D635-4320-A062-28D42920F2B3")> <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2B4")> Public Interface IA Sub M() ReadOnly Property P As Integer Event E As Action End Interface <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2B5")> Public Interface IB End Interface <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2B6")> Public Interface IC End Interface Public Structure S Public F As Object End Structure ]]></file> </compilation> Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C(Of T) Shared Private F As Object = GetType(IC) Shared Sub M1() Dim o As IA = Nothing o.M() M2(o.P) AddHandler o.E, AddressOf M1 M2(C(Of IA).F) M2(New S()) End Sub Shared Sub M2(o As Object) End Sub End Class ]]></file> </compilation> Dim sources1A = sources0 Dim sources1B = <compilation> <file name="a.vb"><![CDATA[ Class C(Of T) Shared Private F As Object = GetType(IC) Shared Sub M1() M2(Nothing) End Sub Shared Sub M2(o As Object) End Sub End Class ]]></file> </compilation> Dim compilationPIA = CreateCompilationWithMscorlib40AndVBRuntime(sourcesPIA) compilationPIA.AssertTheseDiagnostics() Dim referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes:=True) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, options:=TestOptions.DebugDll, references:={referencePIA}) Dim compilation1A = compilation0.WithSource(sources1A) Dim compilation1B = compilation0.WithSource(sources1B) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C(Of T).M1") Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M1") ' Disallow edits that require NoPIA references. Dim method1A = compilation1A.GetMember(Of MethodSymbol)("C.M1") Dim diff1A = compilation1A.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables:=True))) diff1A.EmitResult.Diagnostics.AssertTheseDiagnostics(<errors><![CDATA[ BC37230: Cannot continue since the edit includes a reference to an embedded type: 'IA'. BC37230: Cannot continue since the edit includes a reference to an embedded type: 'S'. ]]></errors>) ' Allow edits that do not require NoPIA references, Dim method1B = compilation1B.GetMember(Of MethodSymbol)("C.M1") Dim diff1B = compilation1B.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables:=True))) diff1B.VerifyIL("C(Of T).M1", <![CDATA[ { // Code size 9 (0x9) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1) IL_0000: nop IL_0001: ldnull IL_0002: call "Sub C(Of T).M2(Object)" IL_0007: nop IL_0008: ret } ]]>.Value) Using md1 = diff1B.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames()) End Using End Using End Sub <WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")> <Fact()> Public Sub NoPIATypeInNamespace() Dim sourcesPIA = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib("_.dll")> <Assembly: Guid("35DB1A6B-D635-4320-A062-28D42920F2A5")> Namespace N <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2A6")> Public Interface IA End Interface End Namespace <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2A6")> Public Interface IB End Interface ]]></file> </compilation> Dim sources = <compilation> <file name="a.vb"><![CDATA[ Class C(Of T) Shared Sub M(o As Object) M(C(Of N.IA).E.X) M(C(Of IB).E.X) End Sub Enum E X End Enum End Class ]]></file> </compilation> Dim compilationPIA = CreateCompilationWithMscorlib40AndVBRuntime(sourcesPIA) compilationPIA.AssertTheseDiagnostics() Dim referencePIA = AssemblyMetadata.CreateFromImage(compilationPIA.EmitToArray()).GetReference(embedInteropTypes:=True) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources, options:=TestOptions.DebugDll, references:={referencePIA}) Dim compilation1 = compilation0.WithSource(sources) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.EmitResult.Diagnostics.AssertTheseDiagnostics(<errors><![CDATA[ BC37230: Cannot continue since the edit includes a reference to an embedded type: 'IA'. BC37230: Cannot continue since the edit includes a reference to an embedded type: 'IB'. ]]></errors>) diff1.VerifyIL("C(Of T).M", <![CDATA[ { // Code size 26 (0x1a) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box "C(Of N.IA).E" IL_0007: call "Sub C(Of T).M(Object)" IL_000c: nop IL_000d: ldc.i4.0 IL_000e: box "C(Of IB).E" IL_0013: call "Sub C(Of T).M(Object)" IL_0018: nop IL_0019: ret } ]]>.Value) End Using End Sub <Fact, WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")> Public Sub EventFields() Dim source0 = MarkedSource(" Imports System Class C Shared Event handler As EventHandler Shared Function F() As Integer RaiseEvent handler(Nothing, Nothing) Return 1 End Function End Class ") Dim source1 = MarkedSource(" Imports System Class C Shared Event handler As EventHandler Shared Function F() As Integer RaiseEvent handler(Nothing, Nothing) Return 10 End Function End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) compilation0.AssertNoDiagnostics() Dim compilation1 = compilation0.WithSource(source1.Tree) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 26 (0x1a) .maxstack 3 .locals init (Integer V_0, //F [unchanged] V_1, System.EventHandler V_2) IL_0000: nop IL_0001: ldsfld ""C.handlerEvent As System.EventHandler"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: brfalse.s IL_0013 IL_000a: ldloc.2 IL_000b: ldnull IL_000c: ldnull IL_000d: callvirt ""Sub System.EventHandler.Invoke(Object, System.EventArgs)"" IL_0012: nop IL_0013: ldc.i4.s 10 IL_0015: stloc.0 IL_0016: br.s IL_0018 IL_0018: ldloc.0 IL_0019: ret } ") End Sub ''' <summary> ''' Should use TypeDef rather than TypeRef for unrecognized ''' local of a type defined in the original assembly. ''' </summary> <WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")> <Fact()> Public Sub UnrecognizedLocalOfTypeFromAssembly() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class E Inherits System.Exception End Class Class C Shared Sub M() Try Catch e As E End Try End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetAssemblyRefNames(), "mscorlib", "Microsoft.VisualBasic") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") ' Use empty LocalVariableNameProvider for original locals and ' use preserveLocalVariables: true for the edit so that existing ' locals are retained even though all are unrecognized. Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, syntaxMap:=Function(s) Nothing, preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetAssemblyRefNames(), "mscorlib", "Microsoft.VisualBasic") CheckNames(readers, reader1.GetTypeRefNames(), "Object", "ProjectData", "Exception") CheckEncLog(reader1, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef), Handle(4, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact, WorkItem(837315, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837315")> Public Sub AddingSetAccessor() Dim source0 = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine("hello") End Sub Friend name As String Readonly Property GetName Get Return name End Get End Property End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine("hello") End Sub Friend name As String Property GetName Get Return name End Get Private Set(value) End Set End Property End Module</file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim prop0 = compilation0.GetMember(Of PropertySymbol)("Module1.GetName") Dim prop1 = compilation1.GetMember(Of PropertySymbol)("Module1.GetName") Dim method1 = prop1.SetMethod Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, method1, preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetMethodDefNames(), "set_GetName") End Using diff1.VerifyIL("Module1.set_GetName", " { // Code size 2 (0x2) .maxstack 0 IL_0000: nop IL_0001: ret } ") End Using End Sub <Fact> Public Sub PropertyGetterReturnValueVariable() Dim source0 = <compilation> <file name="a.vb"> Module Module1 ReadOnly Property P Get P = 1 End Get End Property End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module Module1 ReadOnly Property P Get P = 2 End Get End Property End Module</file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim getter0 = compilation0.GetMember(Of PropertySymbol)("Module1.P").GetMethod Dim getter1 = compilation1.GetMember(Of PropertySymbol)("Module1.P").GetMethod Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("Module1.get_P").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, getter0, getter1, preserveLocalVariables:=True))) diff1.VerifyIL("Module1.get_P", " { // Code size 10 (0xa) .maxstack 1 .locals init (Object V_0) //P IL_0000: nop IL_0001: ldc.i4.2 IL_0002: box ""Integer"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ret }") End Using End Sub #Region "Local Slots" <Fact, WorkItem(828389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/828389")> Public Sub CatchClause() Dim source0 = <compilation> <file name="a.vb"> Class C Shared Sub M() Try System.Console.WriteLine(1) Catch ex As System.Exception End Try End Sub End Class </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Class C Shared Sub M() Try System.Console.WriteLine(2) Catch ex As System.Exception End Try End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 28 (0x1c) .maxstack 2 .locals init (System.Exception V_0) //ex IL_0000: nop .try { IL_0001: nop IL_0002: ldc.i4.2 IL_0003: call ""Sub System.Console.WriteLine(Integer)"" IL_0008: nop IL_0009: leave.s IL_001a } catch System.Exception { IL_000b: dup IL_000c: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_0011: stloc.0 IL_0012: nop IL_0013: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_0018: leave.s IL_001a } IL_001a: nop IL_001b: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PreserveLocalSlots() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim x As Object = F() Dim y As A(Of B) = F() Dim z As Object = F() M(x) M(y) M(z) End Sub Shared Sub N() Dim a As Object = F() Dim b As Object = F() M(a) M(b) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim z As B = F() Dim y As A(Of B) = F() Dim w As Object = F() M(w) M(y) End Sub Shared Sub N() Dim a As Object = F() Dim b As Object = F() M(a) M(b) End Sub End Class ]]></file> </compilation> Dim sources2 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim x As Object = F() Dim z As B = F() M(x) M(z) End Sub Shared Sub N() Dim a As Object = F() Dim b As Object = F() M(a) M(b) End Sub End Class ]]></file> </compilation> Dim sources3 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim x As Object = F() Dim z As B = F() M(x) M(z) End Sub Shared Sub N() Dim c As Object = F() Dim b As Object = F() M(c) M(b) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim compilation3 = compilation2.WithSource(sources3) ' Verify full metadata contains expected rows. Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("B.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("B.M") Dim methodN = compilation0.GetMember(Of MethodSymbol)("B.N") Dim generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), Function(m) Select Case MetadataTokens.GetRowNumber(m) Case 4 Return testData0.GetMethodData("B.M").GetEncDebugInfo() Case 5 Return testData0.GetMethodData("B.N").GetEncDebugInfo() Case Else Return Nothing End Select End Function) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.VerifyIL(" { // Code size 41 (0x29) .maxstack 1 IL_0000: nop IL_0001: call 0x06000003 IL_0006: stloc.3 IL_0007: call 0x06000003 IL_000c: stloc.1 IL_000d: call 0x06000003 IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: call 0x0A000007 IL_001b: call 0x06000004 IL_0020: nop IL_0021: ldloc.1 IL_0022: call 0x06000004 IL_0027: nop IL_0028: ret } ") diff1.VerifyPdb({&H06000001UI, &H06000002UI, &H06000003UI, &H06000004UI, &H06000005UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000004"> <sequencePoints> <entry offset="0x0" startLine="8" startColumn="5" endLine="8" endColumn="30" document="1"/> <entry offset="0x1" startLine="9" startColumn="13" endLine="9" endColumn="25" document="1"/> <entry offset="0x7" startLine="10" startColumn="13" endLine="10" endColumn="31" document="1"/> <entry offset="0xd" startLine="11" startColumn="13" endLine="11" endColumn="30" document="1"/> <entry offset="0x14" startLine="12" startColumn="9" endLine="12" endColumn="13" document="1"/> <entry offset="0x21" startLine="13" startColumn="9" endLine="13" endColumn="13" document="1"/> <entry offset="0x28" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x29"> <currentnamespace name=""/> <local name="z" il_index="3" il_start="0x0" il_end="0x29" attributes="0"/> <local name="y" il_index="1" il_start="0x0" il_end="0x29" attributes="0"/> <local name="w" il_index="4" il_start="0x0" il_end="0x29" attributes="0"/> </scope> </method> </methods> </symbols>) Dim method2 = compilation2.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B").GetMember(Of MethodSymbol)("M") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables:=True))) diff2.VerifyIL(" { // Code size 35 (0x23) .maxstack 1 IL_0000: nop IL_0001: call 0x06000003 IL_0006: stloc.s V_5 IL_0008: call 0x06000003 IL_000d: stloc.3 IL_000e: ldloc.s V_5 IL_0010: call 0x0A000008 IL_0015: call 0x06000004 IL_001a: nop IL_001b: ldloc.3 IL_001c: call 0x06000004 IL_0021: nop IL_0022: ret } ") diff2.VerifyPdb({&H06000001UI, &H06000002UI, &H06000003UI, &H06000004UI, &H06000005UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000004"> <sequencePoints> <entry offset="0x0" startLine="8" startColumn="5" endLine="8" endColumn="30" document="1"/> <entry offset="0x1" startLine="9" startColumn="13" endLine="9" endColumn="30" document="1"/> <entry offset="0x8" startLine="10" startColumn="13" endLine="10" endColumn="25" document="1"/> <entry offset="0xe" startLine="11" startColumn="9" endLine="11" endColumn="13" document="1"/> <entry offset="0x1b" startLine="12" startColumn="9" endLine="12" endColumn="13" document="1"/> <entry offset="0x22" startLine="13" startColumn="5" endLine="13" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x23"> <currentnamespace name=""/> <local name="x" il_index="5" il_start="0x0" il_end="0x23" attributes="0"/> <local name="z" il_index="3" il_start="0x0" il_end="0x23" attributes="0"/> </scope> </method> </methods> </symbols>) ' Modify different method. (Previous generations ' have not referenced method.) method2 = compilation2.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B").GetMember(Of MethodSymbol)("N") Dim method3 = compilation3.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B").GetMember(Of MethodSymbol)("N") Dim metadata3 As ImmutableArray(Of Byte) = Nothing Dim il3 As ImmutableArray(Of Byte) = Nothing Dim pdb3 As Stream = Nothing Dim diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables:=True))) diff3.VerifyIL(" { // Code size 38 (0x26) .maxstack 1 IL_0000: nop IL_0001: call 0x06000003 IL_0006: stloc.2 IL_0007: call 0x06000003 IL_000c: stloc.1 IL_000d: ldloc.2 IL_000e: call 0x0A000009 IL_0013: call 0x06000004 IL_0018: nop IL_0019: ldloc.1 IL_001a: call 0x0A000009 IL_001f: call 0x06000004 IL_0024: nop IL_0025: ret } ") diff3.VerifyPdb({&H06000001UI, &H06000002UI, &H06000003UI, &H06000004UI, &H06000005UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000005"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="19" document="1"/> <entry offset="0x1" startLine="15" startColumn="13" endLine="15" endColumn="30" document="1"/> <entry offset="0x7" startLine="16" startColumn="13" endLine="16" endColumn="30" document="1"/> <entry offset="0xd" startLine="17" startColumn="9" endLine="17" endColumn="13" document="1"/> <entry offset="0x19" startLine="18" startColumn="9" endLine="18" endColumn="13" document="1"/> <entry offset="0x25" startLine="19" startColumn="5" endLine="19" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x26"> <currentnamespace name=""/> <local name="c" il_index="2" il_start="0x0" il_end="0x26" attributes="0"/> <local name="b" il_index="1" il_start="0x0" il_end="0x26" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub ''' <summary> ''' Preserve locals for method added after initial compilation. ''' </summary> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PreserveLocalSlots_NewMethod() Dim sources0 = <compilation> <file><![CDATA[ Class C End Class ]]></file> </compilation> Dim sources1 = <compilation> <file><![CDATA[ Class C Shared Sub M() Dim a = New Object() Dim b = String.Empty End Sub End Class ]]></file> </compilation> Dim sources2 = <compilation> <file><![CDATA[ Class C Shared Sub M() Dim a = 1 Dim b = String.Empty End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim bytes0 = compilation0.EmitToArray() Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, method1, Nothing, preserveLocalVariables:=True))) Dim method2 = compilation2.GetMember(Of MethodSymbol)("C.M") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables:=True))) diff2.VerifyIL("C.M", <![CDATA[ { // Code size 10 (0xa) .maxstack 1 .locals init ([object] V_0, String V_1, //b Integer V_2) //a IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldsfld "String.Empty As String" IL_0008: stloc.1 IL_0009: ret } ]]>.Value) diff2.VerifyPdb({&H06000002UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000002"> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="19" document="1"/> <entry offset="0x1" startLine="3" startColumn="13" endLine="3" endColumn="18" document="1"/> <entry offset="0x3" startLine="4" startColumn="13" endLine="4" endColumn="29" document="1"/> <entry offset="0x9" startLine="5" startColumn="5" endLine="5" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xa"> <currentnamespace name=""/> <local name="a" il_index="2" il_start="0x0" il_end="0xa" attributes="0"/> <local name="b" il_index="1" il_start="0x0" il_end="0xa" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub ''' <summary> ''' Local types should be retained, even if the local is no longer ''' used by the method body, since there may be existing ''' references to that slot, in a Watch window for instance. ''' </summary> <WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")> <Fact> Public Sub PreserveLocalTypes() Dim sources0 = <compilation> <file><![CDATA[ Class C Shared Sub Main() Dim x = True Dim y = x System.Console.WriteLine(y) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file><![CDATA[ Class C Shared Sub Main() Dim x = "A" Dim y = x System.Console.WriteLine(y) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.Main") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.Main") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.VerifyIL("C.Main", " { // Code size 17 (0x11) .maxstack 1 .locals init ([bool] V_0, [bool] V_1, String V_2, //x String V_3) //y IL_0000: nop IL_0001: ldstr ""A"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: stloc.3 IL_0009: ldloc.3 IL_000a: call ""Sub System.Console.WriteLine(String)"" IL_000f: nop IL_0010: ret }") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsReferences() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x = new system.collections.generic.stack(of Integer) x.Push(1) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, XmlReferences, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.Stack(Of Integer) V_0) //x IL_0000: nop IL_0001: newobj ""Sub System.Collections.Generic.Stack(Of Integer)..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt ""Sub System.Collections.Generic.Stack(Of Integer).Push(Integer)"" IL_000e: nop IL_000f: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim modMeta = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(modMeta, testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", <![CDATA[ { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.Stack(Of Integer) V_0) //x IL_0000: nop IL_0001: newobj "Sub System.Collections.Generic.Stack(Of Integer)..ctor()" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt "Sub System.Collections.Generic.Stack(Of Integer).Push(Integer)" IL_000e: nop IL_000f: ret } ]]>.Value) End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsUsing() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.IDisposable = nothing Using x end using End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 21 (0x15) .maxstack 1 .locals init (System.IDisposable V_0, //x System.IDisposable V_1) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 .try { IL_0006: leave.s IL_0014 } finally { IL_0008: nop IL_0009: ldloc.1 IL_000a: brfalse.s IL_0013 IL_000c: ldloc.1 IL_000d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0012: nop IL_0013: endfinally } IL_0014: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 21 (0x15) .maxstack 1 .locals init (System.IDisposable V_0, //x System.IDisposable V_1) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 .try { IL_0006: leave.s IL_0014 } finally { IL_0008: nop IL_0009: ldloc.1 IL_000a: brfalse.s IL_0013 IL_000c: ldloc.1 IL_000d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0012: nop IL_0013: endfinally } IL_0014: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsWithByRef() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing With x(3) .ToString() end With End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 27 (0x1b) .maxstack 2 .locals init (System.Guid() V_0, //x System.Guid& V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: ldc.i4.3 IL_0006: ldelema ""System.Guid"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: constrained. ""System.Guid"" IL_0013: callvirt ""Function Object.ToString() As String"" IL_0018: pop IL_0019: nop IL_001a: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 27 (0x1b) .maxstack 2 .locals init (System.Guid() V_0, //x System.Guid& V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: ldc.i4.3 IL_0006: ldelema ""System.Guid"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: constrained. ""System.Guid"" IL_0013: callvirt ""Function Object.ToString() As String"" IL_0018: pop IL_0019: nop IL_001a: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsWithByVal() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing With x .ToString() end With End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 17 (0x11) .maxstack 1 .locals init (System.Guid() V_0, //x System.Guid() V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: pop IL_000d: nop IL_000e: ldnull IL_000f: stloc.1 IL_0010: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 17 (0x11) .maxstack 1 .locals init (System.Guid() V_0, //x System.Guid() V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: pop IL_000d: nop IL_000e: ldnull IL_000f: stloc.1 IL_0010: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsSyncLock() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing SyncLock x dim y as System.Guid() = nothing SyncLock y x.ToString() end SyncLock end SyncLock End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 76 (0x4c) .maxstack 2 .locals init (System.Guid() V_0, //x Object V_1, Boolean V_2, System.Guid() V_3, //y Object V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldc.i4.0 IL_0007: stloc.2 .try { IL_0008: ldloc.1 IL_0009: ldloca.s V_2 IL_000b: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0010: nop IL_0011: ldnull IL_0012: stloc.3 IL_0013: nop IL_0014: ldloc.3 IL_0015: stloc.s V_4 IL_0017: ldc.i4.0 IL_0018: stloc.s V_5 .try { IL_001a: ldloc.s V_4 IL_001c: ldloca.s V_5 IL_001e: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0023: nop IL_0024: ldloc.0 IL_0025: callvirt ""Function Object.ToString() As String"" IL_002a: pop IL_002b: leave.s IL_003b } finally { IL_002d: ldloc.s V_5 IL_002f: brfalse.s IL_0039 IL_0031: ldloc.s V_4 IL_0033: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0038: nop IL_0039: nop IL_003a: endfinally } IL_003b: nop IL_003c: leave.s IL_004a } finally { IL_003e: ldloc.2 IL_003f: brfalse.s IL_0048 IL_0041: ldloc.1 IL_0042: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0047: nop IL_0048: nop IL_0049: endfinally } IL_004a: nop IL_004b: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 76 (0x4c) .maxstack 2 .locals init (System.Guid() V_0, //x Object V_1, Boolean V_2, System.Guid() V_3, //y Object V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldc.i4.0 IL_0007: stloc.2 .try { IL_0008: ldloc.1 IL_0009: ldloca.s V_2 IL_000b: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0010: nop IL_0011: ldnull IL_0012: stloc.3 IL_0013: nop IL_0014: ldloc.3 IL_0015: stloc.s V_4 IL_0017: ldc.i4.0 IL_0018: stloc.s V_5 .try { IL_001a: ldloc.s V_4 IL_001c: ldloca.s V_5 IL_001e: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0023: nop IL_0024: ldloc.0 IL_0025: callvirt ""Function Object.ToString() As String"" IL_002a: pop IL_002b: leave.s IL_003b } finally { IL_002d: ldloc.s V_5 IL_002f: brfalse.s IL_0039 IL_0031: ldloc.s V_4 IL_0033: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0038: nop IL_0039: nop IL_003a: endfinally } IL_003b: nop IL_003c: leave.s IL_004a } finally { IL_003e: ldloc.2 IL_003f: brfalse.s IL_0048 IL_0041: ldloc.1 IL_0042: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0047: nop IL_0048: nop IL_0049: endfinally } IL_004a: nop IL_004b: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsForEach() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Collections.Generic.List(of integer) = nothing for each [i] in [x] Next for each i as integer in x Next End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 101 (0x65) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x System.Collections.Generic.List(Of Integer).Enumerator V_1, Integer V_2, //i Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Integer V_5, //i Boolean V_6) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.1 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_1 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.2 IL_0014: nop IL_0015: ldloca.s V_1 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_1 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0046 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.s V_5 IL_0045: nop IL_0046: ldloca.s V_4 IL_0048: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004d: stloc.s V_6 IL_004f: ldloc.s V_6 IL_0051: brtrue.s IL_003c IL_0053: leave.s IL_0064 } finally { IL_0055: ldloca.s V_4 IL_0057: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0062: nop IL_0063: endfinally } IL_0064: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 101 (0x65) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x System.Collections.Generic.List(Of Integer).Enumerator V_1, Integer V_2, //i Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Integer V_5, //i Boolean V_6) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.1 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_1 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.2 IL_0014: nop IL_0015: ldloca.s V_1 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_1 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0046 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.s V_5 IL_0045: nop IL_0046: ldloca.s V_4 IL_0048: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004d: stloc.s V_6 IL_004f: ldloc.s V_6 IL_0051: brtrue.s IL_003c IL_0053: leave.s IL_0064 } finally { IL_0055: ldloca.s V_4 IL_0057: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0062: nop IL_0063: endfinally } IL_0064: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsForEach001() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Collections.Generic.List(of integer) = nothing Dim i as integer for each i in x Next for each i in x Next End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 100 (0x64) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x Integer V_1, //i System.Collections.Generic.List(Of Integer).Enumerator V_2, Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.2 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_2 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.1 IL_0014: nop IL_0015: ldloca.s V_2 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_2 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0045 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.1 IL_0044: nop IL_0045: ldloca.s V_4 IL_0047: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004c: stloc.s V_5 IL_004e: ldloc.s V_5 IL_0050: brtrue.s IL_003c IL_0052: leave.s IL_0063 } finally { IL_0054: ldloca.s V_4 IL_0056: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005c: callvirt ""Sub System.IDisposable.Dispose()"" IL_0061: nop IL_0062: endfinally } IL_0063: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 100 (0x64) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x Integer V_1, //i System.Collections.Generic.List(Of Integer).Enumerator V_2, Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.2 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_2 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.1 IL_0014: nop IL_0015: ldloca.s V_2 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_2 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0045 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.1 IL_0044: nop IL_0045: ldloca.s V_4 IL_0047: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004c: stloc.s V_5 IL_004e: ldloc.s V_5 IL_0050: brtrue.s IL_003c IL_0052: leave.s IL_0063 } finally { IL_0054: ldloca.s V_4 IL_0056: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005c: callvirt ""Sub System.IDisposable.Dispose()"" IL_0061: nop IL_0062: endfinally } IL_0063: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsFor001() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As object) for i as double = goo() to goo() step goo() for j as double = goo() to goo() step goo() next next End Sub shared function goo() as double return 1 end function End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 148 (0x94) .maxstack 2 .locals init (Double V_0, Double V_1, Double V_2, Boolean V_3, Double V_4, //i Double V_5, Double V_6, Double V_7, Boolean V_8, Double V_9) //j IL_0000: nop IL_0001: call ""Function C.goo() As Double"" IL_0006: stloc.0 IL_0007: call ""Function C.goo() As Double"" IL_000c: stloc.1 IL_000d: call ""Function C.goo() As Double"" IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldc.r8 0 IL_001d: clt.un IL_001f: ldc.i4.0 IL_0020: ceq IL_0022: stloc.3 IL_0023: ldloc.0 IL_0024: stloc.s V_4 IL_0026: br.s IL_007c IL_0028: call ""Function C.goo() As Double"" IL_002d: stloc.s V_5 IL_002f: call ""Function C.goo() As Double"" IL_0034: stloc.s V_6 IL_0036: call ""Function C.goo() As Double"" IL_003b: stloc.s V_7 IL_003d: ldloc.s V_7 IL_003f: ldc.r8 0 IL_0048: clt.un IL_004a: ldc.i4.0 IL_004b: ceq IL_004d: stloc.s V_8 IL_004f: ldloc.s V_5 IL_0051: stloc.s V_9 IL_0053: br.s IL_005c IL_0055: ldloc.s V_9 IL_0057: ldloc.s V_7 IL_0059: add IL_005a: stloc.s V_9 IL_005c: ldloc.s V_8 IL_005e: brtrue.s IL_006b IL_0060: ldloc.s V_9 IL_0062: ldloc.s V_6 IL_0064: clt.un IL_0066: ldc.i4.0 IL_0067: ceq IL_0069: br.s IL_0074 IL_006b: ldloc.s V_9 IL_006d: ldloc.s V_6 IL_006f: cgt.un IL_0071: ldc.i4.0 IL_0072: ceq IL_0074: brtrue.s IL_0055 IL_0076: ldloc.s V_4 IL_0078: ldloc.2 IL_0079: add IL_007a: stloc.s V_4 IL_007c: ldloc.3 IL_007d: brtrue.s IL_0089 IL_007f: ldloc.s V_4 IL_0081: ldloc.1 IL_0082: clt.un IL_0084: ldc.i4.0 IL_0085: ceq IL_0087: br.s IL_0091 IL_0089: ldloc.s V_4 IL_008b: ldloc.1 IL_008c: cgt.un IL_008e: ldc.i4.0 IL_008f: ceq IL_0091: brtrue.s IL_0028 IL_0093: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 148 (0x94) .maxstack 2 .locals init (Double V_0, Double V_1, Double V_2, Boolean V_3, Double V_4, //i Double V_5, Double V_6, Double V_7, Boolean V_8, Double V_9) //j IL_0000: nop IL_0001: call ""Function C.goo() As Double"" IL_0006: stloc.0 IL_0007: call ""Function C.goo() As Double"" IL_000c: stloc.1 IL_000d: call ""Function C.goo() As Double"" IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldc.r8 0 IL_001d: clt.un IL_001f: ldc.i4.0 IL_0020: ceq IL_0022: stloc.3 IL_0023: ldloc.0 IL_0024: stloc.s V_4 IL_0026: br.s IL_007c IL_0028: call ""Function C.goo() As Double"" IL_002d: stloc.s V_5 IL_002f: call ""Function C.goo() As Double"" IL_0034: stloc.s V_6 IL_0036: call ""Function C.goo() As Double"" IL_003b: stloc.s V_7 IL_003d: ldloc.s V_7 IL_003f: ldc.r8 0 IL_0048: clt.un IL_004a: ldc.i4.0 IL_004b: ceq IL_004d: stloc.s V_8 IL_004f: ldloc.s V_5 IL_0051: stloc.s V_9 IL_0053: br.s IL_005c IL_0055: ldloc.s V_9 IL_0057: ldloc.s V_7 IL_0059: add IL_005a: stloc.s V_9 IL_005c: ldloc.s V_8 IL_005e: brtrue.s IL_006b IL_0060: ldloc.s V_9 IL_0062: ldloc.s V_6 IL_0064: clt.un IL_0066: ldc.i4.0 IL_0067: ceq IL_0069: br.s IL_0074 IL_006b: ldloc.s V_9 IL_006d: ldloc.s V_6 IL_006f: cgt.un IL_0071: ldc.i4.0 IL_0072: ceq IL_0074: brtrue.s IL_0055 IL_0076: ldloc.s V_4 IL_0078: ldloc.2 IL_0079: add IL_007a: stloc.s V_4 IL_007c: ldloc.3 IL_007d: brtrue.s IL_0089 IL_007f: ldloc.s V_4 IL_0081: ldloc.1 IL_0082: clt.un IL_0084: ldc.i4.0 IL_0085: ceq IL_0087: br.s IL_0091 IL_0089: ldloc.s V_4 IL_008b: ldloc.1 IL_008c: cgt.un IL_008e: ldc.i4.0 IL_008f: ceq IL_0091: brtrue.s IL_0028 IL_0093: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicit() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ option explicit off Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing With x Dim z = .ToString y = z end With End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 19 (0x13) .maxstack 1 .locals init (Object V_0, //y System.Guid() V_1, //x System.Guid() V_2, //$W0 String V_3) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: nop IL_0004: ldloc.1 IL_0005: stloc.2 IL_0006: ldloc.2 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: stloc.3 IL_000d: ldloc.3 IL_000e: stloc.0 IL_000f: nop IL_0010: ldnull IL_0011: stloc.2 IL_0012: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 19 (0x13) .maxstack 1 .locals init (Object V_0, //y System.Guid() V_1, //x System.Guid() V_2, //$W0 String V_3) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: nop IL_0004: ldloc.1 IL_0005: stloc.2 IL_0006: ldloc.2 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: stloc.3 IL_000d: ldloc.3 IL_000e: stloc.0 IL_000f: nop IL_0010: ldnull IL_0011: stloc.2 IL_0012: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicitQualified() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ option explicit off Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing goto Length ' this does not declare Length Length: ' this does not declare Length dim y = x.Length ' this does not declare Length Length = 5 ' this does End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim actualIL0 = testData0.GetMethodData("C.M").GetMethodIL() Dim expectedIL0 = " { // Code size 18 (0x12) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Integer V_2) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: br.s IL_0005 IL_0005: nop IL_0006: ldloc.1 IL_0007: ldlen IL_0008: conv.i4 IL_0009: stloc.2 IL_000a: ldc.i4.5 IL_000b: box ""Integer"" IL_0010: stloc.0 IL_0011: ret } " AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL0, actualIL0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 18 (0x12) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Integer V_2) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: br.s IL_0005 IL_0005: nop IL_0006: ldloc.1 IL_0007: ldlen IL_0008: conv.i4 IL_0009: stloc.2 IL_000a: ldc.i4.5 IL_000b: box ""Integer"" IL_0010: stloc.0 IL_0011: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicitXmlNs() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ option explicit off Imports <xmlns:Length="http: //roslyn/F"> Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing GetXmlNamespace(Length).ToString() ' this does not declare Length dim z as object = GetXmlNamespace(Length) ' this does not declare Length Length = 5 ' this does Dim aa = Length End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, XmlReferences, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 45 (0x2d) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Object V_2, //z Object V_3) //aa IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: ldstr ""http: //roslyn/F"" IL_0008: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_000d: callvirt ""Function System.Xml.Linq.XNamespace.ToString() As String"" IL_0012: pop IL_0013: ldstr ""http: //roslyn/F"" IL_0018: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_001d: stloc.2 IL_001e: ldc.i4.5 IL_001f: box ""Integer"" IL_0024: stloc.0 IL_0025: ldloc.0 IL_0026: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_002b: stloc.3 IL_002c: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 45 (0x2d) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Object V_2, //z Object V_3) //aa IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: ldstr ""http: //roslyn/F"" IL_0008: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_000d: callvirt ""Function System.Xml.Linq.XNamespace.ToString() As String"" IL_0012: pop IL_0013: ldstr ""http: //roslyn/F"" IL_0018: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_001d: stloc.2 IL_001e: ldc.i4.5 IL_001f: box ""Integer"" IL_0024: stloc.0 IL_0025: ldloc.0 IL_0026: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_002b: stloc.3 IL_002c: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicitNamedArgXml() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Option Explicit Off Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub F(qq As Object) End Sub Shared Sub M(o As Object) F(qq:=<qq a="qq"></>) 'does not declare qq qq = 5 Dim aa = qq End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, XmlReferences, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim actualIL0 = testData0.GetMethodData("C.M").GetMethodIL() Dim expectedIL0 = <![CDATA[ { // Code size 88 (0x58) .maxstack 3 .locals init (Object V_0, //qq Object V_1, //aa System.Xml.Linq.XElement V_2) IL_0000: nop IL_0001: ldstr "qq" IL_0006: ldstr "" IL_000b: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0010: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0015: stloc.2 IL_0016: ldloc.2 IL_0017: ldstr "a" IL_001c: ldstr "" IL_0021: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0026: ldstr "qq" IL_002b: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_0030: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0035: nop IL_0036: ldloc.2 IL_0037: ldstr "" IL_003c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0041: nop IL_0042: ldloc.2 IL_0043: call "Sub C.F(Object)" IL_0048: nop IL_0049: ldc.i4.5 IL_004a: box "Integer" IL_004f: stloc.0 IL_0050: ldloc.0 IL_0051: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0056: stloc.1 IL_0057: ret } ]]>.Value AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL0, actualIL0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", <![CDATA[ { // Code size 88 (0x58) .maxstack 3 .locals init (Object V_0, //qq Object V_1, //aa [unchanged] V_2, System.Xml.Linq.XElement V_3) IL_0000: nop IL_0001: ldstr "qq" IL_0006: ldstr "" IL_000b: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0010: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0015: stloc.3 IL_0016: ldloc.3 IL_0017: ldstr "a" IL_001c: ldstr "" IL_0021: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0026: ldstr "qq" IL_002b: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_0030: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0035: nop IL_0036: ldloc.3 IL_0037: ldstr "" IL_003c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0041: nop IL_0042: ldloc.3 IL_0043: call "Sub C.F(Object)" IL_0048: nop IL_0049: ldc.i4.5 IL_004a: box "Integer" IL_004f: stloc.0 IL_0050: ldloc.0 IL_0051: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0056: stloc.1 IL_0057: ret } ]]>.Value) End Sub <Fact> Public Sub AnonymousTypes_Update() Dim source0 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 1 } End Sub End Class ") Dim source1 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 2 } End Sub End Class ") Dim source2 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 3 } End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) v0.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") ' expect a single TypeRef for System.Object Dim md1 = diff1.GetMetadata() AssertEx.Equal({"[0x23000002] 0x0000020d.0x0000021a"}, DumpTypeRefs(md1.Reader)) Dim diff2 = compilation2.EmitDifference(diff1.NextGeneration, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") ' expect a single TypeRef for System.Object Dim md2 = diff2.GetMetadata() AssertEx.Equal({"[0x23000003] 0x00000256.0x00000263"}, DumpTypeRefs(md2.Reader)) End Sub <Fact> Public Sub AnonymousTypes_UpdateAfterAdd() Dim source0 = MarkedSource(" Class C Shared Sub F() End Sub End Class ") Dim source1 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 2 } End Sub End Class ") Dim source2 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 3 } End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") Dim diff2 = compilation2.EmitDifference(diff1.NextGeneration, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") ' expect a single TypeRef for System.Object Dim md2 = diff2.GetMetadata() AssertEx.Equal({"[0x23000003] 0x00000289.0x00000296"}, DumpTypeRefs(md2.Reader)) End Sub Private Shared Iterator Function DumpTypeRefs(reader As MetadataReader) As IEnumerable(Of String) For Each typeRefHandle In reader.TypeReferences Dim typeRef = reader.GetTypeReference(typeRefHandle) Yield $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] 0x{MetadataTokens.GetHeapOffset(typeRef.Namespace):x8}.0x{MetadataTokens.GetHeapOffset(typeRef.Name):x8}" Next End Function <Fact> Public Sub AnonymousTypes() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Namespace N Class A Shared F As Object = New With {.A = 1, .B = 2} End Class End Namespace Namespace M Class B Shared Sub M() Dim x As New With {.B = 3, .A = 4} Dim y = x.A Dim z As New With {.C = 5} End Sub End Class End Namespace ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Namespace N Class A Shared F As Object = New With {.A = 1, .B = 2} End Class End Namespace Namespace M Class B Shared Sub M() Dim x As New With {.B = 3, .A = 4} Dim y As New With {.A = x.A} Dim z As New With {.C = 5} End Sub End Class End Namespace ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("M.B.M").EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("M.B.M") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`2", "VB$AnonymousType_1`2", "VB$AnonymousType_2`1", "A", "B") Dim method1 = compilation1.GetMember(Of MethodSymbol)("M.B.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_3`1") diff1.VerifyIL("M.B.M", " { // Code size 29 (0x1d) .maxstack 2 .locals init (VB$AnonymousType_1(Of Integer, Integer) V_0, //x [int] V_1, VB$AnonymousType_2(Of Integer) V_2, //z VB$AnonymousType_3(Of Integer) V_3) //y IL_0000: nop IL_0001: ldc.i4.3 IL_0002: ldc.i4.4 IL_0003: newobj ""Sub VB$AnonymousType_1(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""Function VB$AnonymousType_1(Of Integer, Integer).get_A() As Integer"" IL_000f: newobj ""Sub VB$AnonymousType_3(Of Integer)..ctor(Integer)"" IL_0014: stloc.3 IL_0015: ldc.i4.5 IL_0016: newobj ""Sub VB$AnonymousType_2(Of Integer)..ctor(Integer)"" IL_001b: stloc.2 IL_001c: ret } ") End Using End Using End Sub ''' <summary> ''' Update method with anonymous type that was ''' not directly referenced in previous generation. ''' </summary> <Fact> Public Sub AnonymousTypes_SkipGeneration() Dim source0 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As Integer = 1 Return x End Function End Class ") Dim source1 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As Integer = 1 Return x + 1 End Function End Class ") Dim source2 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As New With {.A = New A()} Dim <N:2>y</N:2> As New With {.B = 2} Return x.A End Function End Class ") Dim source3 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As New With {.A = New A()} Dim <N:2>y</N:2> As New With {.B = 3} Return y.B End Function End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim compilation3 = compilation2.WithSource(source3.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim method0 = compilation0.GetMember(Of MethodSymbol)("B.G") Dim method1 = compilation1.GetMember(Of MethodSymbol)("B.G") Dim method2 = compilation2.GetMember(Of MethodSymbol)("B.G") Dim method3 = compilation3.GetMember(Of MethodSymbol)("B.G") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`1", "A", "B") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) Dim md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames()) ' no additional types diff1.VerifyIL("B.G", " { // Code size 16 (0x10) .maxstack 2 .locals init (Object V_0, //G Integer V_1) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.1 IL_0003: ldloc.1 IL_0004: ldc.i4.1 IL_0005: add.ovf IL_0006: box ""Integer"" IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } ") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) Dim md2 = diff2.GetMetadata() Dim reader2 = md2.Reader CheckNames({reader0, reader1, reader2}, reader2.GetTypeDefNames(), "VB$AnonymousType_1`1") ' one additional type diff2.VerifyIL("B.G", " { // Code size 30 (0x1e) .maxstack 1 .locals init (Object V_0, //G [int] V_1, VB$AnonymousType_0(Of A) V_2, //x VB$AnonymousType_1(Of Integer) V_3) //y IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: newobj ""Sub VB$AnonymousType_0(Of A)..ctor(A)"" IL_000b: stloc.2 IL_000c: ldc.i4.2 IL_000d: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_0012: stloc.3 IL_0013: ldloc.2 IL_0014: callvirt ""Function VB$AnonymousType_0(Of A).get_A() As A"" IL_0019: stloc.0 IL_001a: br.s IL_001c IL_001c: ldloc.0 IL_001d: ret } ") Dim diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables:=True))) Dim md3 = diff3.GetMetadata() Dim reader3 = md3.Reader CheckNames({reader0, reader1, reader2, reader3}, reader3.GetTypeDefNames()) ' no additional types diff3.VerifyIL("B.G", " { // Code size 35 (0x23) .maxstack 1 .locals init (Object V_0, //G [int] V_1, VB$AnonymousType_0(Of A) V_2, //x VB$AnonymousType_1(Of Integer) V_3) //y IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: newobj ""Sub VB$AnonymousType_0(Of A)..ctor(A)"" IL_000b: stloc.2 IL_000c: ldc.i4.3 IL_000d: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: callvirt ""Function VB$AnonymousType_1(Of Integer).get_B() As Integer"" IL_0019: box ""Integer"" IL_001e: stloc.0 IL_001f: br.s IL_0021 IL_0021: ldloc.0 IL_0022: ret } ") End Sub ''' <summary> ''' Update another method (without directly referencing ''' anonymous type) after updating method with anonymous type. ''' </summary> <Fact> Public Sub AnonymousTypes_SkipGeneration_2() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 1} Return x.A End Function Shared Function G() As Object Dim x As Integer = 1 Return x End Function End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 2, .B = 3} Return x.A End Function Shared Function G() As Object Dim x As Integer = 1 Return x End Function End Class ]]></file> </compilation> Dim sources2 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 2, .B = 3} Return x.A End Function Shared Function G() As Object Dim x As Integer = 1 Return x + 1 End Function End Class ]]></file> </compilation> Dim sources3 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 2, .B = 3} Return x.A End Function Shared Function G() As Object Dim x As New With {.A = DirectCast(Nothing, Object)} Dim y As New With {.A = "a"c, .B = "b"c} Return x End Function End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim compilation3 = compilation2.WithSource(sources3) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), Function(m) Select Case md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) Case "F" : Return testData0.GetMethodData("C.F").GetEncDebugInfo() Case "G" : Return testData0.GetMethodData("C.G").GetEncDebugInfo() End Select Return Nothing End Function) Dim method0F = compilation0.GetMember(Of MethodSymbol)("C.F") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`1", "C") Dim method1F = compilation1.GetMember(Of MethodSymbol)("C.F") Dim method1G = compilation1.GetMember(Of MethodSymbol)("C.G") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0F, method1F, GetEquivalentNodesMap(method1F, method0F), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_1`2") ' one additional type Dim method2G = compilation2.GetMember(Of MethodSymbol)("C.G") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1G, method2G, GetEquivalentNodesMap(method2G, method1G), preserveLocalVariables:=True))) Using md2 = diff2.GetMetadata() Dim reader2 = md2.Reader CheckNames({reader0, reader1, reader2}, reader2.GetTypeDefNames()) ' no additional types Dim method3G = compilation3.GetMember(Of MethodSymbol)("C.G") Dim diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method2G, method3G, GetEquivalentNodesMap(method3G, method2G), preserveLocalVariables:=True))) Using md3 = diff3.GetMetadata() Dim reader3 = md3.Reader CheckNames({reader0, reader1, reader2, reader3}, reader3.GetTypeDefNames()) ' no additional types End Using End Using End Using End Using End Sub <WorkItem(1292, "https://github.com/dotnet/roslyn/issues/1292")> <Fact> Public Sub AnonymousTypes_Key() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.A = 1, .B = 2} Dim y As New With {Key .A = 3, .B = 4} Dim z As New With {.A = 5, Key .B = 6} End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.A = 1, .B = 2} Dim y As New With {Key .A = 3, Key .B = 4} Dim z As New With {Key .A = 5, .B = 6} End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`2", "VB$AnonymousType_1`2", "VB$AnonymousType_2`2", "C") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_3`2") diff1.VerifyIL("C.M", "{ // Code size 27 (0x1b) .maxstack 2 .locals init (VB$AnonymousType_0(Of Integer, Integer) V_0, //x [unchanged] V_1, [unchanged] V_2, VB$AnonymousType_3(Of Integer, Integer) V_3, //y VB$AnonymousType_1(Of Integer, Integer) V_4) //z IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""Sub VB$AnonymousType_0(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.0 IL_0009: ldc.i4.3 IL_000a: ldc.i4.4 IL_000b: newobj ""Sub VB$AnonymousType_3(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0010: stloc.3 IL_0011: ldc.i4.5 IL_0012: ldc.i4.6 IL_0013: newobj ""Sub VB$AnonymousType_1(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0018: stloc.s V_4 IL_001a: ret }") End Using End Using End Sub <Fact> Public Sub AnonymousTypes_DifferentCase() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.A = 1, .B = 2} Dim y As New With {.a = 3, .b = 4} End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.a = 1, .B = 2} Dim y As New With {.AB = 3} Dim z As New With {.ab = 4} End Sub End Class ]]></file> </compilation> Dim sources2 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.a = 1, .B = 2} Dim z As New With {.Ab = 5} End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`2", "C") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_1`1") diff1.VerifyIL("C.M", "{ // Code size 25 (0x19) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, VB$AnonymousType_0(Of Integer, Integer) V_2, //x VB$AnonymousType_1(Of Integer) V_3, //y VB$AnonymousType_1(Of Integer) V_4) //z IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""Sub VB$AnonymousType_0(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.2 IL_0009: ldc.i4.3 IL_000a: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_000f: stloc.3 IL_0010: ldc.i4.4 IL_0011: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_0016: stloc.s V_4 IL_0018: ret }") Dim method2 = compilation2.GetMember(Of MethodSymbol)("C.M") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables:=True))) Using md2 = diff2.GetMetadata() Dim reader2 = md2.Reader CheckNames({reader0, reader1, reader2}, reader2.GetTypeDefNames()) diff2.VerifyIL("C.M", "{ // Code size 18 (0x12) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, VB$AnonymousType_0(Of Integer, Integer) V_2, //x [unchanged] V_3, [unchanged] V_4, VB$AnonymousType_1(Of Integer) V_5) //z IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""Sub VB$AnonymousType_0(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.2 IL_0009: ldc.i4.5 IL_000a: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_000f: stloc.s V_5 IL_0011: ret }") End Using End Using End Using End Sub <Fact> Public Sub AnonymousTypes_Nested() Dim template = " Imports System Imports System.Linq Class C Sub F(args As String()) Dim <N:4>result</N:4> = From a in args Let <N:0>x = a.Reverse()</N:0> Let <N:1>y = x.Reverse()</N:1> <N:2>Where x.SequenceEqual(y)</N:2> Select <N:3>Value = a</N:3>, Length = a.Length Console.WriteLine(<<VALUE>>) End Sub End Class " Dim source0 = MarkedSource(template.Replace("<<VALUE>>", "0")) Dim source1 = MarkedSource(template.Replace("<<VALUE>>", "1")) Dim source2 = MarkedSource(template.Replace("<<VALUE>>", "2")) Dim compilation0 = CreateCompilationWithMscorlib45({source0.Tree}, {SystemCoreRef}, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation0.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim expectedIL = " { // Code size 175 (0xaf) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable(Of <anonymous type: Key Value As String, Key Length As Integer>) V_0) //result IL_0000: nop IL_0001: ldarg.1 IL_0002: ldsfld ""C._Closure$__.$I1-0 As System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0007: brfalse.s IL_0010 IL_0009: ldsfld ""C._Closure$__.$I1-0 As System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_000e: br.s IL_0026 IL_0010: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0015: ldftn ""Function C._Closure$__._Lambda$__1-0(String) As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>"" IL_001b: newobj ""Sub System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)..ctor(Object, System.IntPtr)"" IL_0020: dup IL_0021: stsfld ""C._Closure$__.$I1-0 As System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0026: call ""Function System.Linq.Enumerable.Select(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)(System.Collections.Generic.IEnumerable(Of String), System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_002b: ldsfld ""C._Closure$__.$I1-1 As System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0030: brfalse.s IL_0039 IL_0032: ldsfld ""C._Closure$__.$I1-1 As System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0037: br.s IL_004f IL_0039: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_003e: ldftn ""Function C._Closure$__._Lambda$__1-1(<anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>) As <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>"" IL_0044: newobj ""Sub System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)..ctor(Object, System.IntPtr)"" IL_0049: dup IL_004a: stsfld ""C._Closure$__.$I1-1 As System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_004f: call ""Function System.Linq.Enumerable.Select(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)(System.Collections.Generic.IEnumerable(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>), System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0054: ldsfld ""C._Closure$__.$I1-2 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)"" IL_0059: brfalse.s IL_0062 IL_005b: ldsfld ""C._Closure$__.$I1-2 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)"" IL_0060: br.s IL_0078 IL_0062: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0067: ldftn ""Function C._Closure$__._Lambda$__1-2(<anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>) As Boolean"" IL_006d: newobj ""Sub System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)..ctor(Object, System.IntPtr)"" IL_0072: dup IL_0073: stsfld ""C._Closure$__.$I1-2 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)"" IL_0078: call ""Function System.Linq.Enumerable.Where(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)(System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>), System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_007d: ldsfld ""C._Closure$__.$I1-3 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)"" IL_0082: brfalse.s IL_008b IL_0084: ldsfld ""C._Closure$__.$I1-3 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)"" IL_0089: br.s IL_00a1 IL_008b: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0090: ldftn ""Function C._Closure$__._Lambda$__1-3(<anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>) As <anonymous type: Key Value As String, Key Length As Integer>"" IL_0096: newobj ""Sub System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)..ctor(Object, System.IntPtr)"" IL_009b: dup IL_009c: stsfld ""C._Closure$__.$I1-3 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)"" IL_00a1: call ""Function System.Linq.Enumerable.Select(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)(System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>), System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key Value As String, Key Length As Integer>)"" IL_00a6: stloc.0 IL_00a7: ldc.i4.<<VALUE>> IL_00a8: call ""Sub System.Console.WriteLine(Integer)"" IL_00ad: nop IL_00ae: ret }" v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifySynthesizedMembers( "C: {_Closure$__}", "C._Closure$__: {$I1-0, $I1-1, $I1-2, $I1-3, _Lambda$__1-0, _Lambda$__1-1, _Lambda$__1-2, _Lambda$__1-3}") diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")) Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifySynthesizedMembers( "C: {_Closure$__}", "C._Closure$__: {$I1-0, $I1-1, $I1-2, $I1-3, _Lambda$__1-0, _Lambda$__1-1, _Lambda$__1-2, _Lambda$__1-3}") diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")) End Sub <Fact> Public Sub AnonymousDelegates1() Dim source0 = MarkedSource(" Class C Private Sub F() Dim <N:0>g</N:0> = <N:1>Function(ByRef arg As String) arg</N:1> System.Console.WriteLine(1) End Sub End Class ") Dim source1 = MarkedSource(" Class C Private Sub F() Dim <N:0>g</N:0> = <N:1>Function(ByRef arg As String) arg</N:1> System.Console.WriteLine(2) End Sub End Class ") Dim source2 = MarkedSource(" Class C Private Sub F() Dim <N:0>g</N:0> = <N:1>Function(ByRef arg As String) arg</N:1> System.Console.WriteLine(3) End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40({source0.Tree}, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) v0.VerifyIL("C.F", " { // Code size 46 (0x2e) .maxstack 2 .locals init (VB$AnonymousDelegate_0(Of String, String) V_0) //g IL_0000: nop IL_0001: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0006: brfalse.s IL_000f IL_0008: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_000d: br.s IL_0025 IL_000f: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0014: ldftn ""Function C._Closure$__._Lambda$__1-0(ByRef String) As String"" IL_001a: newobj ""Sub VB$AnonymousDelegate_0(Of String, String)..ctor(Object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0025: stloc.0 IL_0026: ldc.i4.1 IL_0027: call ""Sub System.Console.WriteLine(Integer)"" IL_002c: nop IL_002d: ret } ") Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 46 (0x2e) .maxstack 2 .locals init (VB$AnonymousDelegate_0(Of String, String) V_0) //g IL_0000: nop IL_0001: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0006: brfalse.s IL_000f IL_0008: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_000d: br.s IL_0025 IL_000f: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0014: ldftn ""Function C._Closure$__._Lambda$__1-0(ByRef String) As String"" IL_001a: newobj ""Sub VB$AnonymousDelegate_0(Of String, String)..ctor(Object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0025: stloc.0 IL_0026: ldc.i4.2 IL_0027: call ""Sub System.Console.WriteLine(Integer)"" IL_002c: nop IL_002d: ret } ") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifyIL("C.F", " { // Code size 46 (0x2e) .maxstack 2 .locals init (VB$AnonymousDelegate_0(Of String, String) V_0) //g IL_0000: nop IL_0001: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0006: brfalse.s IL_000f IL_0008: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_000d: br.s IL_0025 IL_000f: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0014: ldftn ""Function C._Closure$__._Lambda$__1-0(ByRef String) As String"" IL_001a: newobj ""Sub VB$AnonymousDelegate_0(Of String, String)..ctor(Object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0025: stloc.0 IL_0026: ldc.i4.3 IL_0027: call ""Sub System.Console.WriteLine(Integer)"" IL_002c: nop IL_002d: ret } ") End Sub ''' <summary> ''' Should not re-use locals with custom modifiers. ''' </summary> <Fact(Skip:="9854")> <WorkItem(9854, "https://github.com/dotnet/roslyn/issues/9854")> Public Sub LocalType_CustomModifiers() ' Equivalent method signature to VB, but ' with optional modifiers on locals. Dim ilSource = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public C { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F(class [mscorlib]System.IDisposable d) { .locals init ([0] object F, [1] class C modopt(int32) c, [2] class [mscorlib]System.IDisposable modopt(object) VB$Using, [3] bool V_3) ldnull ret } } ]]>.Value Dim source = <compilation> <file name="c.vb"><![CDATA[ Class C Shared Function F(d As System.IDisposable) As Object Dim c As C Using d c = DirectCast(d, C) End Using Return c End Function End Class ]]> </file> </compilation> Dim metadata0 = DirectCast(CompileIL(ilSource, prependDefaultHeader:=False), MetadataImageReference) ' Still need a compilation with source for the initial ' generation - to get a MethodSymbol and syntax map. Dim compilation0 = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim moduleMetadata0 = DirectCast(metadata0.GetMetadataNoCopy(), AssemblyMetadata).GetModules(0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline( moduleMetadata0, Function(m) Nothing) Dim testData1 = New CompilationTestData() Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.F", " { // Code size 45 (0x2d) .maxstack 2 .locals init ([object] V_0, [unchanged] V_1, [unchanged] V_2, [bool] V_3, Object V_4, //F C V_5, //c System.IDisposable V_6, //VB$Using Boolean V_7) IL_0000: nop IL_0001: nop IL_0002: ldarg.0 IL_0003: stloc.s V_6 .try { IL_0005: ldarg.0 IL_0006: castclass ""C"" IL_000b: stloc.s V_5 IL_000d: leave.s IL_0024 } finally { IL_000f: nop IL_0010: ldloc.s V_6 IL_0012: ldnull IL_0013: ceq IL_0015: stloc.s V_7 IL_0017: ldloc.s V_7 IL_0019: brtrue.s IL_0023 IL_001b: ldloc.s V_6 IL_001d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0022: nop IL_0023: endfinally } IL_0024: ldloc.s V_5 IL_0026: stloc.s V_4 IL_0028: br.s IL_002a IL_002a: ldloc.s V_4 IL_002c: ret } ") End Sub <WorkItem(839414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839414")> <Fact> Public Sub Bug839414() Dim source0 = <compilation> <file name="a.vb"> Module M Function F() As Object Static x = 1 Return x End Function End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module M Function F() As Object Static x = "2" Return x End Function End Module </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Dim method0 = compilation0.GetMember(Of MethodSymbol)("M.F") Dim method1 = compilation1.GetMember(Of MethodSymbol)("M.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) End Sub <WorkItem(849649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849649")> <Fact> Public Sub Bug849649() Dim source0 = <compilation> <file name="a.vb"> Module M Sub F() Dim x(5) As Integer x(3) = 2 End Sub End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module M Sub F() Dim x(5) As Integer x(3) = 3 End Sub End Module </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Dim method0 = compilation0.GetMember(Of MethodSymbol)("M.F") Dim method1 = compilation1.GetMember(Of MethodSymbol)("M.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff0 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff0.VerifyIL(" { // Code size 13 (0xd) .maxstack 3 IL_0000: nop IL_0001: ldc.i4.6 IL_0002: newarr 0x0100000A IL_0007: stloc.1 IL_0008: ldloc.1 IL_0009: ldc.i4.3 IL_000a: ldc.i4.3 IL_000b: stelem.i4 IL_000c: ret } ") End Sub #End Region <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SymWriterErrors() Dim source0 = <compilation> <file name="a.vb"><![CDATA[ Class C End Class ]]></file> </compilation> Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Class C Sub Main() End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) ' Verify full metadata contains expected rows. Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, compilation1.GetMember(Of MethodSymbol)("C.Main"))), testData:=New CompilationTestData With {.SymWriterFactory = Function() New MockSymUnmanagedWriter()}) diff1.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_PDBWritingFailed).WithArguments("MockSymUnmanagedWriter error message")) Assert.False(diff1.EmitResult.Success) End Using End Sub <WorkItem(1003274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1003274")> <Fact> Public Sub ConditionalAttribute() Const source0 = " Imports System.Diagnostics Class C Sub M() ' Body End Sub <Conditional(""Defined"")> Sub N1() End Sub <Conditional(""Undefined"")> Sub N2() End Sub End Class " Dim parseOptions As New VisualBasicParseOptions(preprocessorSymbols:={New KeyValuePair(Of String, Object)("Defined", True)}) Dim tree0 = VisualBasicSyntaxTree.ParseText(source0, parseOptions) Dim tree1 = VisualBasicSyntaxTree.ParseText(source0.Replace("' Body", "N1(): N2()"), parseOptions) Dim compilation0 = CreateCompilationWithMscorlib40({tree0}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.ReplaceSyntaxTree(tree0, tree1) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) diff1.EmitResult.Diagnostics.AssertNoErrors() diff1.VerifyIL("C.M", " { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""Sub C.N1()"" IL_0007: nop IL_0008: ret } ") End Using End Sub <Fact> Public Sub ReferenceToMemberAddedToAnotherAssembly1() Dim sourceA0 = " Public Class A End Class " Dim sourceA1 = " Public Class A Public Sub M() System.Console.WriteLine(1) End Sub End Class Public Class X End Class " Dim sourceB0 = " Public Class B Public Shared Sub F() End Sub End Class" Dim sourceB1 = " Public Class B Public Shared Sub F() Dim a = New A() a.M() End Sub End Class Public Class Y Inherits X End Class " Dim compilationA0 = CreateCompilationWithMscorlib40({sourceA0}, options:=TestOptions.DebugDll, assemblyName:="LibA") Dim compilationA1 = compilationA0.WithSource(sourceA1) Dim compilationB0 = CreateCompilationWithMscorlib40({sourceB0}, {compilationA0.ToMetadataReference()}, options:=TestOptions.DebugDll, assemblyName:="LibB") Dim compilationB1 = CreateCompilationWithMscorlib40({sourceB1}, {compilationA1.ToMetadataReference()}, options:=TestOptions.DebugDll, assemblyName:="LibB") Dim bytesA0 = compilationA0.EmitToArray() Dim bytesB0 = compilationB0.EmitToArray() Dim mdA0 = ModuleMetadata.CreateFromImage(bytesA0) Dim mdB0 = ModuleMetadata.CreateFromImage(bytesB0) Dim generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider) Dim generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider) Dim mA1 = compilationA1.GetMember(Of MethodSymbol)("A.M") Dim mX1 = compilationA1.GetMember(Of TypeSymbol)("X") Dim allAddedSymbols = New ISymbol() {mA1, mX1} Dim diffA1 = compilationA1.EmitDifference( generationA0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Insert, Nothing, mA1), New SemanticEdit(SemanticEditKind.Insert, Nothing, mX1)), allAddedSymbols) diffA1.EmitResult.Diagnostics.Verify() Dim diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, compilationB0.GetMember(Of MethodSymbol)("B.F"), compilationB1.GetMember(Of MethodSymbol)("B.F")), New SemanticEdit(SemanticEditKind.Insert, Nothing, compilationB1.GetMember(Of TypeSymbol)("Y"))), allAddedSymbols) diffB1.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(8, 14), Diagnostic(ERRID.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(3, 16)) End Sub <Fact> Public Sub ReferenceToMemberAddedToAnotherAssembly2() Dim sourceA = " Public Class A Public Sub M() End Sub End Class" Dim sourceB0 = " Public Class B Public Shared Sub F() Dim a = New A() End Sub End Class" Dim sourceB1 = " Public Class B Public Shared Sub F() Dim a = New A() a.M() End Sub End Class" Dim sourceB2 = " Public Class B Public Shared Sub F() Dim a = New A() End Sub End Class" Dim compilationA = CreateCompilationWithMscorlib40({sourceA}, options:=TestOptions.DebugDll, assemblyName:="AssemblyA") Dim aRef = compilationA.ToMetadataReference() Dim compilationB0 = CreateCompilationWithMscorlib40({sourceB0}, {aRef}, options:=TestOptions.DebugDll, assemblyName:="AssemblyB") Dim compilationB1 = compilationB0.WithSource(sourceB1) Dim compilationB2 = compilationB1.WithSource(sourceB2) Dim testDataB0 = New CompilationTestData() Dim bytesB0 = compilationB0.EmitToArray(testData:=testDataB0) Dim mdB0 = ModuleMetadata.CreateFromImage(bytesB0) Dim generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider()) Dim f0 = compilationB0.GetMember(Of MethodSymbol)("B.F") Dim f1 = compilationB1.GetMember(Of MethodSymbol)("B.F") Dim f2 = compilationB2.GetMember(Of MethodSymbol)("B.F") Dim diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables:=True))) diffB1.VerifyIL("B.F", " { // Code size 15 (0xf) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: callvirt ""Sub A.M()"" IL_000d: nop IL_000e: ret } ") Dim diffB2 = compilationB2.EmitDifference( diffB1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables:=True))) diffB2.VerifyIL("B.F", " { // Code size 8 (0x8) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: stloc.0 IL_0007: ret } ") End Sub <Fact> Public Sub ForStatement() Dim source0 = MarkedSource(" Imports System Class C Sub F() <N:0><N:1>For a = G(0) To G(1) Step G(2)</N:1> Console.WriteLine(1) Next</N:0> End Sub Function G(a As Integer) As Integer Return 10 End Function End Class ") Dim source1 = MarkedSource(" Imports System Class C Sub F() <N:0><N:1>For a = G(0) To G(1) Step G(2)</N:1> Console.WriteLine(2) Next</N:0> End Sub Function G(a As Integer) As Integer Return 10 End Function End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, {MsvbRef}, ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) Dim md1 = diff1.GetMetadata() Dim reader1 = md1.Reader v0.VerifyIL("C.F", " { // Code size 55 (0x37) .maxstack 3 .locals init (Integer V_0, Integer V_1, Integer V_2, Integer V_3) //a IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: call ""Function C.G(Integer) As Integer"" IL_0008: stloc.0 IL_0009: ldarg.0 IL_000a: ldc.i4.1 IL_000b: call ""Function C.G(Integer) As Integer"" IL_0010: stloc.1 IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: call ""Function C.G(Integer) As Integer"" IL_0018: stloc.2 IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0028 IL_001d: ldc.i4.1 IL_001e: call ""Sub System.Console.WriteLine(Integer)"" IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.2 IL_0026: add.ovf IL_0027: stloc.3 IL_0028: ldloc.2 IL_0029: ldc.i4.s 31 IL_002b: shr IL_002c: ldloc.3 IL_002d: xor IL_002e: ldloc.2 IL_002f: ldc.i4.s 31 IL_0031: shr IL_0032: ldloc.1 IL_0033: xor IL_0034: ble.s IL_001d IL_0036: ret } ") ' Note that all variables are mapped to their previous slots diff1.VerifyIL("C.F", " { // Code size 55 (0x37) .maxstack 3 .locals init (Integer V_0, Integer V_1, Integer V_2, Integer V_3) //a IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: call ""Function C.G(Integer) As Integer"" IL_0008: stloc.0 IL_0009: ldarg.0 IL_000a: ldc.i4.1 IL_000b: call ""Function C.G(Integer) As Integer"" IL_0010: stloc.1 IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: call ""Function C.G(Integer) As Integer"" IL_0018: stloc.2 IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0028 IL_001d: ldc.i4.2 IL_001e: call ""Sub System.Console.WriteLine(Integer)"" IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.2 IL_0026: add.ovf IL_0027: stloc.3 IL_0028: ldloc.2 IL_0029: ldc.i4.s 31 IL_002b: shr IL_002c: ldloc.3 IL_002d: xor IL_002e: ldloc.2 IL_002f: ldc.i4.s 31 IL_0031: shr IL_0032: ldloc.1 IL_0033: xor IL_0034: ble.s IL_001d IL_0036: ret } ") End Sub <Fact> Public Sub ForStatement_LateBound() Dim source0 = MarkedSource(" Option Strict On Public Class C Public Shared Sub F() Dim <N:0>a</N:0> As Object = 0 Dim <N:1>b</N:1> As Object = 0 Dim <N:2>c</N:2> As Object = 0 Dim <N:3>d</N:3> As Object = 0 <N:4>For a = b To c Step d System.Console.Write(a) Next</N:4> End Sub End Class") Dim source1 = MarkedSource(" Option Strict On Public Class C Public Shared Sub F() Dim <N:0>a</N:0> As Object = 0 Dim <N:1>b</N:1> As Object = 0 Dim <N:2>c</N:2> As Object = 0 Dim <N:3>d</N:3> As Object = 0 <N:4>For a = b To c Step d System.Console.WriteLine(a) Next</N:4> End Sub End Class") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, {MsvbRef}, ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) Dim md1 = diff1.GetMetadata() Dim reader1 = md1.Reader v0.VerifyIL("C.F", " { // Code size 77 (0x4d) .maxstack 6 .locals init (Object V_0, //a Object V_1, //b Object V_2, //c Object V_3, //d Object V_4, Boolean V_5, Boolean V_6) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""Integer"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: box ""Integer"" IL_000e: stloc.1 IL_000f: ldc.i4.0 IL_0010: box ""Integer"" IL_0015: stloc.2 IL_0016: ldc.i4.0 IL_0017: box ""Integer"" IL_001c: stloc.3 IL_001d: ldloc.0 IL_001e: ldloc.1 IL_001f: ldloc.2 IL_0020: ldloc.3 IL_0021: ldloca.s V_4 IL_0023: ldloca.s V_0 IL_0025: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Object, Object, Object, Object, ByRef Object, ByRef Object) As Boolean"" IL_002a: stloc.s V_5 IL_002c: ldloc.s V_5 IL_002e: brfalse.s IL_004c IL_0030: ldloc.0 IL_0031: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_0036: call ""Sub System.Console.Write(Object)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldloc.s V_4 IL_003f: ldloca.s V_0 IL_0041: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Object, Object, ByRef Object) As Boolean"" IL_0046: stloc.s V_6 IL_0048: ldloc.s V_6 IL_004a: brtrue.s IL_0030 IL_004c: ret } ") ' Note that all variables are mapped to their previous slots diff1.VerifyIL("C.F", " { // Code size 77 (0x4d) .maxstack 6 .locals init (Object V_0, //a Object V_1, //b Object V_2, //c Object V_3, //d Object V_4, Boolean V_5, Boolean V_6) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""Integer"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: box ""Integer"" IL_000e: stloc.1 IL_000f: ldc.i4.0 IL_0010: box ""Integer"" IL_0015: stloc.2 IL_0016: ldc.i4.0 IL_0017: box ""Integer"" IL_001c: stloc.3 IL_001d: ldloc.0 IL_001e: ldloc.1 IL_001f: ldloc.2 IL_0020: ldloc.3 IL_0021: ldloca.s V_4 IL_0023: ldloca.s V_0 IL_0025: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Object, Object, Object, Object, ByRef Object, ByRef Object) As Boolean"" IL_002a: stloc.s V_5 IL_002c: ldloc.s V_5 IL_002e: brfalse.s IL_004c IL_0030: ldloc.0 IL_0031: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_0036: call ""Sub System.Console.WriteLine(Object)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldloc.s V_4 IL_003f: ldloca.s V_0 IL_0041: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Object, Object, ByRef Object) As Boolean"" IL_0046: stloc.s V_6 IL_0048: ldloc.s V_6 IL_004a: brtrue.s IL_0030 IL_004c: ret } ") End Sub <Fact> Public Sub AddImports_AmbiguousCode() Dim source0 = MarkedSource(" Imports System.Threading Class C Shared Sub E() Dim t = New Timer(Sub(s) System.Console.WriteLine(s)) End Sub End Class ") Dim source1 = MarkedSource(" Imports System.Threading Imports System.Timers Class C Shared Sub E() Dim t = New Timer(Sub(s) System.Console.WriteLine(s)) End Sub Shared Sub G() System.Console.WriteLine(new TimersDescriptionAttribute("""")) End Sub End Class ") Dim compilation0 = CreateCompilation(source0.Tree, targetFramework:=TargetFramework.NetStandard20, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim e0 = compilation0.GetMember(Of MethodSymbol)("C.E") Dim e1 = compilation1.GetMember(Of MethodSymbol)("C.E") Dim g1 = compilation1.GetMember(Of MethodSymbol)("C.G") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) ' Pretend there was an update to C.E to ensure we haven't invalidated the test Dim diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diffError.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_AmbiguousInImports2, "Timer").WithArguments("Timer", "System.Threading, System.Timers").WithLocation(7, 21)) Dim diff = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, g1))) diff.EmitResult.Diagnostics.Verify() diff.VerifyIL("C.G", " { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldstr """" IL_0006: newobj ""Sub System.Timers.TimersDescriptionAttribute..ctor(String)"" IL_000b: call ""Sub System.Console.WriteLine(Object)"" IL_0010: nop IL_0011: ret }") 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.Collections.Immutable Imports System.IO Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.MetadataUtilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class EditAndContinueTests Inherits EditAndContinueTestBase <Fact> Public Sub SemanticErrors_MethodBody() Dim source0 = MarkedSource(" Class C Shared Sub E() Dim x As Integer = 1 System.Console.WriteLine(x) End Sub Shared Sub G() System.Console.WriteLine(1) End Sub End Class ") Dim source1 = MarkedSource(" Class C Shared Sub E() Dim x = Unknown(2) System.Console.WriteLine(x) End Sub Shared Sub G() System.Console.WriteLine(2) End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim e0 = compilation0.GetMember(Of MethodSymbol)("C.E") Dim e1 = compilation1.GetMember(Of MethodSymbol)("C.E") Dim g0 = compilation0.GetMember(Of MethodSymbol)("C.G") Dim g1 = compilation1.GetMember(Of MethodSymbol)("C.G") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) ' Semantic errors are reported only for the bodies of members being emitted. Dim diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diffError.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_NameNotDeclared1, "Unknown").WithArguments("Unknown").WithLocation(4, 17)) Dim diffGood = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diffGood.EmitResult.Diagnostics.Verify() diffGood.VerifyIL("C.G", " { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.2 IL_0002: call ""Sub System.Console.WriteLine(Integer)"" IL_0007: nop IL_0008: ret }") End Sub <Fact> Public Sub SemanticErrors_Declaration() Dim source0 = MarkedSource(" Class C Sub G() System.Console.WriteLine(1) End Sub End Class ") Dim source1 = MarkedSource(" Class C Sub G() System.Console.WriteLine(1) End Sub End Class Class Bad Inherits Bad End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim g0 = compilation0.GetMember(Of MethodSymbol)("C.G") Dim g1 = compilation1.GetMember(Of MethodSymbol)("C.G") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_TypeInItsInheritsClause1, "Bad").WithArguments("Bad").WithLocation(9, 12)) End Sub <Fact> Public Sub ModifyMethod_WithTuples() Dim source0 = " Class C Shared Sub Main End Sub Shared Function F() As (Integer, Integer) Return (1, 2) End Function End Class " Dim source1 = " Class C Shared Sub Main End Sub Shared Function F() As (Integer, Integer) Return (2, 3) End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugExe, references:={ValueTupleRef, SystemRuntimeFacadeRef}) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) ' Verify delta metadata contains expected rows. Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} EncValidation.VerifyModuleMvid(1, reader0, reader1) CheckNames(readers, reader1.GetTypeDefNames()) CheckNames(readers, reader1.GetMethodDefNames(), "F") CheckNames(readers, reader1.GetMemberRefNames(), ".ctor") ' System.ValueTuple ctor CheckEncLog(reader1, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) ' C.F CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.TypeSpec), Handle(3, TableIndex.AssemblyRef), Handle(4, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact> Public Sub ModifyMethod_RenameParameter() Dim source0 = " Class C Shared Function F(i As Integer) As Integer Return i End Function End Class " Dim source1 = " Class C Shared Function F(x As Integer) As Integer Return x End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll, references:={ValueTupleRef, SystemRuntimeFacadeRef}) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) CheckNames(reader0, reader0.GetParameterDefNames(), "i") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) ' Verify delta metadata contains expected rows. Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} EncValidation.VerifyModuleMvid(1, reader0, reader1) CheckNames(readers, reader1.GetTypeDefNames()) CheckNames(readers, reader1.GetMethodDefNames(), "F") CheckNames(readers, reader1.GetParameterDefNames(), "x") CheckEncLogDefinitions(reader1, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)) CheckEncMapDefinitions(reader1, Handle(2, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.StandAloneSig)) End Using End Using End Sub <WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")> <Fact> Public Sub PartialMethod() Dim source = <compilation> <file name="a.vb"> Partial Class C Private Shared Partial Sub M1() End Sub Private Shared Partial Sub M2() End Sub Private Shared Partial Sub M3() End Sub Private Shared Sub M1() End Sub Private Shared Sub M2() End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "M1", "M2") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M2").PartialImplementationPart Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M2").PartialImplementationPart Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) Dim methods = diff1.TestData.GetMethodsByName() Assert.Equal(methods.Count, 1) Assert.True(methods.ContainsKey("C.M2()")) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetMethodDefNames(), "M2") CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact> Public Sub AddThenModifyExplicitImplementation() Dim source0 = <compilation> <file name="a.vb"> Interface I(Of T) Sub M() End Interface </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Interface I(Of T) Sub M() End Interface Class A Implements I(Of Integer), I(Of Object) Public Sub New() End Sub Sub M() Implements I(Of Integer).M, I(Of Object).M End Sub End Class </file> </compilation> Dim source2 = source1 Dim source3 = <compilation> <file name="a.vb"> Interface I(Of T) Sub M() End Interface Class A Implements I(Of Integer), I(Of Object) Public Sub New() End Sub Sub M() Implements I(Of Integer).M, I(Of Object).M End Sub End Class Class B Implements I(Of Object) Public Sub New() End Sub Sub M() Implements I(Of Object).M End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim compilation2 = compilation1.WithSource(source2) Dim compilation3 = compilation2.WithSource(source3) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim type1 = compilation1.GetMember(Of NamedTypeSymbol)("A") Dim method1 = compilation1.GetMember(Of MethodSymbol)("A.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, type1))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetMethodDefNames(), ".ctor", "M") CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(4, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(2, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(5, TableIndex.TypeRef), Handle(3, TableIndex.TypeDef), Handle(2, TableIndex.MethodDef), Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.InterfaceImpl), Handle(2, TableIndex.InterfaceImpl), Handle(4, TableIndex.MemberRef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(1, TableIndex.MethodImpl), Handle(2, TableIndex.MethodImpl), Handle(1, TableIndex.TypeSpec), Handle(2, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)) Dim generation1 = diff1.NextGeneration Dim method2 = compilation2.GetMember(Of MethodSymbol)("A.M") Dim diff2 = compilation2.EmitDifference( generation1, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2))) Using md2 = diff2.GetMetadata() Dim reader2 = md2.Reader readers = {reader0, reader1, reader2} CheckNames(readers, reader2.GetMethodDefNames(), "M") CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader2, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(3, TableIndex.TypeSpec), Handle(4, TableIndex.TypeSpec), Handle(3, TableIndex.AssemblyRef)) Dim generation2 = diff2.NextGeneration Dim type3 = compilation3.GetMember(Of NamedTypeSymbol)("B") Dim diff3 = compilation3.EmitDifference( generation1, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, type3))) Using md3 = diff3.GetMetadata() Dim reader3 = md3.Reader readers = {reader0, reader1, reader3} CheckNames(readers, reader3.GetMethodDefNames(), ".ctor", "M") CheckEncLog(reader3, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(3, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)) CheckEncMap(reader3, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(3, TableIndex.InterfaceImpl), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(3, TableIndex.MethodImpl), Handle(3, TableIndex.TypeSpec), Handle(3, TableIndex.AssemblyRef)) End Using End Using End Using End Using End Sub <Fact, WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")> Public Sub ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation() Dim source = <compilation> <file name="a.vb"> Interface I Sub M1() Sub M2() End Interface Class C Implements I Public Sub New() End Sub Sub M() Implements I.M1, I.M2 End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of NamedTypeSymbol)("C").InstanceConstructors.Single() Dim method1 = compilation1.GetMember(Of NamedTypeSymbol)("C").InstanceConstructors.Single() Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetTypeDefNames()) CheckNames(readers, reader1.GetMethodDefNames(), ".ctor") CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact> Public Sub NamespacesAndOverloads() Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(options:=TestOptions.DebugDll, source:= <compilation> <file name="a.vb"><![CDATA[ Class C End Class Namespace N Class C End Class End Namespace Namespace M Class C Sub M1(o As N.C) End Sub Sub M1(o As M.C) End Sub Sub M2(a As N.C, b As M.C, c As Global.C) M1(a) End Sub End Class End Namespace ]]></file> </compilation>) Dim bytes = compilation0.EmitToArray() Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes), EmptyLocalsProvider) Dim compilation1 = compilation0.WithSource( <compilation> <file name="a.vb"><![CDATA[ Class C End Class Namespace N Class C End Class End Namespace Namespace M Class C Sub M1(o As N.C) End Sub Sub M1(o As M.C) End Sub Sub M1(o As Global.C) End Sub Sub M2(a As N.C, b As M.C, c As Global.C) M1(a) M1(b) End Sub End Class End Namespace ]]></file> </compilation>) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, compilation1.GetMembers("M.C.M1")(2)), New SemanticEdit(SemanticEditKind.Update, compilation0.GetMembers("M.C.M2")(0), compilation1.GetMembers("M.C.M2")(0)))) diff1.VerifyIL(" { // Code size 18 (0x12) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000004 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000005 IL_0010: nop IL_0011: ret } { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } ") Dim compilation2 = compilation1.WithSource( <compilation> <file name="a.vb"><![CDATA[ Class C End Class Namespace N Class C End Class End Namespace Namespace M Class C Sub M1(o As N.C) End Sub Sub M1(o As M.C) End Sub Sub M1(o As Global.C) End Sub Sub M2(a As N.C, b As M.C, c As Global.C) M1(a) M1(b) M1(c) End Sub End Class End Namespace ]]></file> </compilation>) Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, compilation1.GetMembers("M.C.M2")(0), compilation2.GetMembers("M.C.M2")(0)))) diff2.VerifyIL(" { // Code size 26 (0x1a) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000004 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000005 IL_0010: nop IL_0011: ldarg.0 IL_0012: ldarg.3 IL_0013: call 0x06000007 IL_0018: nop IL_0019: ret } ") End Sub <WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")> <Fact()> Public Sub PrivateImplementationDetails_ArrayInitializer_FromMetadata() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim a As Integer() = {1, 2, 3} System.Console.Write(a(0)) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim a As Integer() = {1, 2, 3} System.Console.Write(a(1)) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(sources0, TestOptions.DebugDll.WithModuleName("MODULE")) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.M") methodData0.VerifyIL(" { // Code size 29 (0x1d) .maxstack 3 .locals init (Integer() V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""Integer"" IL_0007: dup IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000d: call ""Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: ldelem.i4 IL_0016: call ""Sub System.Console.Write(Integer)"" IL_001b: nop IL_001c: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider) Dim testData1 = New CompilationTestData() Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 30 (0x1e) .maxstack 4 .locals init (Integer() V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""Integer"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: ldelem.i4 IL_0017: call ""Sub System.Console.Write(Integer)"" IL_001c: nop IL_001d: ret } ") End Sub ''' <summary> ''' Should not generate method for string switch since ''' the CLR only allows adding private members. ''' </summary> <WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")> <Fact()> Public Sub PrivateImplementationDetails_ComputeStringHash() Dim sources = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F(s As String) Select Case s Case "1" Return 1 Case "2" Return 2 Case "3" Return 3 Case "4" Return 4 Case "5" Return 5 Case "6" Return 6 Case "7" Return 7 Case Else Return 0 End Select End Function End Class ]]></file> </compilation> Const ComputeStringHashName As String = "ComputeStringHash" Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(sources, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.F") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider) ' Should have generated call to ComputeStringHash and ' added the method to <PrivateImplementationDetails>. Dim actualIL0 = methodData0.GetMethodIL() Assert.True(actualIL0.Contains(ComputeStringHashName)) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "F", ComputeStringHashName) Dim testData1 = New CompilationTestData() Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) ' Should not have generated call to ComputeStringHash nor ' added the method to <PrivateImplementationDetails>. Dim actualIL1 = diff1.GetMethodIL("C.F") Assert.False(actualIL1.Contains(ComputeStringHashName)) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetMethodDefNames(), "F") End Using End Using End Sub ''' <summary> ''' Avoid adding references from method bodies ''' other than the changed methods. ''' </summary> <Fact> Public Sub ReferencesInIL() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Module M Sub F() System.Console.WriteLine(1) End Sub Sub G() System.Console.WriteLine(2) End Sub End Module ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Module M Sub F() System.Console.WriteLine(1) End Sub Sub G() System.Console.Write(2) End Sub End Module ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(sources0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) ' Verify full metadata contains expected rows. Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "M") CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G") CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", ".ctor", "WriteLine") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, compilation1.GetMember("M.G")))) ' "Write" should be included in string table, but "WriteLine" should not. Assert.True(diff1.MetadataDelta.IsIncluded("Write")) Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine")) End Using End Sub <Fact> Public Sub ExceptionFilters() Dim source0 = MarkedSource(" Imports System Imports System.IO Class C Shared Function filter(e As Exception) Return True End Function Shared Sub F() Try Throw New InvalidOperationException() <N:0>Catch e As IOException <N:1>When filter(e)</N:1></N:0> Console.WriteLine() <N:2>Catch e As Exception <N:3>When filter(e)</N:3></N:2> Console.WriteLine() End Try End Sub End Class ") Dim source1 = MarkedSource(" Imports System Imports System.IO Class C Shared Function filter(e As Exception) Return True End Function Shared Sub F() Try Throw New InvalidOperationException() <N:0>Catch e As IOException <N:1>When filter(e)</N:1></N:0> Console.WriteLine() <N:2>Catch e As Exception <N:3>When filter(e)</N:3></N:2> Console.WriteLine() End Try Console.WriteLine() End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib45AndVBRuntime({source0.Tree}, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 118 (0x76) .maxstack 2 .locals init (System.IO.IOException V_0, //e Boolean V_1, System.Exception V_2, //e Boolean V_3) IL_0000: nop .try { IL_0001: nop IL_0002: newobj ""Sub System.InvalidOperationException..ctor()"" IL_0007: throw } filter { IL_0008: isinst ""System.IO.IOException"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_002b IL_0014: dup IL_0015: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_001a: stloc.0 IL_001b: ldloc.0 IL_001c: call ""Function C.filter(System.Exception) As Object"" IL_0021: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"" IL_0026: stloc.1 IL_0027: ldloc.1 IL_0028: ldc.i4.0 IL_0029: cgt.un IL_002b: endfilter } // end filter { // handler IL_002d: pop IL_002e: call ""Sub System.Console.WriteLine()"" IL_0033: nop IL_0034: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_0039: leave.s IL_006e } filter { IL_003b: isinst ""System.Exception"" IL_0040: dup IL_0041: brtrue.s IL_0047 IL_0043: pop IL_0044: ldc.i4.0 IL_0045: br.s IL_005e IL_0047: dup IL_0048: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_004d: stloc.2 IL_004e: ldloc.2 IL_004f: call ""Function C.filter(System.Exception) As Object"" IL_0054: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"" IL_0059: stloc.3 IL_005a: ldloc.3 IL_005b: ldc.i4.0 IL_005c: cgt.un IL_005e: endfilter } // end filter { // handler IL_0060: pop IL_0061: call ""Sub System.Console.WriteLine()"" IL_0066: nop IL_0067: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_006c: leave.s IL_006e } IL_006e: nop IL_006f: call ""Sub System.Console.WriteLine()"" IL_0074: nop IL_0075: ret } ") End Sub <Fact> Public Sub SymbolMatcher_TypeArguments() Dim source = <compilation> <file name="c.vb"><![CDATA[ Class A(Of T) Class B(Of U) Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of Object).S) As A(Of V) Return Nothing End Function Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of V).S) As A(Of V) Return Nothing End Function End Class Structure S End Structure End Class ]]> </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim matcher = CreateMatcher(compilation1, compilation0) Dim members = compilation1.GetMember(Of NamedTypeSymbol)("A.B").GetMembers("M") Assert.Equal(members.Length, 2) For Each member In members Dim other = DirectCast(matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IMethodDefinition)).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) Next End Sub <Fact> Public Sub SymbolMatcher_Constraints() Dim source = <compilation> <file name="c.vb"><![CDATA[ Interface I(Of T As I(Of T)) End Interface Class C Shared Sub M(Of T As I(Of T))(o As I(Of T)) End Sub End Class ]]> </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim matcher = CreateMatcher(compilation1, compilation0) Dim member = compilation1.GetMember(Of MethodSymbol)("C.M") Dim other = DirectCast(matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IMethodDefinition)).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) End Sub <Fact> Public Sub SymbolMatcher_CustomModifiers() Dim ilSource = <![CDATA[ .class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F() { } } ]]>.Value Dim source = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits A Public Overrides Function F() As Object() Return Nothing End Function End Class ]]> </file> </compilation> Dim metadata = CompileIL(ilSource) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, {metadata}, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim member1 = compilation1.GetMember(Of MethodSymbol)("B.F") Const nModifiers As Integer = 1 Assert.Equal(nModifiers, DirectCast(member1.ReturnType, ArrayTypeSymbol).CustomModifiers.Length) Dim matcher = CreateMatcher(compilation1, compilation0) Dim other = DirectCast(matcher.MapDefinition(DirectCast(member1.GetCciAdapter(), Cci.IMethodDefinition)).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) Assert.Equal(nModifiers, DirectCast(other.ReturnType, ArrayTypeSymbol).CustomModifiers.Length) End Sub <WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")> <Fact()> Public Sub MethodSignatureWithNoPIAType() Dim sourcesPIA = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib("_.dll")> <Assembly: Guid("35DB1A6B-D635-4320-A062-28D42920F2A3")> <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2A4")> Public Interface I End Interface ]]></file> </compilation> Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M(x As I) Dim y As I = Nothing M(Nothing) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M(x As I) Dim y As I = Nothing M(x) End Sub End Class ]]></file> </compilation> Dim compilationPIA = CreateCompilationWithMscorlib40AndVBRuntime(sourcesPIA) compilationPIA.AssertTheseDiagnostics() Dim referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes:=True) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, options:=TestOptions.DebugDll, references:={referencePIA}) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.M") Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.VerifyIL("C.M", <![CDATA[ { // Code size 11 (0xb) .maxstack 1 .locals init ([unchanged] V_0, I V_1) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: ldarg.0 IL_0004: call "Sub C.M(I)" IL_0009: nop IL_000a: ret } ]]>.Value) End Using End Sub ''' <summary> ''' Disallow edits that require NoPIA references. ''' </summary> <Fact()> Public Sub NoPIAReferences() Dim sourcesPIA = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib("_.dll")> <Assembly: Guid("35DB1A6B-D635-4320-A062-28D42920F2B3")> <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2B4")> Public Interface IA Sub M() ReadOnly Property P As Integer Event E As Action End Interface <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2B5")> Public Interface IB End Interface <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2B6")> Public Interface IC End Interface Public Structure S Public F As Object End Structure ]]></file> </compilation> Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C(Of T) Shared Private F As Object = GetType(IC) Shared Sub M1() Dim o As IA = Nothing o.M() M2(o.P) AddHandler o.E, AddressOf M1 M2(C(Of IA).F) M2(New S()) End Sub Shared Sub M2(o As Object) End Sub End Class ]]></file> </compilation> Dim sources1A = sources0 Dim sources1B = <compilation> <file name="a.vb"><![CDATA[ Class C(Of T) Shared Private F As Object = GetType(IC) Shared Sub M1() M2(Nothing) End Sub Shared Sub M2(o As Object) End Sub End Class ]]></file> </compilation> Dim compilationPIA = CreateCompilationWithMscorlib40AndVBRuntime(sourcesPIA) compilationPIA.AssertTheseDiagnostics() Dim referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes:=True) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, options:=TestOptions.DebugDll, references:={referencePIA}) Dim compilation1A = compilation0.WithSource(sources1A) Dim compilation1B = compilation0.WithSource(sources1B) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C(Of T).M1") Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M1") ' Disallow edits that require NoPIA references. Dim method1A = compilation1A.GetMember(Of MethodSymbol)("C.M1") Dim diff1A = compilation1A.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables:=True))) diff1A.EmitResult.Diagnostics.AssertTheseDiagnostics(<errors><![CDATA[ BC37230: Cannot continue since the edit includes a reference to an embedded type: 'IA'. BC37230: Cannot continue since the edit includes a reference to an embedded type: 'S'. ]]></errors>) ' Allow edits that do not require NoPIA references, Dim method1B = compilation1B.GetMember(Of MethodSymbol)("C.M1") Dim diff1B = compilation1B.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables:=True))) diff1B.VerifyIL("C(Of T).M1", <![CDATA[ { // Code size 9 (0x9) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1) IL_0000: nop IL_0001: ldnull IL_0002: call "Sub C(Of T).M2(Object)" IL_0007: nop IL_0008: ret } ]]>.Value) Using md1 = diff1B.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames()) End Using End Using End Sub <WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")> <Fact()> Public Sub NoPIATypeInNamespace() Dim sourcesPIA = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib("_.dll")> <Assembly: Guid("35DB1A6B-D635-4320-A062-28D42920F2A5")> Namespace N <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2A6")> Public Interface IA End Interface End Namespace <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2A6")> Public Interface IB End Interface ]]></file> </compilation> Dim sources = <compilation> <file name="a.vb"><![CDATA[ Class C(Of T) Shared Sub M(o As Object) M(C(Of N.IA).E.X) M(C(Of IB).E.X) End Sub Enum E X End Enum End Class ]]></file> </compilation> Dim compilationPIA = CreateCompilationWithMscorlib40AndVBRuntime(sourcesPIA) compilationPIA.AssertTheseDiagnostics() Dim referencePIA = AssemblyMetadata.CreateFromImage(compilationPIA.EmitToArray()).GetReference(embedInteropTypes:=True) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources, options:=TestOptions.DebugDll, references:={referencePIA}) Dim compilation1 = compilation0.WithSource(sources) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.EmitResult.Diagnostics.AssertTheseDiagnostics(<errors><![CDATA[ BC37230: Cannot continue since the edit includes a reference to an embedded type: 'IA'. BC37230: Cannot continue since the edit includes a reference to an embedded type: 'IB'. ]]></errors>) diff1.VerifyIL("C(Of T).M", <![CDATA[ { // Code size 26 (0x1a) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box "C(Of N.IA).E" IL_0007: call "Sub C(Of T).M(Object)" IL_000c: nop IL_000d: ldc.i4.0 IL_000e: box "C(Of IB).E" IL_0013: call "Sub C(Of T).M(Object)" IL_0018: nop IL_0019: ret } ]]>.Value) End Using End Sub <Fact, WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")> Public Sub EventFields() Dim source0 = MarkedSource(" Imports System Class C Shared Event handler As EventHandler Shared Function F() As Integer RaiseEvent handler(Nothing, Nothing) Return 1 End Function End Class ") Dim source1 = MarkedSource(" Imports System Class C Shared Event handler As EventHandler Shared Function F() As Integer RaiseEvent handler(Nothing, Nothing) Return 10 End Function End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) compilation0.AssertNoDiagnostics() Dim compilation1 = compilation0.WithSource(source1.Tree) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 26 (0x1a) .maxstack 3 .locals init (Integer V_0, //F [unchanged] V_1, System.EventHandler V_2) IL_0000: nop IL_0001: ldsfld ""C.handlerEvent As System.EventHandler"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: brfalse.s IL_0013 IL_000a: ldloc.2 IL_000b: ldnull IL_000c: ldnull IL_000d: callvirt ""Sub System.EventHandler.Invoke(Object, System.EventArgs)"" IL_0012: nop IL_0013: ldc.i4.s 10 IL_0015: stloc.0 IL_0016: br.s IL_0018 IL_0018: ldloc.0 IL_0019: ret } ") End Sub ''' <summary> ''' Should use TypeDef rather than TypeRef for unrecognized ''' local of a type defined in the original assembly. ''' </summary> <WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")> <Fact()> Public Sub UnrecognizedLocalOfTypeFromAssembly() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class E Inherits System.Exception End Class Class C Shared Sub M() Try Catch e As E End Try End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetAssemblyRefNames(), "mscorlib", "Microsoft.VisualBasic") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") ' Use empty LocalVariableNameProvider for original locals and ' use preserveLocalVariables: true for the edit so that existing ' locals are retained even though all are unrecognized. Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, syntaxMap:=Function(s) Nothing, preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetAssemblyRefNames(), "mscorlib", "Microsoft.VisualBasic") CheckNames(readers, reader1.GetTypeRefNames(), "Object", "ProjectData", "Exception") CheckEncLog(reader1, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef), Handle(4, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact, WorkItem(837315, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837315")> Public Sub AddingSetAccessor() Dim source0 = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine("hello") End Sub Friend name As String Readonly Property GetName Get Return name End Get End Property End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine("hello") End Sub Friend name As String Property GetName Get Return name End Get Private Set(value) End Set End Property End Module</file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim prop0 = compilation0.GetMember(Of PropertySymbol)("Module1.GetName") Dim prop1 = compilation1.GetMember(Of PropertySymbol)("Module1.GetName") Dim method1 = prop1.SetMethod Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, method1, preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetMethodDefNames(), "set_GetName") End Using diff1.VerifyIL("Module1.set_GetName", " { // Code size 2 (0x2) .maxstack 0 IL_0000: nop IL_0001: ret } ") End Using End Sub <Fact> Public Sub PropertyGetterReturnValueVariable() Dim source0 = <compilation> <file name="a.vb"> Module Module1 ReadOnly Property P Get P = 1 End Get End Property End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module Module1 ReadOnly Property P Get P = 2 End Get End Property End Module</file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim getter0 = compilation0.GetMember(Of PropertySymbol)("Module1.P").GetMethod Dim getter1 = compilation1.GetMember(Of PropertySymbol)("Module1.P").GetMethod Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("Module1.get_P").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, getter0, getter1, preserveLocalVariables:=True))) diff1.VerifyIL("Module1.get_P", " { // Code size 10 (0xa) .maxstack 1 .locals init (Object V_0) //P IL_0000: nop IL_0001: ldc.i4.2 IL_0002: box ""Integer"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ret }") End Using End Sub #Region "Local Slots" <Fact, WorkItem(828389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/828389")> Public Sub CatchClause() Dim source0 = <compilation> <file name="a.vb"> Class C Shared Sub M() Try System.Console.WriteLine(1) Catch ex As System.Exception End Try End Sub End Class </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Class C Shared Sub M() Try System.Console.WriteLine(2) Catch ex As System.Exception End Try End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 28 (0x1c) .maxstack 2 .locals init (System.Exception V_0) //ex IL_0000: nop .try { IL_0001: nop IL_0002: ldc.i4.2 IL_0003: call ""Sub System.Console.WriteLine(Integer)"" IL_0008: nop IL_0009: leave.s IL_001a } catch System.Exception { IL_000b: dup IL_000c: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_0011: stloc.0 IL_0012: nop IL_0013: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_0018: leave.s IL_001a } IL_001a: nop IL_001b: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PreserveLocalSlots() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim x As Object = F() Dim y As A(Of B) = F() Dim z As Object = F() M(x) M(y) M(z) End Sub Shared Sub N() Dim a As Object = F() Dim b As Object = F() M(a) M(b) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim z As B = F() Dim y As A(Of B) = F() Dim w As Object = F() M(w) M(y) End Sub Shared Sub N() Dim a As Object = F() Dim b As Object = F() M(a) M(b) End Sub End Class ]]></file> </compilation> Dim sources2 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim x As Object = F() Dim z As B = F() M(x) M(z) End Sub Shared Sub N() Dim a As Object = F() Dim b As Object = F() M(a) M(b) End Sub End Class ]]></file> </compilation> Dim sources3 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim x As Object = F() Dim z As B = F() M(x) M(z) End Sub Shared Sub N() Dim c As Object = F() Dim b As Object = F() M(c) M(b) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim compilation3 = compilation2.WithSource(sources3) ' Verify full metadata contains expected rows. Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("B.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("B.M") Dim methodN = compilation0.GetMember(Of MethodSymbol)("B.N") Dim generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), Function(m) Select Case MetadataTokens.GetRowNumber(m) Case 4 Return testData0.GetMethodData("B.M").GetEncDebugInfo() Case 5 Return testData0.GetMethodData("B.N").GetEncDebugInfo() Case Else Return Nothing End Select End Function) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.VerifyIL(" { // Code size 41 (0x29) .maxstack 1 IL_0000: nop IL_0001: call 0x06000003 IL_0006: stloc.3 IL_0007: call 0x06000003 IL_000c: stloc.1 IL_000d: call 0x06000003 IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: call 0x0A000007 IL_001b: call 0x06000004 IL_0020: nop IL_0021: ldloc.1 IL_0022: call 0x06000004 IL_0027: nop IL_0028: ret } ") diff1.VerifyPdb({&H06000001UI, &H06000002UI, &H06000003UI, &H06000004UI, &H06000005UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000004"> <sequencePoints> <entry offset="0x0" startLine="8" startColumn="5" endLine="8" endColumn="30" document="1"/> <entry offset="0x1" startLine="9" startColumn="13" endLine="9" endColumn="25" document="1"/> <entry offset="0x7" startLine="10" startColumn="13" endLine="10" endColumn="31" document="1"/> <entry offset="0xd" startLine="11" startColumn="13" endLine="11" endColumn="30" document="1"/> <entry offset="0x14" startLine="12" startColumn="9" endLine="12" endColumn="13" document="1"/> <entry offset="0x21" startLine="13" startColumn="9" endLine="13" endColumn="13" document="1"/> <entry offset="0x28" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x29"> <currentnamespace name=""/> <local name="z" il_index="3" il_start="0x0" il_end="0x29" attributes="0"/> <local name="y" il_index="1" il_start="0x0" il_end="0x29" attributes="0"/> <local name="w" il_index="4" il_start="0x0" il_end="0x29" attributes="0"/> </scope> </method> </methods> </symbols>) Dim method2 = compilation2.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B").GetMember(Of MethodSymbol)("M") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables:=True))) diff2.VerifyIL(" { // Code size 35 (0x23) .maxstack 1 IL_0000: nop IL_0001: call 0x06000003 IL_0006: stloc.s V_5 IL_0008: call 0x06000003 IL_000d: stloc.3 IL_000e: ldloc.s V_5 IL_0010: call 0x0A000008 IL_0015: call 0x06000004 IL_001a: nop IL_001b: ldloc.3 IL_001c: call 0x06000004 IL_0021: nop IL_0022: ret } ") diff2.VerifyPdb({&H06000001UI, &H06000002UI, &H06000003UI, &H06000004UI, &H06000005UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000004"> <sequencePoints> <entry offset="0x0" startLine="8" startColumn="5" endLine="8" endColumn="30" document="1"/> <entry offset="0x1" startLine="9" startColumn="13" endLine="9" endColumn="30" document="1"/> <entry offset="0x8" startLine="10" startColumn="13" endLine="10" endColumn="25" document="1"/> <entry offset="0xe" startLine="11" startColumn="9" endLine="11" endColumn="13" document="1"/> <entry offset="0x1b" startLine="12" startColumn="9" endLine="12" endColumn="13" document="1"/> <entry offset="0x22" startLine="13" startColumn="5" endLine="13" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x23"> <currentnamespace name=""/> <local name="x" il_index="5" il_start="0x0" il_end="0x23" attributes="0"/> <local name="z" il_index="3" il_start="0x0" il_end="0x23" attributes="0"/> </scope> </method> </methods> </symbols>) ' Modify different method. (Previous generations ' have not referenced method.) method2 = compilation2.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B").GetMember(Of MethodSymbol)("N") Dim method3 = compilation3.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B").GetMember(Of MethodSymbol)("N") Dim metadata3 As ImmutableArray(Of Byte) = Nothing Dim il3 As ImmutableArray(Of Byte) = Nothing Dim pdb3 As Stream = Nothing Dim diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables:=True))) diff3.VerifyIL(" { // Code size 38 (0x26) .maxstack 1 IL_0000: nop IL_0001: call 0x06000003 IL_0006: stloc.2 IL_0007: call 0x06000003 IL_000c: stloc.1 IL_000d: ldloc.2 IL_000e: call 0x0A000009 IL_0013: call 0x06000004 IL_0018: nop IL_0019: ldloc.1 IL_001a: call 0x0A000009 IL_001f: call 0x06000004 IL_0024: nop IL_0025: ret } ") diff3.VerifyPdb({&H06000001UI, &H06000002UI, &H06000003UI, &H06000004UI, &H06000005UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000005"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="19" document="1"/> <entry offset="0x1" startLine="15" startColumn="13" endLine="15" endColumn="30" document="1"/> <entry offset="0x7" startLine="16" startColumn="13" endLine="16" endColumn="30" document="1"/> <entry offset="0xd" startLine="17" startColumn="9" endLine="17" endColumn="13" document="1"/> <entry offset="0x19" startLine="18" startColumn="9" endLine="18" endColumn="13" document="1"/> <entry offset="0x25" startLine="19" startColumn="5" endLine="19" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x26"> <currentnamespace name=""/> <local name="c" il_index="2" il_start="0x0" il_end="0x26" attributes="0"/> <local name="b" il_index="1" il_start="0x0" il_end="0x26" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub ''' <summary> ''' Preserve locals for method added after initial compilation. ''' </summary> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PreserveLocalSlots_NewMethod() Dim sources0 = <compilation> <file><![CDATA[ Class C End Class ]]></file> </compilation> Dim sources1 = <compilation> <file><![CDATA[ Class C Shared Sub M() Dim a = New Object() Dim b = String.Empty End Sub End Class ]]></file> </compilation> Dim sources2 = <compilation> <file><![CDATA[ Class C Shared Sub M() Dim a = 1 Dim b = String.Empty End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim bytes0 = compilation0.EmitToArray() Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, method1, Nothing, preserveLocalVariables:=True))) Dim method2 = compilation2.GetMember(Of MethodSymbol)("C.M") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables:=True))) diff2.VerifyIL("C.M", <![CDATA[ { // Code size 10 (0xa) .maxstack 1 .locals init ([object] V_0, String V_1, //b Integer V_2) //a IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldsfld "String.Empty As String" IL_0008: stloc.1 IL_0009: ret } ]]>.Value) diff2.VerifyPdb({&H06000002UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000002"> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="19" document="1"/> <entry offset="0x1" startLine="3" startColumn="13" endLine="3" endColumn="18" document="1"/> <entry offset="0x3" startLine="4" startColumn="13" endLine="4" endColumn="29" document="1"/> <entry offset="0x9" startLine="5" startColumn="5" endLine="5" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xa"> <currentnamespace name=""/> <local name="a" il_index="2" il_start="0x0" il_end="0xa" attributes="0"/> <local name="b" il_index="1" il_start="0x0" il_end="0xa" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub ''' <summary> ''' Local types should be retained, even if the local is no longer ''' used by the method body, since there may be existing ''' references to that slot, in a Watch window for instance. ''' </summary> <WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")> <Fact> Public Sub PreserveLocalTypes() Dim sources0 = <compilation> <file><![CDATA[ Class C Shared Sub Main() Dim x = True Dim y = x System.Console.WriteLine(y) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file><![CDATA[ Class C Shared Sub Main() Dim x = "A" Dim y = x System.Console.WriteLine(y) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.Main") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.Main") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.VerifyIL("C.Main", " { // Code size 17 (0x11) .maxstack 1 .locals init ([bool] V_0, [bool] V_1, String V_2, //x String V_3) //y IL_0000: nop IL_0001: ldstr ""A"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: stloc.3 IL_0009: ldloc.3 IL_000a: call ""Sub System.Console.WriteLine(String)"" IL_000f: nop IL_0010: ret }") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsReferences() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x = new system.collections.generic.stack(of Integer) x.Push(1) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, XmlReferences, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.Stack(Of Integer) V_0) //x IL_0000: nop IL_0001: newobj ""Sub System.Collections.Generic.Stack(Of Integer)..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt ""Sub System.Collections.Generic.Stack(Of Integer).Push(Integer)"" IL_000e: nop IL_000f: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim modMeta = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(modMeta, testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", <![CDATA[ { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.Stack(Of Integer) V_0) //x IL_0000: nop IL_0001: newobj "Sub System.Collections.Generic.Stack(Of Integer)..ctor()" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt "Sub System.Collections.Generic.Stack(Of Integer).Push(Integer)" IL_000e: nop IL_000f: ret } ]]>.Value) End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsUsing() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.IDisposable = nothing Using x end using End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 21 (0x15) .maxstack 1 .locals init (System.IDisposable V_0, //x System.IDisposable V_1) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 .try { IL_0006: leave.s IL_0014 } finally { IL_0008: nop IL_0009: ldloc.1 IL_000a: brfalse.s IL_0013 IL_000c: ldloc.1 IL_000d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0012: nop IL_0013: endfinally } IL_0014: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 21 (0x15) .maxstack 1 .locals init (System.IDisposable V_0, //x System.IDisposable V_1) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 .try { IL_0006: leave.s IL_0014 } finally { IL_0008: nop IL_0009: ldloc.1 IL_000a: brfalse.s IL_0013 IL_000c: ldloc.1 IL_000d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0012: nop IL_0013: endfinally } IL_0014: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsWithByRef() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing With x(3) .ToString() end With End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 27 (0x1b) .maxstack 2 .locals init (System.Guid() V_0, //x System.Guid& V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: ldc.i4.3 IL_0006: ldelema ""System.Guid"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: constrained. ""System.Guid"" IL_0013: callvirt ""Function Object.ToString() As String"" IL_0018: pop IL_0019: nop IL_001a: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 27 (0x1b) .maxstack 2 .locals init (System.Guid() V_0, //x System.Guid& V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: ldc.i4.3 IL_0006: ldelema ""System.Guid"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: constrained. ""System.Guid"" IL_0013: callvirt ""Function Object.ToString() As String"" IL_0018: pop IL_0019: nop IL_001a: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsWithByVal() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing With x .ToString() end With End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 17 (0x11) .maxstack 1 .locals init (System.Guid() V_0, //x System.Guid() V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: pop IL_000d: nop IL_000e: ldnull IL_000f: stloc.1 IL_0010: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 17 (0x11) .maxstack 1 .locals init (System.Guid() V_0, //x System.Guid() V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: pop IL_000d: nop IL_000e: ldnull IL_000f: stloc.1 IL_0010: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsSyncLock() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing SyncLock x dim y as System.Guid() = nothing SyncLock y x.ToString() end SyncLock end SyncLock End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 76 (0x4c) .maxstack 2 .locals init (System.Guid() V_0, //x Object V_1, Boolean V_2, System.Guid() V_3, //y Object V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldc.i4.0 IL_0007: stloc.2 .try { IL_0008: ldloc.1 IL_0009: ldloca.s V_2 IL_000b: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0010: nop IL_0011: ldnull IL_0012: stloc.3 IL_0013: nop IL_0014: ldloc.3 IL_0015: stloc.s V_4 IL_0017: ldc.i4.0 IL_0018: stloc.s V_5 .try { IL_001a: ldloc.s V_4 IL_001c: ldloca.s V_5 IL_001e: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0023: nop IL_0024: ldloc.0 IL_0025: callvirt ""Function Object.ToString() As String"" IL_002a: pop IL_002b: leave.s IL_003b } finally { IL_002d: ldloc.s V_5 IL_002f: brfalse.s IL_0039 IL_0031: ldloc.s V_4 IL_0033: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0038: nop IL_0039: nop IL_003a: endfinally } IL_003b: nop IL_003c: leave.s IL_004a } finally { IL_003e: ldloc.2 IL_003f: brfalse.s IL_0048 IL_0041: ldloc.1 IL_0042: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0047: nop IL_0048: nop IL_0049: endfinally } IL_004a: nop IL_004b: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 76 (0x4c) .maxstack 2 .locals init (System.Guid() V_0, //x Object V_1, Boolean V_2, System.Guid() V_3, //y Object V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldc.i4.0 IL_0007: stloc.2 .try { IL_0008: ldloc.1 IL_0009: ldloca.s V_2 IL_000b: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0010: nop IL_0011: ldnull IL_0012: stloc.3 IL_0013: nop IL_0014: ldloc.3 IL_0015: stloc.s V_4 IL_0017: ldc.i4.0 IL_0018: stloc.s V_5 .try { IL_001a: ldloc.s V_4 IL_001c: ldloca.s V_5 IL_001e: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0023: nop IL_0024: ldloc.0 IL_0025: callvirt ""Function Object.ToString() As String"" IL_002a: pop IL_002b: leave.s IL_003b } finally { IL_002d: ldloc.s V_5 IL_002f: brfalse.s IL_0039 IL_0031: ldloc.s V_4 IL_0033: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0038: nop IL_0039: nop IL_003a: endfinally } IL_003b: nop IL_003c: leave.s IL_004a } finally { IL_003e: ldloc.2 IL_003f: brfalse.s IL_0048 IL_0041: ldloc.1 IL_0042: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0047: nop IL_0048: nop IL_0049: endfinally } IL_004a: nop IL_004b: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsForEach() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Collections.Generic.List(of integer) = nothing for each [i] in [x] Next for each i as integer in x Next End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 101 (0x65) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x System.Collections.Generic.List(Of Integer).Enumerator V_1, Integer V_2, //i Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Integer V_5, //i Boolean V_6) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.1 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_1 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.2 IL_0014: nop IL_0015: ldloca.s V_1 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_1 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0046 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.s V_5 IL_0045: nop IL_0046: ldloca.s V_4 IL_0048: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004d: stloc.s V_6 IL_004f: ldloc.s V_6 IL_0051: brtrue.s IL_003c IL_0053: leave.s IL_0064 } finally { IL_0055: ldloca.s V_4 IL_0057: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0062: nop IL_0063: endfinally } IL_0064: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 101 (0x65) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x System.Collections.Generic.List(Of Integer).Enumerator V_1, Integer V_2, //i Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Integer V_5, //i Boolean V_6) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.1 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_1 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.2 IL_0014: nop IL_0015: ldloca.s V_1 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_1 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0046 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.s V_5 IL_0045: nop IL_0046: ldloca.s V_4 IL_0048: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004d: stloc.s V_6 IL_004f: ldloc.s V_6 IL_0051: brtrue.s IL_003c IL_0053: leave.s IL_0064 } finally { IL_0055: ldloca.s V_4 IL_0057: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0062: nop IL_0063: endfinally } IL_0064: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsForEach001() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Collections.Generic.List(of integer) = nothing Dim i as integer for each i in x Next for each i in x Next End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 100 (0x64) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x Integer V_1, //i System.Collections.Generic.List(Of Integer).Enumerator V_2, Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.2 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_2 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.1 IL_0014: nop IL_0015: ldloca.s V_2 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_2 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0045 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.1 IL_0044: nop IL_0045: ldloca.s V_4 IL_0047: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004c: stloc.s V_5 IL_004e: ldloc.s V_5 IL_0050: brtrue.s IL_003c IL_0052: leave.s IL_0063 } finally { IL_0054: ldloca.s V_4 IL_0056: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005c: callvirt ""Sub System.IDisposable.Dispose()"" IL_0061: nop IL_0062: endfinally } IL_0063: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 100 (0x64) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x Integer V_1, //i System.Collections.Generic.List(Of Integer).Enumerator V_2, Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.2 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_2 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.1 IL_0014: nop IL_0015: ldloca.s V_2 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_2 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0045 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.1 IL_0044: nop IL_0045: ldloca.s V_4 IL_0047: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004c: stloc.s V_5 IL_004e: ldloc.s V_5 IL_0050: brtrue.s IL_003c IL_0052: leave.s IL_0063 } finally { IL_0054: ldloca.s V_4 IL_0056: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005c: callvirt ""Sub System.IDisposable.Dispose()"" IL_0061: nop IL_0062: endfinally } IL_0063: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsFor001() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As object) for i as double = goo() to goo() step goo() for j as double = goo() to goo() step goo() next next End Sub shared function goo() as double return 1 end function End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 148 (0x94) .maxstack 2 .locals init (Double V_0, Double V_1, Double V_2, Boolean V_3, Double V_4, //i Double V_5, Double V_6, Double V_7, Boolean V_8, Double V_9) //j IL_0000: nop IL_0001: call ""Function C.goo() As Double"" IL_0006: stloc.0 IL_0007: call ""Function C.goo() As Double"" IL_000c: stloc.1 IL_000d: call ""Function C.goo() As Double"" IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldc.r8 0 IL_001d: clt.un IL_001f: ldc.i4.0 IL_0020: ceq IL_0022: stloc.3 IL_0023: ldloc.0 IL_0024: stloc.s V_4 IL_0026: br.s IL_007c IL_0028: call ""Function C.goo() As Double"" IL_002d: stloc.s V_5 IL_002f: call ""Function C.goo() As Double"" IL_0034: stloc.s V_6 IL_0036: call ""Function C.goo() As Double"" IL_003b: stloc.s V_7 IL_003d: ldloc.s V_7 IL_003f: ldc.r8 0 IL_0048: clt.un IL_004a: ldc.i4.0 IL_004b: ceq IL_004d: stloc.s V_8 IL_004f: ldloc.s V_5 IL_0051: stloc.s V_9 IL_0053: br.s IL_005c IL_0055: ldloc.s V_9 IL_0057: ldloc.s V_7 IL_0059: add IL_005a: stloc.s V_9 IL_005c: ldloc.s V_8 IL_005e: brtrue.s IL_006b IL_0060: ldloc.s V_9 IL_0062: ldloc.s V_6 IL_0064: clt.un IL_0066: ldc.i4.0 IL_0067: ceq IL_0069: br.s IL_0074 IL_006b: ldloc.s V_9 IL_006d: ldloc.s V_6 IL_006f: cgt.un IL_0071: ldc.i4.0 IL_0072: ceq IL_0074: brtrue.s IL_0055 IL_0076: ldloc.s V_4 IL_0078: ldloc.2 IL_0079: add IL_007a: stloc.s V_4 IL_007c: ldloc.3 IL_007d: brtrue.s IL_0089 IL_007f: ldloc.s V_4 IL_0081: ldloc.1 IL_0082: clt.un IL_0084: ldc.i4.0 IL_0085: ceq IL_0087: br.s IL_0091 IL_0089: ldloc.s V_4 IL_008b: ldloc.1 IL_008c: cgt.un IL_008e: ldc.i4.0 IL_008f: ceq IL_0091: brtrue.s IL_0028 IL_0093: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 148 (0x94) .maxstack 2 .locals init (Double V_0, Double V_1, Double V_2, Boolean V_3, Double V_4, //i Double V_5, Double V_6, Double V_7, Boolean V_8, Double V_9) //j IL_0000: nop IL_0001: call ""Function C.goo() As Double"" IL_0006: stloc.0 IL_0007: call ""Function C.goo() As Double"" IL_000c: stloc.1 IL_000d: call ""Function C.goo() As Double"" IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldc.r8 0 IL_001d: clt.un IL_001f: ldc.i4.0 IL_0020: ceq IL_0022: stloc.3 IL_0023: ldloc.0 IL_0024: stloc.s V_4 IL_0026: br.s IL_007c IL_0028: call ""Function C.goo() As Double"" IL_002d: stloc.s V_5 IL_002f: call ""Function C.goo() As Double"" IL_0034: stloc.s V_6 IL_0036: call ""Function C.goo() As Double"" IL_003b: stloc.s V_7 IL_003d: ldloc.s V_7 IL_003f: ldc.r8 0 IL_0048: clt.un IL_004a: ldc.i4.0 IL_004b: ceq IL_004d: stloc.s V_8 IL_004f: ldloc.s V_5 IL_0051: stloc.s V_9 IL_0053: br.s IL_005c IL_0055: ldloc.s V_9 IL_0057: ldloc.s V_7 IL_0059: add IL_005a: stloc.s V_9 IL_005c: ldloc.s V_8 IL_005e: brtrue.s IL_006b IL_0060: ldloc.s V_9 IL_0062: ldloc.s V_6 IL_0064: clt.un IL_0066: ldc.i4.0 IL_0067: ceq IL_0069: br.s IL_0074 IL_006b: ldloc.s V_9 IL_006d: ldloc.s V_6 IL_006f: cgt.un IL_0071: ldc.i4.0 IL_0072: ceq IL_0074: brtrue.s IL_0055 IL_0076: ldloc.s V_4 IL_0078: ldloc.2 IL_0079: add IL_007a: stloc.s V_4 IL_007c: ldloc.3 IL_007d: brtrue.s IL_0089 IL_007f: ldloc.s V_4 IL_0081: ldloc.1 IL_0082: clt.un IL_0084: ldc.i4.0 IL_0085: ceq IL_0087: br.s IL_0091 IL_0089: ldloc.s V_4 IL_008b: ldloc.1 IL_008c: cgt.un IL_008e: ldc.i4.0 IL_008f: ceq IL_0091: brtrue.s IL_0028 IL_0093: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicit() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ option explicit off Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing With x Dim z = .ToString y = z end With End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 19 (0x13) .maxstack 1 .locals init (Object V_0, //y System.Guid() V_1, //x System.Guid() V_2, //$W0 String V_3) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: nop IL_0004: ldloc.1 IL_0005: stloc.2 IL_0006: ldloc.2 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: stloc.3 IL_000d: ldloc.3 IL_000e: stloc.0 IL_000f: nop IL_0010: ldnull IL_0011: stloc.2 IL_0012: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 19 (0x13) .maxstack 1 .locals init (Object V_0, //y System.Guid() V_1, //x System.Guid() V_2, //$W0 String V_3) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: nop IL_0004: ldloc.1 IL_0005: stloc.2 IL_0006: ldloc.2 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: stloc.3 IL_000d: ldloc.3 IL_000e: stloc.0 IL_000f: nop IL_0010: ldnull IL_0011: stloc.2 IL_0012: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicitQualified() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ option explicit off Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing goto Length ' this does not declare Length Length: ' this does not declare Length dim y = x.Length ' this does not declare Length Length = 5 ' this does End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim actualIL0 = testData0.GetMethodData("C.M").GetMethodIL() Dim expectedIL0 = " { // Code size 18 (0x12) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Integer V_2) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: br.s IL_0005 IL_0005: nop IL_0006: ldloc.1 IL_0007: ldlen IL_0008: conv.i4 IL_0009: stloc.2 IL_000a: ldc.i4.5 IL_000b: box ""Integer"" IL_0010: stloc.0 IL_0011: ret } " AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL0, actualIL0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 18 (0x12) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Integer V_2) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: br.s IL_0005 IL_0005: nop IL_0006: ldloc.1 IL_0007: ldlen IL_0008: conv.i4 IL_0009: stloc.2 IL_000a: ldc.i4.5 IL_000b: box ""Integer"" IL_0010: stloc.0 IL_0011: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicitXmlNs() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ option explicit off Imports <xmlns:Length="http: //roslyn/F"> Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing GetXmlNamespace(Length).ToString() ' this does not declare Length dim z as object = GetXmlNamespace(Length) ' this does not declare Length Length = 5 ' this does Dim aa = Length End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, XmlReferences, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 45 (0x2d) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Object V_2, //z Object V_3) //aa IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: ldstr ""http: //roslyn/F"" IL_0008: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_000d: callvirt ""Function System.Xml.Linq.XNamespace.ToString() As String"" IL_0012: pop IL_0013: ldstr ""http: //roslyn/F"" IL_0018: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_001d: stloc.2 IL_001e: ldc.i4.5 IL_001f: box ""Integer"" IL_0024: stloc.0 IL_0025: ldloc.0 IL_0026: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_002b: stloc.3 IL_002c: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 45 (0x2d) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Object V_2, //z Object V_3) //aa IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: ldstr ""http: //roslyn/F"" IL_0008: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_000d: callvirt ""Function System.Xml.Linq.XNamespace.ToString() As String"" IL_0012: pop IL_0013: ldstr ""http: //roslyn/F"" IL_0018: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_001d: stloc.2 IL_001e: ldc.i4.5 IL_001f: box ""Integer"" IL_0024: stloc.0 IL_0025: ldloc.0 IL_0026: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_002b: stloc.3 IL_002c: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicitNamedArgXml() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Option Explicit Off Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub F(qq As Object) End Sub Shared Sub M(o As Object) F(qq:=<qq a="qq"></>) 'does not declare qq qq = 5 Dim aa = qq End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, XmlReferences, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim actualIL0 = testData0.GetMethodData("C.M").GetMethodIL() Dim expectedIL0 = <![CDATA[ { // Code size 88 (0x58) .maxstack 3 .locals init (Object V_0, //qq Object V_1, //aa System.Xml.Linq.XElement V_2) IL_0000: nop IL_0001: ldstr "qq" IL_0006: ldstr "" IL_000b: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0010: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0015: stloc.2 IL_0016: ldloc.2 IL_0017: ldstr "a" IL_001c: ldstr "" IL_0021: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0026: ldstr "qq" IL_002b: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_0030: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0035: nop IL_0036: ldloc.2 IL_0037: ldstr "" IL_003c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0041: nop IL_0042: ldloc.2 IL_0043: call "Sub C.F(Object)" IL_0048: nop IL_0049: ldc.i4.5 IL_004a: box "Integer" IL_004f: stloc.0 IL_0050: ldloc.0 IL_0051: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0056: stloc.1 IL_0057: ret } ]]>.Value AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL0, actualIL0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", <![CDATA[ { // Code size 88 (0x58) .maxstack 3 .locals init (Object V_0, //qq Object V_1, //aa [unchanged] V_2, System.Xml.Linq.XElement V_3) IL_0000: nop IL_0001: ldstr "qq" IL_0006: ldstr "" IL_000b: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0010: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0015: stloc.3 IL_0016: ldloc.3 IL_0017: ldstr "a" IL_001c: ldstr "" IL_0021: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0026: ldstr "qq" IL_002b: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_0030: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0035: nop IL_0036: ldloc.3 IL_0037: ldstr "" IL_003c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0041: nop IL_0042: ldloc.3 IL_0043: call "Sub C.F(Object)" IL_0048: nop IL_0049: ldc.i4.5 IL_004a: box "Integer" IL_004f: stloc.0 IL_0050: ldloc.0 IL_0051: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0056: stloc.1 IL_0057: ret } ]]>.Value) End Sub <Fact> Public Sub AnonymousTypes_Update() Dim source0 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 1 } End Sub End Class ") Dim source1 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 2 } End Sub End Class ") Dim source2 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 3 } End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) v0.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") ' expect a single TypeRef for System.Object Dim md1 = diff1.GetMetadata() AssertEx.Equal({"[0x23000002] 0x0000020d.0x0000021a"}, DumpTypeRefs(md1.Reader)) Dim diff2 = compilation2.EmitDifference(diff1.NextGeneration, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") ' expect a single TypeRef for System.Object Dim md2 = diff2.GetMetadata() AssertEx.Equal({"[0x23000003] 0x00000256.0x00000263"}, DumpTypeRefs(md2.Reader)) End Sub <Fact> Public Sub AnonymousTypes_UpdateAfterAdd() Dim source0 = MarkedSource(" Class C Shared Sub F() End Sub End Class ") Dim source1 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 2 } End Sub End Class ") Dim source2 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 3 } End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") Dim diff2 = compilation2.EmitDifference(diff1.NextGeneration, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") ' expect a single TypeRef for System.Object Dim md2 = diff2.GetMetadata() AssertEx.Equal({"[0x23000003] 0x00000289.0x00000296"}, DumpTypeRefs(md2.Reader)) End Sub Private Shared Iterator Function DumpTypeRefs(reader As MetadataReader) As IEnumerable(Of String) For Each typeRefHandle In reader.TypeReferences Dim typeRef = reader.GetTypeReference(typeRefHandle) Yield $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] 0x{MetadataTokens.GetHeapOffset(typeRef.Namespace):x8}.0x{MetadataTokens.GetHeapOffset(typeRef.Name):x8}" Next End Function <Fact> Public Sub AnonymousTypes() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Namespace N Class A Shared F As Object = New With {.A = 1, .B = 2} End Class End Namespace Namespace M Class B Shared Sub M() Dim x As New With {.B = 3, .A = 4} Dim y = x.A Dim z As New With {.C = 5} End Sub End Class End Namespace ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Namespace N Class A Shared F As Object = New With {.A = 1, .B = 2} End Class End Namespace Namespace M Class B Shared Sub M() Dim x As New With {.B = 3, .A = 4} Dim y As New With {.A = x.A} Dim z As New With {.C = 5} End Sub End Class End Namespace ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("M.B.M").EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("M.B.M") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`2", "VB$AnonymousType_1`2", "VB$AnonymousType_2`1", "A", "B") Dim method1 = compilation1.GetMember(Of MethodSymbol)("M.B.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_3`1") diff1.VerifyIL("M.B.M", " { // Code size 29 (0x1d) .maxstack 2 .locals init (VB$AnonymousType_1(Of Integer, Integer) V_0, //x [int] V_1, VB$AnonymousType_2(Of Integer) V_2, //z VB$AnonymousType_3(Of Integer) V_3) //y IL_0000: nop IL_0001: ldc.i4.3 IL_0002: ldc.i4.4 IL_0003: newobj ""Sub VB$AnonymousType_1(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""Function VB$AnonymousType_1(Of Integer, Integer).get_A() As Integer"" IL_000f: newobj ""Sub VB$AnonymousType_3(Of Integer)..ctor(Integer)"" IL_0014: stloc.3 IL_0015: ldc.i4.5 IL_0016: newobj ""Sub VB$AnonymousType_2(Of Integer)..ctor(Integer)"" IL_001b: stloc.2 IL_001c: ret } ") End Using End Using End Sub ''' <summary> ''' Update method with anonymous type that was ''' not directly referenced in previous generation. ''' </summary> <Fact> Public Sub AnonymousTypes_SkipGeneration() Dim source0 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As Integer = 1 Return x End Function End Class ") Dim source1 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As Integer = 1 Return x + 1 End Function End Class ") Dim source2 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As New With {.A = New A()} Dim <N:2>y</N:2> As New With {.B = 2} Return x.A End Function End Class ") Dim source3 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As New With {.A = New A()} Dim <N:2>y</N:2> As New With {.B = 3} Return y.B End Function End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim compilation3 = compilation2.WithSource(source3.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim method0 = compilation0.GetMember(Of MethodSymbol)("B.G") Dim method1 = compilation1.GetMember(Of MethodSymbol)("B.G") Dim method2 = compilation2.GetMember(Of MethodSymbol)("B.G") Dim method3 = compilation3.GetMember(Of MethodSymbol)("B.G") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`1", "A", "B") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) Dim md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames()) ' no additional types diff1.VerifyIL("B.G", " { // Code size 16 (0x10) .maxstack 2 .locals init (Object V_0, //G Integer V_1) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.1 IL_0003: ldloc.1 IL_0004: ldc.i4.1 IL_0005: add.ovf IL_0006: box ""Integer"" IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } ") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) Dim md2 = diff2.GetMetadata() Dim reader2 = md2.Reader CheckNames({reader0, reader1, reader2}, reader2.GetTypeDefNames(), "VB$AnonymousType_1`1") ' one additional type diff2.VerifyIL("B.G", " { // Code size 30 (0x1e) .maxstack 1 .locals init (Object V_0, //G [int] V_1, VB$AnonymousType_0(Of A) V_2, //x VB$AnonymousType_1(Of Integer) V_3) //y IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: newobj ""Sub VB$AnonymousType_0(Of A)..ctor(A)"" IL_000b: stloc.2 IL_000c: ldc.i4.2 IL_000d: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_0012: stloc.3 IL_0013: ldloc.2 IL_0014: callvirt ""Function VB$AnonymousType_0(Of A).get_A() As A"" IL_0019: stloc.0 IL_001a: br.s IL_001c IL_001c: ldloc.0 IL_001d: ret } ") Dim diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables:=True))) Dim md3 = diff3.GetMetadata() Dim reader3 = md3.Reader CheckNames({reader0, reader1, reader2, reader3}, reader3.GetTypeDefNames()) ' no additional types diff3.VerifyIL("B.G", " { // Code size 35 (0x23) .maxstack 1 .locals init (Object V_0, //G [int] V_1, VB$AnonymousType_0(Of A) V_2, //x VB$AnonymousType_1(Of Integer) V_3) //y IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: newobj ""Sub VB$AnonymousType_0(Of A)..ctor(A)"" IL_000b: stloc.2 IL_000c: ldc.i4.3 IL_000d: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: callvirt ""Function VB$AnonymousType_1(Of Integer).get_B() As Integer"" IL_0019: box ""Integer"" IL_001e: stloc.0 IL_001f: br.s IL_0021 IL_0021: ldloc.0 IL_0022: ret } ") End Sub ''' <summary> ''' Update another method (without directly referencing ''' anonymous type) after updating method with anonymous type. ''' </summary> <Fact> Public Sub AnonymousTypes_SkipGeneration_2() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 1} Return x.A End Function Shared Function G() As Object Dim x As Integer = 1 Return x End Function End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 2, .B = 3} Return x.A End Function Shared Function G() As Object Dim x As Integer = 1 Return x End Function End Class ]]></file> </compilation> Dim sources2 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 2, .B = 3} Return x.A End Function Shared Function G() As Object Dim x As Integer = 1 Return x + 1 End Function End Class ]]></file> </compilation> Dim sources3 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 2, .B = 3} Return x.A End Function Shared Function G() As Object Dim x As New With {.A = DirectCast(Nothing, Object)} Dim y As New With {.A = "a"c, .B = "b"c} Return x End Function End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim compilation3 = compilation2.WithSource(sources3) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), Function(m) Select Case md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) Case "F" : Return testData0.GetMethodData("C.F").GetEncDebugInfo() Case "G" : Return testData0.GetMethodData("C.G").GetEncDebugInfo() End Select Return Nothing End Function) Dim method0F = compilation0.GetMember(Of MethodSymbol)("C.F") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`1", "C") Dim method1F = compilation1.GetMember(Of MethodSymbol)("C.F") Dim method1G = compilation1.GetMember(Of MethodSymbol)("C.G") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0F, method1F, GetEquivalentNodesMap(method1F, method0F), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_1`2") ' one additional type Dim method2G = compilation2.GetMember(Of MethodSymbol)("C.G") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1G, method2G, GetEquivalentNodesMap(method2G, method1G), preserveLocalVariables:=True))) Using md2 = diff2.GetMetadata() Dim reader2 = md2.Reader CheckNames({reader0, reader1, reader2}, reader2.GetTypeDefNames()) ' no additional types Dim method3G = compilation3.GetMember(Of MethodSymbol)("C.G") Dim diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method2G, method3G, GetEquivalentNodesMap(method3G, method2G), preserveLocalVariables:=True))) Using md3 = diff3.GetMetadata() Dim reader3 = md3.Reader CheckNames({reader0, reader1, reader2, reader3}, reader3.GetTypeDefNames()) ' no additional types End Using End Using End Using End Using End Sub <WorkItem(1292, "https://github.com/dotnet/roslyn/issues/1292")> <Fact> Public Sub AnonymousTypes_Key() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.A = 1, .B = 2} Dim y As New With {Key .A = 3, .B = 4} Dim z As New With {.A = 5, Key .B = 6} End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.A = 1, .B = 2} Dim y As New With {Key .A = 3, Key .B = 4} Dim z As New With {Key .A = 5, .B = 6} End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`2", "VB$AnonymousType_1`2", "VB$AnonymousType_2`2", "C") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_3`2") diff1.VerifyIL("C.M", "{ // Code size 27 (0x1b) .maxstack 2 .locals init (VB$AnonymousType_0(Of Integer, Integer) V_0, //x [unchanged] V_1, [unchanged] V_2, VB$AnonymousType_3(Of Integer, Integer) V_3, //y VB$AnonymousType_1(Of Integer, Integer) V_4) //z IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""Sub VB$AnonymousType_0(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.0 IL_0009: ldc.i4.3 IL_000a: ldc.i4.4 IL_000b: newobj ""Sub VB$AnonymousType_3(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0010: stloc.3 IL_0011: ldc.i4.5 IL_0012: ldc.i4.6 IL_0013: newobj ""Sub VB$AnonymousType_1(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0018: stloc.s V_4 IL_001a: ret }") End Using End Using End Sub <Fact> Public Sub AnonymousTypes_DifferentCase() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.A = 1, .B = 2} Dim y As New With {.a = 3, .b = 4} End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.a = 1, .B = 2} Dim y As New With {.AB = 3} Dim z As New With {.ab = 4} End Sub End Class ]]></file> </compilation> Dim sources2 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.a = 1, .B = 2} Dim z As New With {.Ab = 5} End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`2", "C") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_1`1") diff1.VerifyIL("C.M", "{ // Code size 25 (0x19) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, VB$AnonymousType_0(Of Integer, Integer) V_2, //x VB$AnonymousType_1(Of Integer) V_3, //y VB$AnonymousType_1(Of Integer) V_4) //z IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""Sub VB$AnonymousType_0(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.2 IL_0009: ldc.i4.3 IL_000a: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_000f: stloc.3 IL_0010: ldc.i4.4 IL_0011: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_0016: stloc.s V_4 IL_0018: ret }") Dim method2 = compilation2.GetMember(Of MethodSymbol)("C.M") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables:=True))) Using md2 = diff2.GetMetadata() Dim reader2 = md2.Reader CheckNames({reader0, reader1, reader2}, reader2.GetTypeDefNames()) diff2.VerifyIL("C.M", "{ // Code size 18 (0x12) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, VB$AnonymousType_0(Of Integer, Integer) V_2, //x [unchanged] V_3, [unchanged] V_4, VB$AnonymousType_1(Of Integer) V_5) //z IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""Sub VB$AnonymousType_0(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.2 IL_0009: ldc.i4.5 IL_000a: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_000f: stloc.s V_5 IL_0011: ret }") End Using End Using End Using End Sub <Fact> Public Sub AnonymousTypes_Nested() Dim template = " Imports System Imports System.Linq Class C Sub F(args As String()) Dim <N:4>result</N:4> = From a in args Let <N:0>x = a.Reverse()</N:0> Let <N:1>y = x.Reverse()</N:1> <N:2>Where x.SequenceEqual(y)</N:2> Select <N:3>Value = a</N:3>, Length = a.Length Console.WriteLine(<<VALUE>>) End Sub End Class " Dim source0 = MarkedSource(template.Replace("<<VALUE>>", "0")) Dim source1 = MarkedSource(template.Replace("<<VALUE>>", "1")) Dim source2 = MarkedSource(template.Replace("<<VALUE>>", "2")) Dim compilation0 = CreateCompilationWithMscorlib45({source0.Tree}, {SystemCoreRef}, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation0.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim expectedIL = " { // Code size 175 (0xaf) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable(Of <anonymous type: Key Value As String, Key Length As Integer>) V_0) //result IL_0000: nop IL_0001: ldarg.1 IL_0002: ldsfld ""C._Closure$__.$I1-0 As System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0007: brfalse.s IL_0010 IL_0009: ldsfld ""C._Closure$__.$I1-0 As System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_000e: br.s IL_0026 IL_0010: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0015: ldftn ""Function C._Closure$__._Lambda$__1-0(String) As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>"" IL_001b: newobj ""Sub System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)..ctor(Object, System.IntPtr)"" IL_0020: dup IL_0021: stsfld ""C._Closure$__.$I1-0 As System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0026: call ""Function System.Linq.Enumerable.Select(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)(System.Collections.Generic.IEnumerable(Of String), System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_002b: ldsfld ""C._Closure$__.$I1-1 As System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0030: brfalse.s IL_0039 IL_0032: ldsfld ""C._Closure$__.$I1-1 As System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0037: br.s IL_004f IL_0039: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_003e: ldftn ""Function C._Closure$__._Lambda$__1-1(<anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>) As <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>"" IL_0044: newobj ""Sub System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)..ctor(Object, System.IntPtr)"" IL_0049: dup IL_004a: stsfld ""C._Closure$__.$I1-1 As System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_004f: call ""Function System.Linq.Enumerable.Select(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)(System.Collections.Generic.IEnumerable(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>), System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0054: ldsfld ""C._Closure$__.$I1-2 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)"" IL_0059: brfalse.s IL_0062 IL_005b: ldsfld ""C._Closure$__.$I1-2 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)"" IL_0060: br.s IL_0078 IL_0062: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0067: ldftn ""Function C._Closure$__._Lambda$__1-2(<anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>) As Boolean"" IL_006d: newobj ""Sub System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)..ctor(Object, System.IntPtr)"" IL_0072: dup IL_0073: stsfld ""C._Closure$__.$I1-2 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)"" IL_0078: call ""Function System.Linq.Enumerable.Where(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)(System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>), System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_007d: ldsfld ""C._Closure$__.$I1-3 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)"" IL_0082: brfalse.s IL_008b IL_0084: ldsfld ""C._Closure$__.$I1-3 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)"" IL_0089: br.s IL_00a1 IL_008b: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0090: ldftn ""Function C._Closure$__._Lambda$__1-3(<anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>) As <anonymous type: Key Value As String, Key Length As Integer>"" IL_0096: newobj ""Sub System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)..ctor(Object, System.IntPtr)"" IL_009b: dup IL_009c: stsfld ""C._Closure$__.$I1-3 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)"" IL_00a1: call ""Function System.Linq.Enumerable.Select(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)(System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>), System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key Value As String, Key Length As Integer>)"" IL_00a6: stloc.0 IL_00a7: ldc.i4.<<VALUE>> IL_00a8: call ""Sub System.Console.WriteLine(Integer)"" IL_00ad: nop IL_00ae: ret }" v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifySynthesizedMembers( "C: {_Closure$__}", "C._Closure$__: {$I1-0, $I1-1, $I1-2, $I1-3, _Lambda$__1-0, _Lambda$__1-1, _Lambda$__1-2, _Lambda$__1-3}") diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")) Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifySynthesizedMembers( "C: {_Closure$__}", "C._Closure$__: {$I1-0, $I1-1, $I1-2, $I1-3, _Lambda$__1-0, _Lambda$__1-1, _Lambda$__1-2, _Lambda$__1-3}") diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")) End Sub <Fact> Public Sub AnonymousDelegates1() Dim source0 = MarkedSource(" Class C Private Sub F() Dim <N:0>g</N:0> = <N:1>Function(ByRef arg As String) arg</N:1> System.Console.WriteLine(1) End Sub End Class ") Dim source1 = MarkedSource(" Class C Private Sub F() Dim <N:0>g</N:0> = <N:1>Function(ByRef arg As String) arg</N:1> System.Console.WriteLine(2) End Sub End Class ") Dim source2 = MarkedSource(" Class C Private Sub F() Dim <N:0>g</N:0> = <N:1>Function(ByRef arg As String) arg</N:1> System.Console.WriteLine(3) End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40({source0.Tree}, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) v0.VerifyIL("C.F", " { // Code size 46 (0x2e) .maxstack 2 .locals init (VB$AnonymousDelegate_0(Of String, String) V_0) //g IL_0000: nop IL_0001: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0006: brfalse.s IL_000f IL_0008: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_000d: br.s IL_0025 IL_000f: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0014: ldftn ""Function C._Closure$__._Lambda$__1-0(ByRef String) As String"" IL_001a: newobj ""Sub VB$AnonymousDelegate_0(Of String, String)..ctor(Object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0025: stloc.0 IL_0026: ldc.i4.1 IL_0027: call ""Sub System.Console.WriteLine(Integer)"" IL_002c: nop IL_002d: ret } ") Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 46 (0x2e) .maxstack 2 .locals init (VB$AnonymousDelegate_0(Of String, String) V_0) //g IL_0000: nop IL_0001: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0006: brfalse.s IL_000f IL_0008: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_000d: br.s IL_0025 IL_000f: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0014: ldftn ""Function C._Closure$__._Lambda$__1-0(ByRef String) As String"" IL_001a: newobj ""Sub VB$AnonymousDelegate_0(Of String, String)..ctor(Object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0025: stloc.0 IL_0026: ldc.i4.2 IL_0027: call ""Sub System.Console.WriteLine(Integer)"" IL_002c: nop IL_002d: ret } ") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifyIL("C.F", " { // Code size 46 (0x2e) .maxstack 2 .locals init (VB$AnonymousDelegate_0(Of String, String) V_0) //g IL_0000: nop IL_0001: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0006: brfalse.s IL_000f IL_0008: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_000d: br.s IL_0025 IL_000f: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0014: ldftn ""Function C._Closure$__._Lambda$__1-0(ByRef String) As String"" IL_001a: newobj ""Sub VB$AnonymousDelegate_0(Of String, String)..ctor(Object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0025: stloc.0 IL_0026: ldc.i4.3 IL_0027: call ""Sub System.Console.WriteLine(Integer)"" IL_002c: nop IL_002d: ret } ") End Sub ''' <summary> ''' Should not re-use locals with custom modifiers. ''' </summary> <Fact(Skip:="9854")> <WorkItem(9854, "https://github.com/dotnet/roslyn/issues/9854")> Public Sub LocalType_CustomModifiers() ' Equivalent method signature to VB, but ' with optional modifiers on locals. Dim ilSource = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public C { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F(class [mscorlib]System.IDisposable d) { .locals init ([0] object F, [1] class C modopt(int32) c, [2] class [mscorlib]System.IDisposable modopt(object) VB$Using, [3] bool V_3) ldnull ret } } ]]>.Value Dim source = <compilation> <file name="c.vb"><![CDATA[ Class C Shared Function F(d As System.IDisposable) As Object Dim c As C Using d c = DirectCast(d, C) End Using Return c End Function End Class ]]> </file> </compilation> Dim metadata0 = DirectCast(CompileIL(ilSource, prependDefaultHeader:=False), MetadataImageReference) ' Still need a compilation with source for the initial ' generation - to get a MethodSymbol and syntax map. Dim compilation0 = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim moduleMetadata0 = DirectCast(metadata0.GetMetadataNoCopy(), AssemblyMetadata).GetModules(0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline( moduleMetadata0, Function(m) Nothing) Dim testData1 = New CompilationTestData() Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.F", " { // Code size 45 (0x2d) .maxstack 2 .locals init ([object] V_0, [unchanged] V_1, [unchanged] V_2, [bool] V_3, Object V_4, //F C V_5, //c System.IDisposable V_6, //VB$Using Boolean V_7) IL_0000: nop IL_0001: nop IL_0002: ldarg.0 IL_0003: stloc.s V_6 .try { IL_0005: ldarg.0 IL_0006: castclass ""C"" IL_000b: stloc.s V_5 IL_000d: leave.s IL_0024 } finally { IL_000f: nop IL_0010: ldloc.s V_6 IL_0012: ldnull IL_0013: ceq IL_0015: stloc.s V_7 IL_0017: ldloc.s V_7 IL_0019: brtrue.s IL_0023 IL_001b: ldloc.s V_6 IL_001d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0022: nop IL_0023: endfinally } IL_0024: ldloc.s V_5 IL_0026: stloc.s V_4 IL_0028: br.s IL_002a IL_002a: ldloc.s V_4 IL_002c: ret } ") End Sub <WorkItem(839414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839414")> <Fact> Public Sub Bug839414() Dim source0 = <compilation> <file name="a.vb"> Module M Function F() As Object Static x = 1 Return x End Function End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module M Function F() As Object Static x = "2" Return x End Function End Module </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Dim method0 = compilation0.GetMember(Of MethodSymbol)("M.F") Dim method1 = compilation1.GetMember(Of MethodSymbol)("M.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) End Sub <WorkItem(849649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849649")> <Fact> Public Sub Bug849649() Dim source0 = <compilation> <file name="a.vb"> Module M Sub F() Dim x(5) As Integer x(3) = 2 End Sub End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module M Sub F() Dim x(5) As Integer x(3) = 3 End Sub End Module </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Dim method0 = compilation0.GetMember(Of MethodSymbol)("M.F") Dim method1 = compilation1.GetMember(Of MethodSymbol)("M.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff0 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff0.VerifyIL(" { // Code size 13 (0xd) .maxstack 3 IL_0000: nop IL_0001: ldc.i4.6 IL_0002: newarr 0x0100000A IL_0007: stloc.1 IL_0008: ldloc.1 IL_0009: ldc.i4.3 IL_000a: ldc.i4.3 IL_000b: stelem.i4 IL_000c: ret } ") End Sub #End Region <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SymWriterErrors() Dim source0 = <compilation> <file name="a.vb"><![CDATA[ Class C End Class ]]></file> </compilation> Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Class C Sub Main() End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) ' Verify full metadata contains expected rows. Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, compilation1.GetMember(Of MethodSymbol)("C.Main"))), testData:=New CompilationTestData With {.SymWriterFactory = Function() New MockSymUnmanagedWriter()}) diff1.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_PDBWritingFailed).WithArguments("MockSymUnmanagedWriter error message")) Assert.False(diff1.EmitResult.Success) End Using End Sub <WorkItem(1003274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1003274")> <Fact> Public Sub ConditionalAttribute() Const source0 = " Imports System.Diagnostics Class C Sub M() ' Body End Sub <Conditional(""Defined"")> Sub N1() End Sub <Conditional(""Undefined"")> Sub N2() End Sub End Class " Dim parseOptions As New VisualBasicParseOptions(preprocessorSymbols:={New KeyValuePair(Of String, Object)("Defined", True)}) Dim tree0 = VisualBasicSyntaxTree.ParseText(source0, parseOptions) Dim tree1 = VisualBasicSyntaxTree.ParseText(source0.Replace("' Body", "N1(): N2()"), parseOptions) Dim compilation0 = CreateCompilationWithMscorlib40({tree0}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.ReplaceSyntaxTree(tree0, tree1) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) diff1.EmitResult.Diagnostics.AssertNoErrors() diff1.VerifyIL("C.M", " { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""Sub C.N1()"" IL_0007: nop IL_0008: ret } ") End Using End Sub <Fact> Public Sub ReferenceToMemberAddedToAnotherAssembly1() Dim sourceA0 = " Public Class A End Class " Dim sourceA1 = " Public Class A Public Sub M() System.Console.WriteLine(1) End Sub End Class Public Class X End Class " Dim sourceB0 = " Public Class B Public Shared Sub F() End Sub End Class" Dim sourceB1 = " Public Class B Public Shared Sub F() Dim a = New A() a.M() End Sub End Class Public Class Y Inherits X End Class " Dim compilationA0 = CreateCompilationWithMscorlib40({sourceA0}, options:=TestOptions.DebugDll, assemblyName:="LibA") Dim compilationA1 = compilationA0.WithSource(sourceA1) Dim compilationB0 = CreateCompilationWithMscorlib40({sourceB0}, {compilationA0.ToMetadataReference()}, options:=TestOptions.DebugDll, assemblyName:="LibB") Dim compilationB1 = CreateCompilationWithMscorlib40({sourceB1}, {compilationA1.ToMetadataReference()}, options:=TestOptions.DebugDll, assemblyName:="LibB") Dim bytesA0 = compilationA0.EmitToArray() Dim bytesB0 = compilationB0.EmitToArray() Dim mdA0 = ModuleMetadata.CreateFromImage(bytesA0) Dim mdB0 = ModuleMetadata.CreateFromImage(bytesB0) Dim generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider) Dim generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider) Dim mA1 = compilationA1.GetMember(Of MethodSymbol)("A.M") Dim mX1 = compilationA1.GetMember(Of TypeSymbol)("X") Dim allAddedSymbols = New ISymbol() {mA1, mX1} Dim diffA1 = compilationA1.EmitDifference( generationA0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Insert, Nothing, mA1), New SemanticEdit(SemanticEditKind.Insert, Nothing, mX1)), allAddedSymbols) diffA1.EmitResult.Diagnostics.Verify() Dim diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, compilationB0.GetMember(Of MethodSymbol)("B.F"), compilationB1.GetMember(Of MethodSymbol)("B.F")), New SemanticEdit(SemanticEditKind.Insert, Nothing, compilationB1.GetMember(Of TypeSymbol)("Y"))), allAddedSymbols) diffB1.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(8, 14), Diagnostic(ERRID.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(3, 16)) End Sub <Fact> Public Sub ReferenceToMemberAddedToAnotherAssembly2() Dim sourceA = " Public Class A Public Sub M() End Sub End Class" Dim sourceB0 = " Public Class B Public Shared Sub F() Dim a = New A() End Sub End Class" Dim sourceB1 = " Public Class B Public Shared Sub F() Dim a = New A() a.M() End Sub End Class" Dim sourceB2 = " Public Class B Public Shared Sub F() Dim a = New A() End Sub End Class" Dim compilationA = CreateCompilationWithMscorlib40({sourceA}, options:=TestOptions.DebugDll, assemblyName:="AssemblyA") Dim aRef = compilationA.ToMetadataReference() Dim compilationB0 = CreateCompilationWithMscorlib40({sourceB0}, {aRef}, options:=TestOptions.DebugDll, assemblyName:="AssemblyB") Dim compilationB1 = compilationB0.WithSource(sourceB1) Dim compilationB2 = compilationB1.WithSource(sourceB2) Dim testDataB0 = New CompilationTestData() Dim bytesB0 = compilationB0.EmitToArray(testData:=testDataB0) Dim mdB0 = ModuleMetadata.CreateFromImage(bytesB0) Dim generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider()) Dim f0 = compilationB0.GetMember(Of MethodSymbol)("B.F") Dim f1 = compilationB1.GetMember(Of MethodSymbol)("B.F") Dim f2 = compilationB2.GetMember(Of MethodSymbol)("B.F") Dim diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables:=True))) diffB1.VerifyIL("B.F", " { // Code size 15 (0xf) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: callvirt ""Sub A.M()"" IL_000d: nop IL_000e: ret } ") Dim diffB2 = compilationB2.EmitDifference( diffB1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables:=True))) diffB2.VerifyIL("B.F", " { // Code size 8 (0x8) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: stloc.0 IL_0007: ret } ") End Sub <Fact> Public Sub ForStatement() Dim source0 = MarkedSource(" Imports System Class C Sub F() <N:0><N:1>For a = G(0) To G(1) Step G(2)</N:1> Console.WriteLine(1) Next</N:0> End Sub Function G(a As Integer) As Integer Return 10 End Function End Class ") Dim source1 = MarkedSource(" Imports System Class C Sub F() <N:0><N:1>For a = G(0) To G(1) Step G(2)</N:1> Console.WriteLine(2) Next</N:0> End Sub Function G(a As Integer) As Integer Return 10 End Function End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, {MsvbRef}, ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) Dim md1 = diff1.GetMetadata() Dim reader1 = md1.Reader v0.VerifyIL("C.F", " { // Code size 55 (0x37) .maxstack 3 .locals init (Integer V_0, Integer V_1, Integer V_2, Integer V_3) //a IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: call ""Function C.G(Integer) As Integer"" IL_0008: stloc.0 IL_0009: ldarg.0 IL_000a: ldc.i4.1 IL_000b: call ""Function C.G(Integer) As Integer"" IL_0010: stloc.1 IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: call ""Function C.G(Integer) As Integer"" IL_0018: stloc.2 IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0028 IL_001d: ldc.i4.1 IL_001e: call ""Sub System.Console.WriteLine(Integer)"" IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.2 IL_0026: add.ovf IL_0027: stloc.3 IL_0028: ldloc.2 IL_0029: ldc.i4.s 31 IL_002b: shr IL_002c: ldloc.3 IL_002d: xor IL_002e: ldloc.2 IL_002f: ldc.i4.s 31 IL_0031: shr IL_0032: ldloc.1 IL_0033: xor IL_0034: ble.s IL_001d IL_0036: ret } ") ' Note that all variables are mapped to their previous slots diff1.VerifyIL("C.F", " { // Code size 55 (0x37) .maxstack 3 .locals init (Integer V_0, Integer V_1, Integer V_2, Integer V_3) //a IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: call ""Function C.G(Integer) As Integer"" IL_0008: stloc.0 IL_0009: ldarg.0 IL_000a: ldc.i4.1 IL_000b: call ""Function C.G(Integer) As Integer"" IL_0010: stloc.1 IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: call ""Function C.G(Integer) As Integer"" IL_0018: stloc.2 IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0028 IL_001d: ldc.i4.2 IL_001e: call ""Sub System.Console.WriteLine(Integer)"" IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.2 IL_0026: add.ovf IL_0027: stloc.3 IL_0028: ldloc.2 IL_0029: ldc.i4.s 31 IL_002b: shr IL_002c: ldloc.3 IL_002d: xor IL_002e: ldloc.2 IL_002f: ldc.i4.s 31 IL_0031: shr IL_0032: ldloc.1 IL_0033: xor IL_0034: ble.s IL_001d IL_0036: ret } ") End Sub <Fact> Public Sub ForStatement_LateBound() Dim source0 = MarkedSource(" Option Strict On Public Class C Public Shared Sub F() Dim <N:0>a</N:0> As Object = 0 Dim <N:1>b</N:1> As Object = 0 Dim <N:2>c</N:2> As Object = 0 Dim <N:3>d</N:3> As Object = 0 <N:4>For a = b To c Step d System.Console.Write(a) Next</N:4> End Sub End Class") Dim source1 = MarkedSource(" Option Strict On Public Class C Public Shared Sub F() Dim <N:0>a</N:0> As Object = 0 Dim <N:1>b</N:1> As Object = 0 Dim <N:2>c</N:2> As Object = 0 Dim <N:3>d</N:3> As Object = 0 <N:4>For a = b To c Step d System.Console.WriteLine(a) Next</N:4> End Sub End Class") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, {MsvbRef}, ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) Dim md1 = diff1.GetMetadata() Dim reader1 = md1.Reader v0.VerifyIL("C.F", " { // Code size 77 (0x4d) .maxstack 6 .locals init (Object V_0, //a Object V_1, //b Object V_2, //c Object V_3, //d Object V_4, Boolean V_5, Boolean V_6) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""Integer"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: box ""Integer"" IL_000e: stloc.1 IL_000f: ldc.i4.0 IL_0010: box ""Integer"" IL_0015: stloc.2 IL_0016: ldc.i4.0 IL_0017: box ""Integer"" IL_001c: stloc.3 IL_001d: ldloc.0 IL_001e: ldloc.1 IL_001f: ldloc.2 IL_0020: ldloc.3 IL_0021: ldloca.s V_4 IL_0023: ldloca.s V_0 IL_0025: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Object, Object, Object, Object, ByRef Object, ByRef Object) As Boolean"" IL_002a: stloc.s V_5 IL_002c: ldloc.s V_5 IL_002e: brfalse.s IL_004c IL_0030: ldloc.0 IL_0031: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_0036: call ""Sub System.Console.Write(Object)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldloc.s V_4 IL_003f: ldloca.s V_0 IL_0041: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Object, Object, ByRef Object) As Boolean"" IL_0046: stloc.s V_6 IL_0048: ldloc.s V_6 IL_004a: brtrue.s IL_0030 IL_004c: ret } ") ' Note that all variables are mapped to their previous slots diff1.VerifyIL("C.F", " { // Code size 77 (0x4d) .maxstack 6 .locals init (Object V_0, //a Object V_1, //b Object V_2, //c Object V_3, //d Object V_4, Boolean V_5, Boolean V_6) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""Integer"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: box ""Integer"" IL_000e: stloc.1 IL_000f: ldc.i4.0 IL_0010: box ""Integer"" IL_0015: stloc.2 IL_0016: ldc.i4.0 IL_0017: box ""Integer"" IL_001c: stloc.3 IL_001d: ldloc.0 IL_001e: ldloc.1 IL_001f: ldloc.2 IL_0020: ldloc.3 IL_0021: ldloca.s V_4 IL_0023: ldloca.s V_0 IL_0025: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Object, Object, Object, Object, ByRef Object, ByRef Object) As Boolean"" IL_002a: stloc.s V_5 IL_002c: ldloc.s V_5 IL_002e: brfalse.s IL_004c IL_0030: ldloc.0 IL_0031: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_0036: call ""Sub System.Console.WriteLine(Object)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldloc.s V_4 IL_003f: ldloca.s V_0 IL_0041: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Object, Object, ByRef Object) As Boolean"" IL_0046: stloc.s V_6 IL_0048: ldloc.s V_6 IL_004a: brtrue.s IL_0030 IL_004c: ret } ") End Sub <Fact> Public Sub AddImports_AmbiguousCode() Dim source0 = MarkedSource(" Imports System.Threading Class C Shared Sub E() Dim t = New Timer(Sub(s) System.Console.WriteLine(s)) End Sub End Class ") Dim source1 = MarkedSource(" Imports System.Threading Imports System.Timers Class C Shared Sub E() Dim t = New Timer(Sub(s) System.Console.WriteLine(s)) End Sub Shared Sub G() System.Console.WriteLine(new TimersDescriptionAttribute("""")) End Sub End Class ") Dim compilation0 = CreateCompilation(source0.Tree, targetFramework:=TargetFramework.NetStandard20, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim e0 = compilation0.GetMember(Of MethodSymbol)("C.E") Dim e1 = compilation1.GetMember(Of MethodSymbol)("C.E") Dim g1 = compilation1.GetMember(Of MethodSymbol)("C.G") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) ' Pretend there was an update to C.E to ensure we haven't invalidated the test Dim diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diffError.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_AmbiguousInImports2, "Timer").WithArguments("Timer", "System.Threading, System.Timers").WithLocation(7, 21)) Dim diff = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, g1))) diff.EmitResult.Diagnostics.Verify() diff.VerifyIL("C.G", " { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldstr """" IL_0006: newobj ""Sub System.Timers.TimersDescriptionAttribute..ctor(String)"" IL_000b: call ""Sub System.Console.WriteLine(Object)"" IL_0010: nop IL_0011: ret }") End Sub End Class End Namespace
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/CodeStyle/VisualBasic/Analyzers/xlf/VBCodeStyleResources.ja.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="ja" original="../VBCodeStyleResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">別の値が追加されたら、この値を削除します。</target> <note>https://github.com/Microsoft/msbuild/issues/1661</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="ja" original="../VBCodeStyleResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">別の値が追加されたら、この値を削除します。</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/CSharp/Portable/UseExpressionBody/UseExpressionBodyCodeRefactoringProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.UseExpressionBody), Shared] internal class UseExpressionBodyCodeRefactoringProvider : CodeRefactoringProvider { private static readonly ImmutableArray<UseExpressionBodyHelper> _helpers = UseExpressionBodyHelper.Helpers; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseExpressionBodyCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (textSpan.Length > 0) return; var position = textSpan.Start; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = root.FindToken(position).Parent!; var containingLambda = node.FirstAncestorOrSelf<LambdaExpressionSyntax>(); if (containingLambda != null && node.AncestorsAndSelf().Contains(containingLambda.Body)) { // don't offer inside a lambda. Lambdas can be quite large, and it will be very noisy // inside the body of one to be offering to use a block/expression body for the containing // class member. return; } var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); foreach (var helper in _helpers) { var declaration = TryGetDeclaration(helper, text, node, position); if (declaration == null) continue; var succeeded = TryComputeRefactoring(context, root, declaration, optionSet, helper); if (succeeded) return; } } private static SyntaxNode? TryGetDeclaration( UseExpressionBodyHelper helper, SourceText text, SyntaxNode node, int position) { var declaration = GetDeclaration(node, helper); if (declaration == null) return null; if (position < declaration.SpanStart) { // The user is allowed to be before the starting point of this node, as long as // they're only between the start of the node and the start of the same line the // node starts on. This prevents unnecessarily showing this feature in areas like // the comment of a method. if (!text.AreOnSameLine(position, declaration.SpanStart)) return null; } return declaration; } private static bool TryComputeRefactoring( CodeRefactoringContext context, SyntaxNode root, SyntaxNode declaration, OptionSet optionSet, UseExpressionBodyHelper helper) { var document = context.Document; var succeeded = false; if (helper.CanOfferUseExpressionBody(optionSet, declaration, forAnalyzer: false)) { context.RegisterRefactoring(new MyCodeAction( helper.UseExpressionBodyTitle.ToString(), c => UpdateDocumentAsync( document, root, declaration, helper, useExpressionBody: true, cancellationToken: c)), declaration.Span); succeeded = true; } var (canOffer, _) = helper.CanOfferUseBlockBody(optionSet, declaration, forAnalyzer: false); if (canOffer) { context.RegisterRefactoring( new MyCodeAction( helper.UseBlockBodyTitle.ToString(), c => UpdateDocumentAsync( document, root, declaration, helper, useExpressionBody: false, cancellationToken: c)), declaration.Span); succeeded = true; } return succeeded; } private static SyntaxNode? GetDeclaration(SyntaxNode node, UseExpressionBodyHelper helper) { for (var current = node; current != null; current = current.Parent) { if (helper.SyntaxKinds.Contains(current.Kind())) return current; } return null; } private static async Task<Document> UpdateDocumentAsync( Document document, SyntaxNode root, SyntaxNode declaration, UseExpressionBodyHelper helper, bool useExpressionBody, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var updatedDeclaration = helper.Update(semanticModel, declaration, useExpressionBody); var parent = declaration is AccessorDeclarationSyntax ? declaration.Parent : declaration; RoslynDebug.Assert(parent is object); var updatedParent = parent.ReplaceNode(declaration, updatedDeclaration) .WithAdditionalAnnotations(Formatter.Annotation); var newRoot = root.ReplaceNode(parent, updatedParent); return document.WithSyntaxRoot(newRoot); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.UseExpressionBody), Shared] internal class UseExpressionBodyCodeRefactoringProvider : CodeRefactoringProvider { private static readonly ImmutableArray<UseExpressionBodyHelper> _helpers = UseExpressionBodyHelper.Helpers; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseExpressionBodyCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (textSpan.Length > 0) return; var position = textSpan.Start; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = root.FindToken(position).Parent!; var containingLambda = node.FirstAncestorOrSelf<LambdaExpressionSyntax>(); if (containingLambda != null && node.AncestorsAndSelf().Contains(containingLambda.Body)) { // don't offer inside a lambda. Lambdas can be quite large, and it will be very noisy // inside the body of one to be offering to use a block/expression body for the containing // class member. return; } var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); foreach (var helper in _helpers) { var declaration = TryGetDeclaration(helper, text, node, position); if (declaration == null) continue; var succeeded = TryComputeRefactoring(context, root, declaration, optionSet, helper); if (succeeded) return; } } private static SyntaxNode? TryGetDeclaration( UseExpressionBodyHelper helper, SourceText text, SyntaxNode node, int position) { var declaration = GetDeclaration(node, helper); if (declaration == null) return null; if (position < declaration.SpanStart) { // The user is allowed to be before the starting point of this node, as long as // they're only between the start of the node and the start of the same line the // node starts on. This prevents unnecessarily showing this feature in areas like // the comment of a method. if (!text.AreOnSameLine(position, declaration.SpanStart)) return null; } return declaration; } private static bool TryComputeRefactoring( CodeRefactoringContext context, SyntaxNode root, SyntaxNode declaration, OptionSet optionSet, UseExpressionBodyHelper helper) { var document = context.Document; var succeeded = false; if (helper.CanOfferUseExpressionBody(optionSet, declaration, forAnalyzer: false)) { context.RegisterRefactoring(new MyCodeAction( helper.UseExpressionBodyTitle.ToString(), c => UpdateDocumentAsync( document, root, declaration, helper, useExpressionBody: true, cancellationToken: c)), declaration.Span); succeeded = true; } var (canOffer, _) = helper.CanOfferUseBlockBody(optionSet, declaration, forAnalyzer: false); if (canOffer) { context.RegisterRefactoring( new MyCodeAction( helper.UseBlockBodyTitle.ToString(), c => UpdateDocumentAsync( document, root, declaration, helper, useExpressionBody: false, cancellationToken: c)), declaration.Span); succeeded = true; } return succeeded; } private static SyntaxNode? GetDeclaration(SyntaxNode node, UseExpressionBodyHelper helper) { for (var current = node; current != null; current = current.Parent) { if (helper.SyntaxKinds.Contains(current.Kind())) return current; } return null; } private static async Task<Document> UpdateDocumentAsync( Document document, SyntaxNode root, SyntaxNode declaration, UseExpressionBodyHelper helper, bool useExpressionBody, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var updatedDeclaration = helper.Update(semanticModel, declaration, useExpressionBody); var parent = declaration is AccessorDeclarationSyntax ? declaration.Parent : declaration; RoslynDebug.Assert(parent is object); var updatedParent = parent.ReplaceNode(declaration, updatedDeclaration) .WithAdditionalAnnotations(Formatter.Annotation); var newRoot = root.ReplaceNode(parent, updatedParent); return document.WithSyntaxRoot(newRoot); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Server/VBCSCompiler/ClientConnectionHandler.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.Diagnostics; using System.IO; using System.IO.Pipes; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; namespace Microsoft.CodeAnalysis.CompilerServer { /// <summary> /// This class is responsible for processing a request from a client of the compiler server. /// </summary> internal sealed class ClientConnectionHandler { internal ICompilerServerHost CompilerServerHost { get; } internal ICompilerServerLogger Logger => CompilerServerHost.Logger; internal ClientConnectionHandler(ICompilerServerHost compilerServerHost) { CompilerServerHost = compilerServerHost; } /// <summary> /// Handles a client connection. The returned task here will never fail. Instead all exceptions will be wrapped /// in a <see cref="CompletionReason.RequestError"/> /// </summary> internal async Task<CompletionData> ProcessAsync( Task<IClientConnection> clientConnectionTask, bool allowCompilationRequests = true, CancellationToken cancellationToken = default) { try { return await ProcessCore().ConfigureAwait(false); } catch (Exception ex) { Logger.LogException(ex, $"Error processing request for client"); return CompletionData.RequestError; } async Task<CompletionData> ProcessCore() { using var clientConnection = await clientConnectionTask.ConfigureAwait(false); var request = await clientConnection.ReadBuildRequestAsync(cancellationToken).ConfigureAwait(false); Logger.Log($"Received request {request.RequestId} of type {request.GetType()}"); if (!string.Equals(request.CompilerHash, BuildProtocolConstants.GetCommitHash(), StringComparison.OrdinalIgnoreCase)) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new IncorrectHashBuildResponse(), CompletionData.RequestError, cancellationToken).ConfigureAwait(false); } if (request.Arguments.Count == 1 && request.Arguments[0].ArgumentId == BuildProtocolConstants.ArgumentId.Shutdown) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new ShutdownBuildResponse(Process.GetCurrentProcess().Id), new CompletionData(CompletionReason.RequestCompleted, shutdownRequested: true), cancellationToken).ConfigureAwait(false); } if (!allowCompilationRequests) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new RejectedBuildResponse("Compilation not allowed at this time"), CompletionData.RequestCompleted, cancellationToken).ConfigureAwait(false); } if (!Environment.Is64BitProcess && !MemoryHelper.IsMemoryAvailable(Logger)) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new RejectedBuildResponse("Not enough resources to accept connection"), CompletionData.RequestError, cancellationToken).ConfigureAwait(false); } return await ProcessCompilationRequestAsync(clientConnection, request, cancellationToken).ConfigureAwait(false); } } private async Task<CompletionData> WriteBuildResponseAsync(IClientConnection clientConnection, Guid requestId, BuildResponse response, CompletionData completionData, CancellationToken cancellationToken) { var message = response switch { RejectedBuildResponse r => $"Writing {r.Type} response '{r.Reason}' for {requestId}", _ => $"Writing {response.Type} response for {requestId}" }; Logger.Log(message); await clientConnection.WriteBuildResponseAsync(response, cancellationToken).ConfigureAwait(false); return completionData; } private async Task<CompletionData> ProcessCompilationRequestAsync(IClientConnection clientConnection, BuildRequest request, CancellationToken cancellationToken) { // Need to wait for the compilation and client disconnection in parallel. If the client // suddenly disconnects we need to cancel the compilation that is occurring. It could be the // client hit Ctrl-C due to a run away analyzer. var buildCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var compilationTask = ProcessCompilationRequestCore(CompilerServerHost, request, buildCancellationTokenSource.Token); await Task.WhenAny(compilationTask, clientConnection.DisconnectTask).ConfigureAwait(false); try { if (compilationTask.IsCompleted) { BuildResponse response; CompletionData completionData; try { response = await compilationTask.ConfigureAwait(false); completionData = response switch { // Once there is an analyzer inconsistency the assembly load space is polluted. The // request is an error. AnalyzerInconsistencyBuildResponse _ => CompletionData.RequestError, _ => new CompletionData(CompletionReason.RequestCompleted, newKeepAlive: CheckForNewKeepAlive(request)) }; } catch (Exception ex) { // The compilation task should never throw. If it does we need to assume that the compiler is // in a bad state and need to issue a RequestError Logger.LogException(ex, $"Exception running compilation for {request.RequestId}"); response = new RejectedBuildResponse($"Exception during compilation: {ex.Message}"); completionData = CompletionData.RequestError; } return await WriteBuildResponseAsync( clientConnection, request.RequestId, response, completionData, cancellationToken).ConfigureAwait(false); } else { return CompletionData.RequestError; } } finally { buildCancellationTokenSource.Cancel(); } static Task<BuildResponse> ProcessCompilationRequestCore(ICompilerServerHost compilerServerHost, BuildRequest buildRequest, CancellationToken cancellationToken) { Func<BuildResponse> func = () => { var request = BuildProtocolUtil.GetRunRequest(buildRequest); var response = compilerServerHost.RunCompilation(request, cancellationToken); return response; }; var task = new Task<BuildResponse>(func, cancellationToken, TaskCreationOptions.LongRunning); task.Start(); return task; } } /// <summary> /// Check the request arguments for a new keep alive time. If one is present, /// set the server timer to the new time. /// </summary> private static TimeSpan? CheckForNewKeepAlive(BuildRequest request) { TimeSpan? timeout = null; foreach (var arg in request.Arguments) { if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.KeepAlive) { int result; // If the value is not a valid integer for any reason, // ignore it and continue with the current timeout. The client // is responsible for validating the argument. if (int.TryParse(arg.Value, out result)) { // Keep alive times are specified in seconds timeout = TimeSpan.FromSeconds(result); } } } return timeout; } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.IO; using System.IO.Pipes; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; namespace Microsoft.CodeAnalysis.CompilerServer { /// <summary> /// This class is responsible for processing a request from a client of the compiler server. /// </summary> internal sealed class ClientConnectionHandler { internal ICompilerServerHost CompilerServerHost { get; } internal ICompilerServerLogger Logger => CompilerServerHost.Logger; internal ClientConnectionHandler(ICompilerServerHost compilerServerHost) { CompilerServerHost = compilerServerHost; } /// <summary> /// Handles a client connection. The returned task here will never fail. Instead all exceptions will be wrapped /// in a <see cref="CompletionReason.RequestError"/> /// </summary> internal async Task<CompletionData> ProcessAsync( Task<IClientConnection> clientConnectionTask, bool allowCompilationRequests = true, CancellationToken cancellationToken = default) { try { return await ProcessCore().ConfigureAwait(false); } catch (Exception ex) { Logger.LogException(ex, $"Error processing request for client"); return CompletionData.RequestError; } async Task<CompletionData> ProcessCore() { using var clientConnection = await clientConnectionTask.ConfigureAwait(false); var request = await clientConnection.ReadBuildRequestAsync(cancellationToken).ConfigureAwait(false); Logger.Log($"Received request {request.RequestId} of type {request.GetType()}"); if (!string.Equals(request.CompilerHash, BuildProtocolConstants.GetCommitHash(), StringComparison.OrdinalIgnoreCase)) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new IncorrectHashBuildResponse(), CompletionData.RequestError, cancellationToken).ConfigureAwait(false); } if (request.Arguments.Count == 1 && request.Arguments[0].ArgumentId == BuildProtocolConstants.ArgumentId.Shutdown) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new ShutdownBuildResponse(Process.GetCurrentProcess().Id), new CompletionData(CompletionReason.RequestCompleted, shutdownRequested: true), cancellationToken).ConfigureAwait(false); } if (!allowCompilationRequests) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new RejectedBuildResponse("Compilation not allowed at this time"), CompletionData.RequestCompleted, cancellationToken).ConfigureAwait(false); } if (!Environment.Is64BitProcess && !MemoryHelper.IsMemoryAvailable(Logger)) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new RejectedBuildResponse("Not enough resources to accept connection"), CompletionData.RequestError, cancellationToken).ConfigureAwait(false); } return await ProcessCompilationRequestAsync(clientConnection, request, cancellationToken).ConfigureAwait(false); } } private async Task<CompletionData> WriteBuildResponseAsync(IClientConnection clientConnection, Guid requestId, BuildResponse response, CompletionData completionData, CancellationToken cancellationToken) { var message = response switch { RejectedBuildResponse r => $"Writing {r.Type} response '{r.Reason}' for {requestId}", _ => $"Writing {response.Type} response for {requestId}" }; Logger.Log(message); await clientConnection.WriteBuildResponseAsync(response, cancellationToken).ConfigureAwait(false); return completionData; } private async Task<CompletionData> ProcessCompilationRequestAsync(IClientConnection clientConnection, BuildRequest request, CancellationToken cancellationToken) { // Need to wait for the compilation and client disconnection in parallel. If the client // suddenly disconnects we need to cancel the compilation that is occurring. It could be the // client hit Ctrl-C due to a run away analyzer. var buildCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var compilationTask = ProcessCompilationRequestCore(CompilerServerHost, request, buildCancellationTokenSource.Token); await Task.WhenAny(compilationTask, clientConnection.DisconnectTask).ConfigureAwait(false); try { if (compilationTask.IsCompleted) { BuildResponse response; CompletionData completionData; try { response = await compilationTask.ConfigureAwait(false); completionData = response switch { // Once there is an analyzer inconsistency the assembly load space is polluted. The // request is an error. AnalyzerInconsistencyBuildResponse _ => CompletionData.RequestError, _ => new CompletionData(CompletionReason.RequestCompleted, newKeepAlive: CheckForNewKeepAlive(request)) }; } catch (Exception ex) { // The compilation task should never throw. If it does we need to assume that the compiler is // in a bad state and need to issue a RequestError Logger.LogException(ex, $"Exception running compilation for {request.RequestId}"); response = new RejectedBuildResponse($"Exception during compilation: {ex.Message}"); completionData = CompletionData.RequestError; } return await WriteBuildResponseAsync( clientConnection, request.RequestId, response, completionData, cancellationToken).ConfigureAwait(false); } else { return CompletionData.RequestError; } } finally { buildCancellationTokenSource.Cancel(); } static Task<BuildResponse> ProcessCompilationRequestCore(ICompilerServerHost compilerServerHost, BuildRequest buildRequest, CancellationToken cancellationToken) { Func<BuildResponse> func = () => { var request = BuildProtocolUtil.GetRunRequest(buildRequest); var response = compilerServerHost.RunCompilation(request, cancellationToken); return response; }; var task = new Task<BuildResponse>(func, cancellationToken, TaskCreationOptions.LongRunning); task.Start(); return task; } } /// <summary> /// Check the request arguments for a new keep alive time. If one is present, /// set the server timer to the new time. /// </summary> private static TimeSpan? CheckForNewKeepAlive(BuildRequest request) { TimeSpan? timeout = null; foreach (var arg in request.Arguments) { if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.KeepAlive) { int result; // If the value is not a valid integer for any reason, // ignore it and continue with the current timeout. The client // is responsible for validating the argument. if (int.TryParse(arg.Value, out result)) { // Keep alive times are specified in seconds timeout = TimeSpan.FromSeconds(result); } } } return timeout; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Test/Syntax/Parsing/PatternParsingTests.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.Text; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.Patterns)] public class PatternParsingTests : ParsingTests { private new void UsingStatement(string text, params DiagnosticDescription[] expectedErrors) { UsingStatement(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8), expectedErrors); } public PatternParsingTests(ITestOutputHelper output) : base(output) { } [Fact] public void CasePatternVersusFeatureFlag() { var test = @" class C { public static void Main(string[] args) { switch ((int) args[0][0]) { case 1: case 2 when args.Length == 2: case 1<<2: case string s: default: break; } bool b = args[0] is string s; } } "; CreateCompilation(test, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics( // (9,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case 2 when args.Length == 2: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case 2 when args.Length == 2:").WithArguments("pattern matching", "7.0").WithLocation(9, 13), // (11,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case string s: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case string s:").WithArguments("pattern matching", "7.0").WithLocation(11, 13), // (15,18): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // bool b = args[0] is string s; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "args[0] is string s").WithArguments("pattern matching", "7.0").WithLocation(15, 18), // (11,18): error CS8121: An expression of type 'int' cannot be handled by a pattern of type 'string'. // case string s: Diagnostic(ErrorCode.ERR_PatternWrongType, "string").WithArguments("int", "string").WithLocation(11, 18), // (11,25): error CS0136: A local or parameter named 's' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case string s: Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "s").WithArguments("s").WithLocation(11, 25) ); } [Fact] public void ThrowExpression_Good() { var test = @"using System; class C { public static void Sample(bool b, string s) { void NeverReturnsFunction() => throw new NullReferenceException(); int x = b ? throw new NullReferenceException() : 1; x = b ? 2 : throw new NullReferenceException(); s = s ?? throw new NullReferenceException(); NeverReturnsFunction(); throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; } public static void NeverReturns() => throw new NullReferenceException(); }"; CreateCompilation(test).VerifyDiagnostics(); CreateCompilation(test, parseOptions: TestOptions.Regular6).VerifyDiagnostics( // (6,14): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // void NeverReturnsFunction() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "NeverReturnsFunction").WithArguments("local functions", "7.0").WithLocation(6, 14), // (6,40): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // void NeverReturnsFunction() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(6, 40), // (7,21): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // int x = b ? throw new NullReferenceException() : 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(7, 21), // (8,21): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // x = b ? 2 : throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(8, 21), // (9,18): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // s = s ?? throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(9, 18), // (11,47): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException() ?? throw null").WithArguments("throw expression", "7.0").WithLocation(11, 47), // (11,85): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw null").WithArguments("throw expression", "7.0").WithLocation(11, 85), // (13,42): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // public static void NeverReturns() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(13, 42) ); } [Fact] public void ThrowExpression_Bad() { var test = @"using System; class C { public static void Sample(bool b, string s) { // throw expression at wrong precedence s = s + throw new NullReferenceException(); if (b || throw new NullReferenceException()) { } // throw expression where not permitted var z = from x in throw new NullReferenceException() select x; M(throw new NullReferenceException()); throw throw null; (int, int) w = (1, throw null); return throw null; } static void M(string s) {} }"; CreateCompilationWithMscorlib46(test).VerifyDiagnostics( // (7,17): error CS1525: Invalid expression term 'throw' // s = s + throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw new NullReferenceException()").WithArguments("throw").WithLocation(7, 17), // (8,18): error CS1525: Invalid expression term 'throw' // if (b || throw new NullReferenceException()) { } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw new NullReferenceException()").WithArguments("throw").WithLocation(8, 18), // (11,27): error CS8115: A throw expression is not allowed in this context. // var z = from x in throw new NullReferenceException() select x; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(11, 27), // (12,11): error CS8115: A throw expression is not allowed in this context. // M(throw new NullReferenceException()); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(12, 11), // (13,15): error CS8115: A throw expression is not allowed in this context. // throw throw null; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(13, 15), // (14,9): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int, int)").WithArguments("System.ValueTuple`2").WithLocation(14, 9), // (14,28): error CS8115: A throw expression is not allowed in this context. // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(14, 28), // (14,24): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, throw null)").WithArguments("System.ValueTuple`2").WithLocation(14, 24), // (15,16): error CS8115: A throw expression is not allowed in this context. // return throw null; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(15, 16), // (14,9): warning CS0162: Unreachable code detected // (int, int) w = (1, throw null); Diagnostic(ErrorCode.WRN_UnreachableCode, "(").WithLocation(14, 9) ); } [Fact] public void ThrowExpression() { UsingTree(@" class C { int x = y ?? throw null; }", options: TestOptions.Regular); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.ThrowExpression); { N(SyntaxKind.ThrowKeyword); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_1() { UsingNode(SyntaxFactory.ParseExpression("A is B < C, D > [ ]")); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_2() { UsingNode(SyntaxFactory.ParseExpression("A < B > C")); N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_3() { SyntaxFactory.ParseExpression("e is A<B> && e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> || e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> ^ e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> | e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> & e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B>[]").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("new { X = e is A<B> }").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B>").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("(item is Dictionary<string, object>[])").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A is B < C, D > [ ]").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A is B < C, D > [ ] E").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A < B > C").GetDiagnostics().Verify(); } [Fact] public void QueryContextualPatternVariable_01() { SyntaxFactory.ParseExpression("from s in a where s is string where s.Length > 1 select s").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("M(out int? x)").GetDiagnostics().Verify(); } [Fact] public void TypeDisambiguation_01() { UsingStatement(@" var r = from s in a where s is X<T> // should disambiguate as a type here where M(s) select s as X<T>;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierToken, "s"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.QueryBody); { N(SyntaxKind.WhereClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } } N(SyntaxKind.WhereClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SelectClause); { N(SyntaxKind.SelectKeyword); N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypeDisambiguation_02() { UsingStatement(@" var r = a is X<T> // should disambiguate as a type here is bool;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.IsKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypeDisambiguation_03() { UsingStatement(@" var r = a is X<T> // should disambiguate as a type here > Z;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence00() { UsingExpression("A is B << C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence01() { UsingExpression("A is 1 << 2"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence02() { UsingExpression("A is null < B"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence02b() { UsingExpression("A is B < C"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence03() { UsingExpression("A is null == B"); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence04() { UsingExpression("A is null & B"); N(SyntaxKind.BitwiseAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.AmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence05() { UsingExpression("A is null && B"); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence05b() { UsingExpression("A is null || B"); N(SyntaxKind.LogicalOrExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.BarBarToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence06() { UsingStatement(@"switch (e) { case 1 << 2: case B << C: case null < B: case null == B: case null & B: case null && B: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.BitwiseAndExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.AmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(21515, "https://github.com/dotnet/roslyn/issues/21515")] public void PatternExpressionPrecedence07() { // This should actually be error-free. UsingStatement(@"switch (array) { case KeyValuePair<string, DateTime>[] pairs1: case KeyValuePair<String, DateTime>[] pairs2: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "array"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "KeyValuePair"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "DateTime"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "pairs1"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "KeyValuePair"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "String"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "DateTime"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "pairs2"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_01() { UsingExpression("A is B***", // (1,10): error CS1733: Expected expression // A is B*** Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 10) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_01b() { UsingExpression("A is B*** C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_02() { UsingExpression("A is B***[]"); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_03() { UsingExpression("A is B***[] C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_04() { UsingExpression("(B*** C, D)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_04b() { UsingExpression("(B*** C)"); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_05() { UsingExpression("(B***[] C, D)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_06() { UsingExpression("(D, B*** C)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_07() { UsingExpression("(D, B***[] C)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_08() { UsingStatement("switch (e) { case B*** C: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_09() { UsingStatement("switch (e) { case B***[] C: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_01() { // This should actually be error-free, because `nameof` might be a type. UsingStatement(@"switch (e) { case nameof n: ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_02() { // This should actually be error-free; a constant pattern with nameof(n) as the constant. UsingStatement(@"switch (e) { case nameof(n): ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_03() { // This should actually be error-free; a constant pattern with nameof(n) as the constant. UsingStatement(@"switch (e) { case nameof(n) when true: ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_01() { UsingStatement(@"switch (e) { case (((3))): ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_02() { UsingStatement(@"switch (e) { case (((3))) when true: ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_03() { var expect = new[] { // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (x: ((3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(x: ((3)))").WithArguments("recursive patterns", "8.0").WithLocation(1, 19) }; UsingStatement(@"switch (e) { case (x: ((3))): ; }", TestOptions.RegularWithoutRecursivePatterns, expect); checkNodes(); UsingStatement(@"switch (e) { case (x: ((3))): ; }", TestOptions.Regular8); checkNodes(); void checkNodes() { N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact] public void ParenthesizedExpression_04() { UsingStatement(@"switch (e) { case (((x: 3))): ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8370: Feature 'parenthesized pattern' is not available in C# 7.3. Please use language version 9.0 or greater. // switch (e) { case (((x: 3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(((x: 3)))").WithArguments("parenthesized pattern", "9.0").WithLocation(1, 19), // (1,20): error CS8370: Feature 'parenthesized pattern' is not available in C# 7.3. Please use language version 9.0 or greater. // switch (e) { case (((x: 3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "((x: 3))").WithArguments("parenthesized pattern", "9.0").WithLocation(1, 20) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void RecursivePattern_01() { UsingStatement(@"switch (e) { case T(X: 3, Y: 4){L: 5} p: ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case T(X: 3, Y: 4){L: 5} p: ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T(X: 3, Y: 4){L: 5} p").WithArguments("recursive patterns", "8.0").WithLocation(1, 19) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "L"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "p"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_06() { UsingStatement(@"switch (e) { case (: ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(: ").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,20): error CS1001: Identifier expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_IdentifierExpected, ":").WithLocation(1, 20), // (1,22): error CS1026: ) expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 22), // (1,22): error CS1003: Syntax error, ':' expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(1, 22) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_07() { UsingStatement(@"switch (e) { case (", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case ( Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,20): error CS1026: ) expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(1, 20), // (1,20): error CS1003: Syntax error, ':' expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 20), // (1,20): error CS1513: } expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 20) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } } M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_07() { UsingStatement(@"switch (e) { case (): }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (): } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "()").WithArguments("recursive patterns", "8.0").WithLocation(1, 19)); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_08() { UsingStatement(@"switch (e) { case", // (1,18): error CS1733: Expected expression // switch (e) { case Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 18), // (1,18): error CS1003: Syntax error, ':' expected // switch (e) { case Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 18), // (1,18): error CS1513: } expected // switch (e) { case Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 18) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); } } M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_05() { UsingStatement(@"switch (e) { case (x: ): ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (x: ): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(x: )").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,23): error CS8504: Pattern missing // switch (e) { case (x: ): ; } Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 23) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void EmptySwitchExpression() { UsingExpression("1 switch {}", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch {}").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression01() { UsingExpression("1 switch {a => b, c => d}", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch {a => b, c => d} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch {a => b, c => d}").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression02() { UsingExpression("1 switch { a?b:c => d }", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { a?b:c => d }").WithArguments("recursive patterns", "8.0").WithLocation(1, 1), // (1,13): error CS1003: Syntax error, '=>' expected // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments("=>", "?").WithLocation(1, 13), // (1,13): error CS1525: Invalid expression term '?' // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "?").WithArguments("?").WithLocation(1, 13) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.ConditionalExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression03() { UsingExpression("1 switch { (a, b, c) => d }", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch { (a, b, c) => d } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { (a, b, c) => d }").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenRecursivePattern01() { // This put the parser into an infinite loop at one time. The precise diagnostics and nodes // are not as important as the fact that it terminates. UsingStatement("switch (e) { case T( : Q x = n; break; } ", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T( : Q x = n").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,22): error CS1001: Identifier expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_IdentifierExpected, ":").WithLocation(1, 22), // (1,28): error CS1003: Syntax error, ',' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, "=").WithArguments(",", "=").WithLocation(1, 28), // (1,30): error CS1003: Syntax error, ',' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, "n").WithArguments(",", "").WithLocation(1, 30), // (1,31): error CS1026: ) expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 31), // (1,31): error CS1003: Syntax error, ':' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(1, 31) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Q"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void VarIsContextualKeywordForPatterns01() { UsingStatement("switch (e) { case var: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void VarIsContextualKeywordForPatterns02() { UsingStatement("if (e is var) {}"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void WhenAsPatternVariable01() { UsingStatement("switch (e) { case var when: break; }", // (1,27): error CS1525: Invalid expression term ':' // switch (e) { case var when: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(1, 27) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void WhenAsPatternVariable02() { UsingStatement("switch (e) { case K when: break; }", // (1,25): error CS1525: Invalid expression term ':' // switch (e) { case K when: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(1, 25) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "K"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact(Skip = "This is not a reliable test, and its failure modes are hard to capture. But it is helpful to run by hand to find parser issues.")] public void ParseFuzz() { Random random = new Random(); for (int i = 0; i < 4000; i++) { string source = $"class C{{void M(){{switch(e){{case {makePattern0()}:T v = e;}}}}}}"; try { Parse(source, options: TestOptions.RegularWithRecursivePatterns); for (int j = 0; j < 30; j++) { int k1 = random.Next(source.Length); int k2 = random.Next(source.Length); string source2 = source.Substring(0, k1) + source.Substring(k2); Parse(source2, options: TestOptions.RegularWithRecursivePatterns); } } catch (StackOverflowException) { Console.WriteLine("Failed on \"" + source + "\""); Assert.True(false, source); } catch (OutOfMemoryException) { Console.WriteLine("Failed on \"" + source + "\""); Assert.True(false, source); } } return; string makeProps(int maxDepth, bool needNames) { int nProps = random.Next(maxDepth); var builder = new StringBuilder(); for (int i = 0; i < nProps; i++) { if (i != 0) builder.Append(", "); if (needNames || random.Next(5) == 0) builder.Append("N: "); builder.Append(makePattern(maxDepth - 1)); } return builder.ToString(); } string makePattern(int maxDepth) { if (maxDepth <= 0 || random.Next(6) == 0) { switch (random.Next(4)) { case 0: return "_"; case 1: return "1"; case 2: return "T x"; default: return "var y"; } } else { // recursive pattern while (true) { bool nameType = random.Next(2) == 0; bool parensPart = random.Next(2) == 0; bool propsPart = random.Next(2) == 0; bool name = random.Next(2) == 0; if (!parensPart && !propsPart && !(nameType && name)) continue; return $"{(nameType ? "N" : "")} {(parensPart ? $"({makeProps(maxDepth, false)})" : "")} {(propsPart ? $"{{ {makeProps(maxDepth, true)} }}" : "")} {(name ? "n" : "")}"; } } } string makePattern0() => makePattern(random.Next(6)); } [Fact] public void ArrayOfTupleType01() { UsingStatement("if (o is (int, int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType02() { UsingStatement("if (o is (int a, int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType03() { UsingStatement("if (o is (int, int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType04() { UsingStatement("if (o is (int a, int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType05() { UsingStatement("if (o is (Int, Int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType06() { UsingStatement("if (o is (Int a, Int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType07() { UsingStatement("if (o is (Int, Int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType08() { UsingStatement("if (o is (Int a, Int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType09() { UsingStatement("if (o is (S.Int, S.Int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType10() { UsingStatement("if (o is (S.Int a, S.Int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType11() { UsingStatement("if (o is (S.Int, S.Int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType12() { UsingStatement("if (o is (S.Int a, S.Int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType13() { UsingStatement("switch (o) { case (int, int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType14() { UsingStatement("switch (o) { case (int a, int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType15() { UsingStatement("switch (o) { case (Int, Int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType16() { UsingStatement("switch (o) { case (Int a, Int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType17() { UsingStatement("switch (o) { case (S.Int, S.Int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType18() { UsingStatement("switch (o) { case (S.Int a, S.Int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void RecursivePattern_00() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_02() { UsingStatement("var x = o is (Param: 3, Param2: 4) { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_03() { UsingStatement("var x = o is Type { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_04() { UsingStatement("var x = o is { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_05() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_06() { UsingStatement("var x = o is (Param: 3, Param2: 4) x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_07() { UsingStatement("var x = o is Type x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_08() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_09() { UsingStatement("var x = o is (Param: 3, Param2: 4) { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_10() { UsingStatement("var x = o is Type { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_11() { UsingStatement("var x = o is { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_12() { UsingStatement("var x = o is Type (Param: 3, Param2: 4);"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_13() { UsingStatement("var x = o is (Param: 3, Param2: 4);"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ParenthesizedExpressionOfSwitchExpression() { UsingStatement("Console.Write((t) switch {var x => x});"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Console"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Write"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.SwitchExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "t"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword, "var"); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void DiscardInSwitchExpression() { UsingExpression("e switch { _ => 1 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_01a() { UsingStatement("switch(e) { case _: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_01b() { UsingStatement("switch(e) { case _: break; }", TestOptions.Regular7_3); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_02() { UsingStatement("switch(e) { case _ when true: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInRecursivePattern_01() { UsingExpression("e is (_, _)"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void DiscardInRecursivePattern_02() { UsingExpression("e is { P: _ }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void NotDiscardInIsTypeExpression() { UsingExpression("e is _"); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } } EOF(); } [Fact] public void ShortTuplePatterns() { UsingExpression( @"e switch { var () => 1, () => 2, var (x) => 3, (1) _ => 4, (1) x => 5, (1) {} => 6, (Item1: 1) => 7, C(1) => 8 }", expectedErrors: new DiagnosticDescription[0]); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "6"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "7"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NestedShortTuplePatterns() { UsingExpression( @"e switch { {X: var ()} => 1, {X: ()} => 2, {X: var (x)} => 3, {X: (1) _} => 4, {X: (1) x} => 5, {X: (1) {}} => 6, {X: (Item1: 1)} => 7, {X: C(1)} => 8 }", expectedErrors: new DiagnosticDescription[0]); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "6"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "7"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void IsNullableArray01() { // OK, this means `(o is A[]) ? b : c` because nullable types are not permitted for a pattern's type UsingExpression("o is A[] ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableArray02() { // error: 'cannot use nullable reference type for a pattern' or 'expected :' UsingExpression("o is A[] ? b && c", // (1,18): error CS1003: Syntax error, ':' expected // o is A[] ? b && c Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 18), // (1,18): error CS1733: Expected expression // o is A[] ? b && c Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 18) ); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } EOF(); } [Fact] public void IsNullableArray03() { // OK, this means `(o is A[][]) ? b : c` UsingExpression("o is A[][] ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableType01() { UsingExpression("o is A ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableType02() { UsingExpression("o is A? ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact, WorkItem(32161, "https://github.com/dotnet/roslyn/issues/32161")] public void ParenthesizedSwitchCase() { var text = @" switch (e) { case (0): break; case (-1): break; case (+2): break; case (~3): break; } "; foreach (var langVersion in new[] { LanguageVersion.CSharp6, LanguageVersion.CSharp7, LanguageVersion.CSharp8 }) { UsingStatement(text, options: CSharpParseOptions.Default.WithLanguageVersion(langVersion)); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.UnaryMinusExpression); { N(SyntaxKind.MinusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.BitwiseNotExpression); { N(SyntaxKind.TildeToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact] public void TrailingCommaInSwitchExpression_01() { UsingExpression("1 switch { 1 => 2, }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void TrailingCommaInSwitchExpression_02() { UsingExpression("1 switch { , }", // (1,12): error CS8504: Pattern missing // 1 switch { , } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 12), // (1,12): error CS1003: Syntax error, '=>' expected // 1 switch { , } Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 12), // (1,12): error CS1525: Invalid expression term ',' // 1 switch { , } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 12) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void TrailingCommaInPropertyPattern_01() { UsingExpression("e is { X: 3, }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void TrailingCommaInPropertyPattern_02() { UsingExpression("e is { , }", // (1,8): error CS8504: Pattern missing // e is { , } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 8) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void TrailingCommaInPositionalPattern_01() { UsingExpression("e is ( X: 3, )", // (1,14): error CS8504: Pattern missing // e is ( X: 3, ) Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 14) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void TrailingCommaInPositionalPattern_02() { UsingExpression("e is ( , )", // (1,8): error CS8504: Pattern missing // e is ( , ) Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 8), // (1,10): error CS8504: Pattern missing // e is ( , ) Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 10) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void ExtraCommaInSwitchExpression() { UsingExpression("e switch { 1 => 2,, }", // (1,19): error CS8504: Pattern missing // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 19), // (1,19): error CS1003: Syntax error, '=>' expected // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 19), // (1,19): error CS1525: Invalid expression term ',' // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 19) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ExtraCommaInPropertyPattern() { UsingExpression("e is { A: 1,, }", // (1,13): error CS8504: Pattern missing // e is { A: 1,, } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 13) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact, WorkItem(33054, "https://github.com/dotnet/roslyn/issues/33054")] public void ParenthesizedExpressionInPattern_01() { UsingStatement( @"switch (e) { case (('C') << 24) + (('g') << 16) + (('B') << 8) + 'I': break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.AddExpression); { N(SyntaxKind.AddExpression); { N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "24"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "16"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_02() { UsingStatement( @"switch (e) { case ((2) + (2)): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_03() { UsingStatement( @"switch (e) { case ((2 + 2) - 2): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SubtractExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.MinusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_04() { UsingStatement( @"switch (e) { case (2) | (2): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.BitwiseOrExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BarToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_05() { UsingStatement( @"switch (e) { case ((2 << 2) | 2): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.BitwiseOrExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BarToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ChainedSwitchExpression_01() { UsingExpression("1 switch { 1 => 2 } switch { 2 => 3 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ChainedSwitchExpression_02() { UsingExpression("a < b switch { 1 => 2 } < c switch { 2 => 3 }"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_01() { UsingExpression("a < b switch { true => 1 }"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_02() { // The left-hand-side of a switch is equality, which binds more loosely than the `switch`, // so `b` ends up on the left of the `switch` and the `a ==` expression has a switch on the right. UsingExpression("a == b switch { true => 1 }"); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_03() { UsingExpression("a * b switch {}"); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_04() { UsingExpression("a + b switch {}"); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_05() { UsingExpression("-a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.UnaryMinusExpression); { N(SyntaxKind.MinusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_06() { UsingExpression("(Type)a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_07() { UsingExpression("(Type)a++ switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.PostIncrementExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusPlusToken); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_08() { UsingExpression("+a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_09() { UsingExpression("a switch {}.X", // (1,1): error CS1073: Unexpected token '.' // a switch {}.X Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments(".").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_10() { UsingExpression("a switch {}[i]", // (1,1): error CS1073: Unexpected token '[' // a switch {}[i] Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("[").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_11() { UsingExpression("a switch {}(b)", // (1,1): error CS1073: Unexpected token '(' // a switch {}(b) Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("(").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_12() { UsingExpression("a switch {}!", // (1,1): error CS1073: Unexpected token '!' // a switch {}! Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("!").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_01() { UsingExpression("(e switch {)", // (1,12): error CS1513: } expected // (e switch {) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(1, 12) ); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_02() { UsingExpression("(e switch {,)", // (1,12): error CS8504: Pattern missing // (e switch {,) Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 12), // (1,12): error CS1003: Syntax error, '=>' expected // (e switch {,) Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 12), // (1,12): error CS1525: Invalid expression term ',' // (e switch {,) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 12), // (1,13): error CS1513: } expected // (e switch {,) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(1, 13) ); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_03() { UsingExpression("e switch {,", // (1,11): error CS8504: Pattern missing // e switch {, Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 11), // (1,11): error CS1003: Syntax error, '=>' expected // e switch {, Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 11), // (1,11): error CS1525: Invalid expression term ',' // e switch {, Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 11), // (1,12): error CS1513: } expected // e switch {, Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 12) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33675, "https://github.com/dotnet/roslyn/issues/33675")] public void ParenthesizedNamedConstantPatternInSwitchExpression() { UsingExpression("e switch { (X) => 1 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(34482, "https://github.com/dotnet/roslyn/issues/34482")] public void SwitchCaseArmErrorRecovery_01() { UsingExpression("e switch { 1 => 1; 2 => 2 }", // (1,18): error CS1003: Syntax error, ',' expected // e switch { 1 => 1; 2 => 2 } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(",", ";").WithLocation(1, 18) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(34482, "https://github.com/dotnet/roslyn/issues/34482")] public void SwitchCaseArmErrorRecovery_02() { UsingExpression("e switch { 1 => 1, 2 => 2; }", // (1,26): error CS1003: Syntax error, ',' expected // e switch { 1 => 1, 2 => 2; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(",", ";").WithLocation(1, 26) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(38121, "https://github.com/dotnet/roslyn/issues/38121")] public void GenericPropertyPattern() { UsingExpression("e is A<B> {}"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithDeclarationPattern() { UsingExpression("o is C c + d", // (1,10): error CS1073: Unexpected token '+' // o is C c + d Diagnostic(ErrorCode.ERR_UnexpectedToken, "+").WithArguments("+").WithLocation(1, 10) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithRecursivePattern() { UsingExpression("o is {} + d", // (1,9): error CS1073: Unexpected token '+' // o is {} + d Diagnostic(ErrorCode.ERR_UnexpectedToken, "+").WithArguments("+").WithLocation(1, 9) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact] public void PatternCombinators_01() { UsingStatement("_ = e is a or b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'or pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is a or b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a or b").WithArguments("or pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_02() { UsingStatement("_ = e is a and b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'and pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is a and b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a and b").WithArguments("and pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_03() { UsingStatement("_ = e is not b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is not b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not b").WithArguments("not pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_04() { UsingStatement("_ = e is not null;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is not null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not null").WithArguments("not pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_05() { UsingStatement( @"_ = e switch { a or b => 1, c and d => 2, not e => 3, not null => 4, };", TestOptions.RegularWithoutPatternCombinators, // (2,5): error CS8400: Feature 'or pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // a or b => 1, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a or b").WithArguments("or pattern", "9.0").WithLocation(2, 5), // (3,5): error CS8400: Feature 'and pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // c and d => 2, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "c and d").WithArguments("and pattern", "9.0").WithLocation(3, 5), // (4,5): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // not e => 3, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not e").WithArguments("not pattern", "9.0").WithLocation(4, 5), // (5,5): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // not null => 4, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not null").WithArguments("not pattern", "9.0").WithLocation(5, 5) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPattern_01() { UsingStatement( @"_ = e switch { < 0 => 0, <= 1 => 1, > 2 => 2, >= 3 => 3, == 4 => 4, != 5 => 5, };", TestOptions.RegularWithoutPatternCombinators, // (2,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // < 0 => 0, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "< 0").WithArguments("relational pattern", "9.0").WithLocation(2, 5), // (3,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // <= 1 => 1, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "<= 1").WithArguments("relational pattern", "9.0").WithLocation(3, 5), // (4,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // > 2 => 2, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "> 2").WithArguments("relational pattern", "9.0").WithLocation(4, 5), // (5,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // >= 3 => 3, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, ">= 3").WithArguments("relational pattern", "9.0").WithLocation(5, 5), // (6,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // == 4 => 4, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "== 4").WithArguments("relational pattern", "9.0").WithLocation(6, 5), // (7,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // != 5 => 5, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "!= 5").WithArguments("relational pattern", "9.0").WithLocation(7, 5) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_01() { UsingStatement( @"_ = e switch { < 0 < 0 => 0, == 4 < 4 => 4, != 5 < 5 => 5, };", TestOptions.RegularWithPatternCombinators, // (2,9): error CS1003: Syntax error, '=>' expected // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(2, 9), // (2,9): error CS1525: Invalid expression term '<' // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(2, 9), // (2,13): error CS1003: Syntax error, ',' expected // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(2, 13), // (2,13): error CS8504: Pattern missing // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(2, 13), // (3,10): error CS1003: Syntax error, '=>' expected // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(3, 10), // (3,10): error CS1525: Invalid expression term '<' // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(3, 10), // (3,14): error CS1003: Syntax error, ',' expected // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(3, 14), // (3,14): error CS8504: Pattern missing // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(3, 14), // (4,10): error CS1003: Syntax error, '=>' expected // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(4, 10), // (4,10): error CS1525: Invalid expression term '<' // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(4, 10), // (4,14): error CS1003: Syntax error, ',' expected // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(4, 14), // (4,14): error CS8504: Pattern missing // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(4, 14) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_02() { UsingStatement( @"_ = e switch { < 0 << 0 => 0, == 4 << 4 => 4, != 5 << 5 => 5, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_03() { UsingStatement( @"_ = e is < 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_04() { UsingStatement( @"_ = e is < 4 < 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_05() { UsingStatement( @"_ = e is < 4 << 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void WhenIsNotKeywordInIsExpression() { UsingStatement(@"_ = e is T when;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "when"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void WhenIsNotKeywordInRecursivePattern() { UsingStatement(@"_ = e switch { T(X when) => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "when"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_01() { UsingStatement(@"_ = e is int or long;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_02() { UsingStatement(@"_ = e is int or System.Int64;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_03() { UsingStatement(@"_ = e switch { int or long => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_04() { UsingStatement(@"_ = e switch { int or System.Int64 => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_05() { UsingStatement(@"_ = e switch { T(int) => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_06() { UsingStatement(@"_ = e switch { int => 1, long => 2, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(49354, "https://github.com/dotnet/roslyn/issues/49354")] public void TypePattern_07() { UsingStatement(@"_ = e is (int) or string;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_08() { UsingStatement($"_ = e is (a) or b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CompoundPattern_01() { UsingStatement(@"bool isLetter(char c) => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z';", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.IdentifierToken, "isLetter"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.CharKeyword); } N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_01() { UsingStatement(@"_ = e is int and;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_02() { UsingStatement(@"_ = e is int and < Z;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_03() { UsingStatement(@"_ = e is int and && b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_04() { UsingStatement(@"_ = e is int and int.MaxValue;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "MaxValue"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_05() { UsingStatement(@"_ = e is int and MaxValue;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "MaxValue"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_06() { UsingStatement(@"_ = e is int and ?? Z;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_07() { UsingStatement(@"_ = e is int and ? a : b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithTypeTest() { UsingExpression("o is int + d", // (1,6): error CS1525: Invalid expression term 'int' // o is int + d Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(1, 6) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.AddExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithBlockLambda() { UsingExpression("() => {} + d", // (1,10): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // () => {} + d Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(1, 10) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithAnonymousMethod() { UsingExpression("delegate {} + d", // (1,13): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // delegate {} + d Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(1, 13) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_01() { UsingStatement(@"_ = e is (3);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_02() { UsingStatement(@"_ = e is (A);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_03() { UsingStatement(@"_ = e is (int);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_04() { UsingStatement(@"_ = e is (Item1: int);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_05() { UsingStatement(@"_ = e is (A) x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_06() { UsingStatement(@"_ = e is ((A, A)) x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_01() { UsingStatement(@"_ = e is ();", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_02() { UsingStatement(@"_ = e is () x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_03() { UsingStatement(@"_ = e is () {};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CastExpressionInPattern_01() { UsingStatement(@"_ = e is (int)+1;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [InlineData("or")] [InlineData("and")] [InlineData("not")] public void CastExpressionInPattern_02(string identifier) { UsingStatement($"_ = e is (int){identifier};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, identifier); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CastExpressionInPattern_03( [CombinatorialValues("and", "or")] string left, [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is (int){left} {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, left); } } } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CastExpressionInPattern_04() { UsingStatement($"_ = e is (a)42 or b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "42"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CombinatorAsConstant_00( [CombinatorialValues("and", "or")] string left, [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is {left} {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, left); } } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CombinatorAsConstant_01( [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is (int) {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_02() { UsingStatement($"_ = e is (int) or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_03() { UsingStatement($"_ = e is (int)or or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "or"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_04() { UsingStatement($"_ = e is (int) or or or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "or"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ConjunctiveFollowedByPropertyPattern_01() { UsingStatement(@"switch (e) { case {} and {}: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConjunctiveFollowedByTuplePattern_01() { UsingStatement(@"switch (e) { case {} and (): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_01() { UsingStatement(@"_ = e is (>= 1);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_02() { UsingStatement(@"_ = e switch { (>= 1) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_03() { UsingStatement(@"bool isAsciiLetter(char c) => c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z');", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.IdentifierToken, "isAsciiLetter"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.CharKeyword); } N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_04() { UsingStatement(@"_ = e is (<= 1, >= 2);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void AndPatternAssociativity_01() { UsingStatement(@"_ = e is A and B and C;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OrPatternAssociativity_01() { UsingStatement(@"_ = e is A or B or C;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(43960, "https://github.com/dotnet/roslyn/issues/43960")] public void NamespaceQualifiedEnumConstantInSwitchCase() { var source = @"switch (e) { case global::E.A: break; }"; UsingStatement(source, TestOptions.RegularWithPatternCombinators ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators ); verifyTree(); void verifyTree() { N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "E"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")] public void NamespaceQualifiedEnumConstantInIsPattern() { var source = @"_ = e is global::E.A;"; UsingStatement(source, TestOptions.RegularWithPatternCombinators ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "E"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(45757, "https://github.com/dotnet/roslyn/issues/45757")] public void IncompleteTuplePatternInPropertySubpattern() { var source = @"_ = this is Program { P1: (1, }"; var expectedErrors = new[] { // (1,32): error CS1026: ) expected // _ = this is Program { P1: (1, } Diagnostic(ErrorCode.ERR_CloseParenExpected, "}").WithLocation(1, 32), // (1,33): error CS1002: ; expected // _ = this is Program { P1: (1, } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 33) }; UsingStatement(source, TestOptions.RegularWithPatternCombinators, expectedErrors ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators, expectedErrors ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Program"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } } } M(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(45757, "https://github.com/dotnet/roslyn/issues/45757")] public void IncompleteTuplePattern() { var source = @"_ = i is (1, }"; var expectedErrors = new[] { // (1,1): error CS1073: Unexpected token '}' // _ = i is (1, } Diagnostic(ErrorCode.ERR_UnexpectedToken, "_ = i is (1, ").WithArguments("}").WithLocation(1, 1), // (1,16): error CS1026: ) expected // _ = i is (1, } Diagnostic(ErrorCode.ERR_CloseParenExpected, "}").WithLocation(1, 16), // (1,16): error CS1002: ; expected // _ = i is (1, } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(1, 16) }; UsingStatement(source, TestOptions.RegularWithPatternCombinators, expectedErrors ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators, expectedErrors ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseParenToken); } } } } M(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(47614, "https://github.com/dotnet/roslyn/issues/47614")] public void GenericTypeAsTypePatternInSwitchExpression() { UsingStatement(@"_ = e switch { List<X> => 1, List<Y> => 2, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "List"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "List"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_PredefinedType() { UsingStatement(@"_ = e switch { int? => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_PredefinedType() { UsingStatement(@"switch(a) { case int?: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_PredefinedType_Parenthesized() { UsingStatement(@"_ = e switch { (int?) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_PredefinedType_Parenthesized() { UsingStatement(@"switch(a) { case (int?): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression() { UsingStatement(@"_ = e switch { a? => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement() { UsingStatement(@"switch(a) { case a?: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_Parenthesized() { UsingStatement(@"_ = e switch { (a?) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_Parenthesized() { UsingStatement(@"switch(a) { case (a?): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchExpression() { UsingStatement(@"_ = e switch { (a?x:y) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchStatement() { UsingStatement(@"switch(a) { case a?x:y: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchStatement_Parenthesized() { UsingStatement(@"switch(a) { case (a?x:y): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } }
// Licensed to the .NET Foundation under one or more 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.Text; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.Patterns)] public class PatternParsingTests : ParsingTests { private new void UsingStatement(string text, params DiagnosticDescription[] expectedErrors) { UsingStatement(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8), expectedErrors); } public PatternParsingTests(ITestOutputHelper output) : base(output) { } [Fact] public void CasePatternVersusFeatureFlag() { var test = @" class C { public static void Main(string[] args) { switch ((int) args[0][0]) { case 1: case 2 when args.Length == 2: case 1<<2: case string s: default: break; } bool b = args[0] is string s; } } "; CreateCompilation(test, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics( // (9,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case 2 when args.Length == 2: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case 2 when args.Length == 2:").WithArguments("pattern matching", "7.0").WithLocation(9, 13), // (11,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case string s: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case string s:").WithArguments("pattern matching", "7.0").WithLocation(11, 13), // (15,18): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // bool b = args[0] is string s; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "args[0] is string s").WithArguments("pattern matching", "7.0").WithLocation(15, 18), // (11,18): error CS8121: An expression of type 'int' cannot be handled by a pattern of type 'string'. // case string s: Diagnostic(ErrorCode.ERR_PatternWrongType, "string").WithArguments("int", "string").WithLocation(11, 18), // (11,25): error CS0136: A local or parameter named 's' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case string s: Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "s").WithArguments("s").WithLocation(11, 25) ); } [Fact] public void ThrowExpression_Good() { var test = @"using System; class C { public static void Sample(bool b, string s) { void NeverReturnsFunction() => throw new NullReferenceException(); int x = b ? throw new NullReferenceException() : 1; x = b ? 2 : throw new NullReferenceException(); s = s ?? throw new NullReferenceException(); NeverReturnsFunction(); throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; } public static void NeverReturns() => throw new NullReferenceException(); }"; CreateCompilation(test).VerifyDiagnostics(); CreateCompilation(test, parseOptions: TestOptions.Regular6).VerifyDiagnostics( // (6,14): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // void NeverReturnsFunction() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "NeverReturnsFunction").WithArguments("local functions", "7.0").WithLocation(6, 14), // (6,40): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // void NeverReturnsFunction() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(6, 40), // (7,21): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // int x = b ? throw new NullReferenceException() : 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(7, 21), // (8,21): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // x = b ? 2 : throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(8, 21), // (9,18): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // s = s ?? throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(9, 18), // (11,47): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException() ?? throw null").WithArguments("throw expression", "7.0").WithLocation(11, 47), // (11,85): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw null").WithArguments("throw expression", "7.0").WithLocation(11, 85), // (13,42): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // public static void NeverReturns() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(13, 42) ); } [Fact] public void ThrowExpression_Bad() { var test = @"using System; class C { public static void Sample(bool b, string s) { // throw expression at wrong precedence s = s + throw new NullReferenceException(); if (b || throw new NullReferenceException()) { } // throw expression where not permitted var z = from x in throw new NullReferenceException() select x; M(throw new NullReferenceException()); throw throw null; (int, int) w = (1, throw null); return throw null; } static void M(string s) {} }"; CreateCompilationWithMscorlib46(test).VerifyDiagnostics( // (7,17): error CS1525: Invalid expression term 'throw' // s = s + throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw new NullReferenceException()").WithArguments("throw").WithLocation(7, 17), // (8,18): error CS1525: Invalid expression term 'throw' // if (b || throw new NullReferenceException()) { } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw new NullReferenceException()").WithArguments("throw").WithLocation(8, 18), // (11,27): error CS8115: A throw expression is not allowed in this context. // var z = from x in throw new NullReferenceException() select x; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(11, 27), // (12,11): error CS8115: A throw expression is not allowed in this context. // M(throw new NullReferenceException()); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(12, 11), // (13,15): error CS8115: A throw expression is not allowed in this context. // throw throw null; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(13, 15), // (14,9): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int, int)").WithArguments("System.ValueTuple`2").WithLocation(14, 9), // (14,28): error CS8115: A throw expression is not allowed in this context. // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(14, 28), // (14,24): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, throw null)").WithArguments("System.ValueTuple`2").WithLocation(14, 24), // (15,16): error CS8115: A throw expression is not allowed in this context. // return throw null; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(15, 16), // (14,9): warning CS0162: Unreachable code detected // (int, int) w = (1, throw null); Diagnostic(ErrorCode.WRN_UnreachableCode, "(").WithLocation(14, 9) ); } [Fact] public void ThrowExpression() { UsingTree(@" class C { int x = y ?? throw null; }", options: TestOptions.Regular); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.ThrowExpression); { N(SyntaxKind.ThrowKeyword); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_1() { UsingNode(SyntaxFactory.ParseExpression("A is B < C, D > [ ]")); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_2() { UsingNode(SyntaxFactory.ParseExpression("A < B > C")); N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_3() { SyntaxFactory.ParseExpression("e is A<B> && e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> || e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> ^ e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> | e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> & e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B>[]").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("new { X = e is A<B> }").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B>").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("(item is Dictionary<string, object>[])").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A is B < C, D > [ ]").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A is B < C, D > [ ] E").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A < B > C").GetDiagnostics().Verify(); } [Fact] public void QueryContextualPatternVariable_01() { SyntaxFactory.ParseExpression("from s in a where s is string where s.Length > 1 select s").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("M(out int? x)").GetDiagnostics().Verify(); } [Fact] public void TypeDisambiguation_01() { UsingStatement(@" var r = from s in a where s is X<T> // should disambiguate as a type here where M(s) select s as X<T>;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierToken, "s"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.QueryBody); { N(SyntaxKind.WhereClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } } N(SyntaxKind.WhereClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SelectClause); { N(SyntaxKind.SelectKeyword); N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypeDisambiguation_02() { UsingStatement(@" var r = a is X<T> // should disambiguate as a type here is bool;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.IsKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypeDisambiguation_03() { UsingStatement(@" var r = a is X<T> // should disambiguate as a type here > Z;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence00() { UsingExpression("A is B << C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence01() { UsingExpression("A is 1 << 2"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence02() { UsingExpression("A is null < B"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence02b() { UsingExpression("A is B < C"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence03() { UsingExpression("A is null == B"); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence04() { UsingExpression("A is null & B"); N(SyntaxKind.BitwiseAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.AmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence05() { UsingExpression("A is null && B"); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence05b() { UsingExpression("A is null || B"); N(SyntaxKind.LogicalOrExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.BarBarToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence06() { UsingStatement(@"switch (e) { case 1 << 2: case B << C: case null < B: case null == B: case null & B: case null && B: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.BitwiseAndExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.AmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(21515, "https://github.com/dotnet/roslyn/issues/21515")] public void PatternExpressionPrecedence07() { // This should actually be error-free. UsingStatement(@"switch (array) { case KeyValuePair<string, DateTime>[] pairs1: case KeyValuePair<String, DateTime>[] pairs2: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "array"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "KeyValuePair"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "DateTime"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "pairs1"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "KeyValuePair"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "String"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "DateTime"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "pairs2"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_01() { UsingExpression("A is B***", // (1,10): error CS1733: Expected expression // A is B*** Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 10) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_01b() { UsingExpression("A is B*** C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_02() { UsingExpression("A is B***[]"); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_03() { UsingExpression("A is B***[] C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_04() { UsingExpression("(B*** C, D)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_04b() { UsingExpression("(B*** C)"); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_05() { UsingExpression("(B***[] C, D)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_06() { UsingExpression("(D, B*** C)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_07() { UsingExpression("(D, B***[] C)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_08() { UsingStatement("switch (e) { case B*** C: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_09() { UsingStatement("switch (e) { case B***[] C: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_01() { // This should actually be error-free, because `nameof` might be a type. UsingStatement(@"switch (e) { case nameof n: ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_02() { // This should actually be error-free; a constant pattern with nameof(n) as the constant. UsingStatement(@"switch (e) { case nameof(n): ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_03() { // This should actually be error-free; a constant pattern with nameof(n) as the constant. UsingStatement(@"switch (e) { case nameof(n) when true: ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_01() { UsingStatement(@"switch (e) { case (((3))): ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_02() { UsingStatement(@"switch (e) { case (((3))) when true: ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_03() { var expect = new[] { // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (x: ((3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(x: ((3)))").WithArguments("recursive patterns", "8.0").WithLocation(1, 19) }; UsingStatement(@"switch (e) { case (x: ((3))): ; }", TestOptions.RegularWithoutRecursivePatterns, expect); checkNodes(); UsingStatement(@"switch (e) { case (x: ((3))): ; }", TestOptions.Regular8); checkNodes(); void checkNodes() { N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact] public void ParenthesizedExpression_04() { UsingStatement(@"switch (e) { case (((x: 3))): ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8370: Feature 'parenthesized pattern' is not available in C# 7.3. Please use language version 9.0 or greater. // switch (e) { case (((x: 3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(((x: 3)))").WithArguments("parenthesized pattern", "9.0").WithLocation(1, 19), // (1,20): error CS8370: Feature 'parenthesized pattern' is not available in C# 7.3. Please use language version 9.0 or greater. // switch (e) { case (((x: 3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "((x: 3))").WithArguments("parenthesized pattern", "9.0").WithLocation(1, 20) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void RecursivePattern_01() { UsingStatement(@"switch (e) { case T(X: 3, Y: 4){L: 5} p: ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case T(X: 3, Y: 4){L: 5} p: ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T(X: 3, Y: 4){L: 5} p").WithArguments("recursive patterns", "8.0").WithLocation(1, 19) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "L"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "p"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_06() { UsingStatement(@"switch (e) { case (: ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(: ").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,20): error CS1001: Identifier expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_IdentifierExpected, ":").WithLocation(1, 20), // (1,22): error CS1026: ) expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 22), // (1,22): error CS1003: Syntax error, ':' expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(1, 22) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_07() { UsingStatement(@"switch (e) { case (", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case ( Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,20): error CS1026: ) expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(1, 20), // (1,20): error CS1003: Syntax error, ':' expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 20), // (1,20): error CS1513: } expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 20) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } } M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_07() { UsingStatement(@"switch (e) { case (): }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (): } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "()").WithArguments("recursive patterns", "8.0").WithLocation(1, 19)); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_08() { UsingStatement(@"switch (e) { case", // (1,18): error CS1733: Expected expression // switch (e) { case Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 18), // (1,18): error CS1003: Syntax error, ':' expected // switch (e) { case Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 18), // (1,18): error CS1513: } expected // switch (e) { case Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 18) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); } } M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_05() { UsingStatement(@"switch (e) { case (x: ): ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (x: ): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(x: )").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,23): error CS8504: Pattern missing // switch (e) { case (x: ): ; } Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 23) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void EmptySwitchExpression() { UsingExpression("1 switch {}", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch {}").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression01() { UsingExpression("1 switch {a => b, c => d}", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch {a => b, c => d} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch {a => b, c => d}").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression02() { UsingExpression("1 switch { a?b:c => d }", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { a?b:c => d }").WithArguments("recursive patterns", "8.0").WithLocation(1, 1), // (1,13): error CS1003: Syntax error, '=>' expected // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments("=>", "?").WithLocation(1, 13), // (1,13): error CS1525: Invalid expression term '?' // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "?").WithArguments("?").WithLocation(1, 13) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.ConditionalExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression03() { UsingExpression("1 switch { (a, b, c) => d }", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch { (a, b, c) => d } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { (a, b, c) => d }").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenRecursivePattern01() { // This put the parser into an infinite loop at one time. The precise diagnostics and nodes // are not as important as the fact that it terminates. UsingStatement("switch (e) { case T( : Q x = n; break; } ", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T( : Q x = n").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,22): error CS1001: Identifier expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_IdentifierExpected, ":").WithLocation(1, 22), // (1,28): error CS1003: Syntax error, ',' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, "=").WithArguments(",", "=").WithLocation(1, 28), // (1,30): error CS1003: Syntax error, ',' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, "n").WithArguments(",", "").WithLocation(1, 30), // (1,31): error CS1026: ) expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 31), // (1,31): error CS1003: Syntax error, ':' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(1, 31) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Q"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void VarIsContextualKeywordForPatterns01() { UsingStatement("switch (e) { case var: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void VarIsContextualKeywordForPatterns02() { UsingStatement("if (e is var) {}"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void WhenAsPatternVariable01() { UsingStatement("switch (e) { case var when: break; }", // (1,27): error CS1525: Invalid expression term ':' // switch (e) { case var when: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(1, 27) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void WhenAsPatternVariable02() { UsingStatement("switch (e) { case K when: break; }", // (1,25): error CS1525: Invalid expression term ':' // switch (e) { case K when: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(1, 25) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "K"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact(Skip = "This is not a reliable test, and its failure modes are hard to capture. But it is helpful to run by hand to find parser issues.")] public void ParseFuzz() { Random random = new Random(); for (int i = 0; i < 4000; i++) { string source = $"class C{{void M(){{switch(e){{case {makePattern0()}:T v = e;}}}}}}"; try { Parse(source, options: TestOptions.RegularWithRecursivePatterns); for (int j = 0; j < 30; j++) { int k1 = random.Next(source.Length); int k2 = random.Next(source.Length); string source2 = source.Substring(0, k1) + source.Substring(k2); Parse(source2, options: TestOptions.RegularWithRecursivePatterns); } } catch (StackOverflowException) { Console.WriteLine("Failed on \"" + source + "\""); Assert.True(false, source); } catch (OutOfMemoryException) { Console.WriteLine("Failed on \"" + source + "\""); Assert.True(false, source); } } return; string makeProps(int maxDepth, bool needNames) { int nProps = random.Next(maxDepth); var builder = new StringBuilder(); for (int i = 0; i < nProps; i++) { if (i != 0) builder.Append(", "); if (needNames || random.Next(5) == 0) builder.Append("N: "); builder.Append(makePattern(maxDepth - 1)); } return builder.ToString(); } string makePattern(int maxDepth) { if (maxDepth <= 0 || random.Next(6) == 0) { switch (random.Next(4)) { case 0: return "_"; case 1: return "1"; case 2: return "T x"; default: return "var y"; } } else { // recursive pattern while (true) { bool nameType = random.Next(2) == 0; bool parensPart = random.Next(2) == 0; bool propsPart = random.Next(2) == 0; bool name = random.Next(2) == 0; if (!parensPart && !propsPart && !(nameType && name)) continue; return $"{(nameType ? "N" : "")} {(parensPart ? $"({makeProps(maxDepth, false)})" : "")} {(propsPart ? $"{{ {makeProps(maxDepth, true)} }}" : "")} {(name ? "n" : "")}"; } } } string makePattern0() => makePattern(random.Next(6)); } [Fact] public void ArrayOfTupleType01() { UsingStatement("if (o is (int, int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType02() { UsingStatement("if (o is (int a, int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType03() { UsingStatement("if (o is (int, int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType04() { UsingStatement("if (o is (int a, int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType05() { UsingStatement("if (o is (Int, Int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType06() { UsingStatement("if (o is (Int a, Int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType07() { UsingStatement("if (o is (Int, Int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType08() { UsingStatement("if (o is (Int a, Int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType09() { UsingStatement("if (o is (S.Int, S.Int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType10() { UsingStatement("if (o is (S.Int a, S.Int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType11() { UsingStatement("if (o is (S.Int, S.Int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType12() { UsingStatement("if (o is (S.Int a, S.Int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType13() { UsingStatement("switch (o) { case (int, int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType14() { UsingStatement("switch (o) { case (int a, int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType15() { UsingStatement("switch (o) { case (Int, Int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType16() { UsingStatement("switch (o) { case (Int a, Int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType17() { UsingStatement("switch (o) { case (S.Int, S.Int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType18() { UsingStatement("switch (o) { case (S.Int a, S.Int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void RecursivePattern_00() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_02() { UsingStatement("var x = o is (Param: 3, Param2: 4) { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_03() { UsingStatement("var x = o is Type { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_04() { UsingStatement("var x = o is { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_05() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_06() { UsingStatement("var x = o is (Param: 3, Param2: 4) x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_07() { UsingStatement("var x = o is Type x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_08() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_09() { UsingStatement("var x = o is (Param: 3, Param2: 4) { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_10() { UsingStatement("var x = o is Type { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_11() { UsingStatement("var x = o is { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_12() { UsingStatement("var x = o is Type (Param: 3, Param2: 4);"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_13() { UsingStatement("var x = o is (Param: 3, Param2: 4);"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ParenthesizedExpressionOfSwitchExpression() { UsingStatement("Console.Write((t) switch {var x => x});"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Console"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Write"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.SwitchExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "t"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword, "var"); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void DiscardInSwitchExpression() { UsingExpression("e switch { _ => 1 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_01a() { UsingStatement("switch(e) { case _: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_01b() { UsingStatement("switch(e) { case _: break; }", TestOptions.Regular7_3); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_02() { UsingStatement("switch(e) { case _ when true: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInRecursivePattern_01() { UsingExpression("e is (_, _)"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void DiscardInRecursivePattern_02() { UsingExpression("e is { P: _ }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void NotDiscardInIsTypeExpression() { UsingExpression("e is _"); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } } EOF(); } [Fact] public void ShortTuplePatterns() { UsingExpression( @"e switch { var () => 1, () => 2, var (x) => 3, (1) _ => 4, (1) x => 5, (1) {} => 6, (Item1: 1) => 7, C(1) => 8 }", expectedErrors: new DiagnosticDescription[0]); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "6"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "7"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NestedShortTuplePatterns() { UsingExpression( @"e switch { {X: var ()} => 1, {X: ()} => 2, {X: var (x)} => 3, {X: (1) _} => 4, {X: (1) x} => 5, {X: (1) {}} => 6, {X: (Item1: 1)} => 7, {X: C(1)} => 8 }", expectedErrors: new DiagnosticDescription[0]); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "6"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "7"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void IsNullableArray01() { // OK, this means `(o is A[]) ? b : c` because nullable types are not permitted for a pattern's type UsingExpression("o is A[] ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableArray02() { // error: 'cannot use nullable reference type for a pattern' or 'expected :' UsingExpression("o is A[] ? b && c", // (1,18): error CS1003: Syntax error, ':' expected // o is A[] ? b && c Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 18), // (1,18): error CS1733: Expected expression // o is A[] ? b && c Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 18) ); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } EOF(); } [Fact] public void IsNullableArray03() { // OK, this means `(o is A[][]) ? b : c` UsingExpression("o is A[][] ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableType01() { UsingExpression("o is A ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableType02() { UsingExpression("o is A? ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact, WorkItem(32161, "https://github.com/dotnet/roslyn/issues/32161")] public void ParenthesizedSwitchCase() { var text = @" switch (e) { case (0): break; case (-1): break; case (+2): break; case (~3): break; } "; foreach (var langVersion in new[] { LanguageVersion.CSharp6, LanguageVersion.CSharp7, LanguageVersion.CSharp8 }) { UsingStatement(text, options: CSharpParseOptions.Default.WithLanguageVersion(langVersion)); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.UnaryMinusExpression); { N(SyntaxKind.MinusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.BitwiseNotExpression); { N(SyntaxKind.TildeToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact] public void TrailingCommaInSwitchExpression_01() { UsingExpression("1 switch { 1 => 2, }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void TrailingCommaInSwitchExpression_02() { UsingExpression("1 switch { , }", // (1,12): error CS8504: Pattern missing // 1 switch { , } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 12), // (1,12): error CS1003: Syntax error, '=>' expected // 1 switch { , } Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 12), // (1,12): error CS1525: Invalid expression term ',' // 1 switch { , } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 12) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void TrailingCommaInPropertyPattern_01() { UsingExpression("e is { X: 3, }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void TrailingCommaInPropertyPattern_02() { UsingExpression("e is { , }", // (1,8): error CS8504: Pattern missing // e is { , } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 8) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void TrailingCommaInPositionalPattern_01() { UsingExpression("e is ( X: 3, )", // (1,14): error CS8504: Pattern missing // e is ( X: 3, ) Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 14) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void TrailingCommaInPositionalPattern_02() { UsingExpression("e is ( , )", // (1,8): error CS8504: Pattern missing // e is ( , ) Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 8), // (1,10): error CS8504: Pattern missing // e is ( , ) Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 10) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void ExtraCommaInSwitchExpression() { UsingExpression("e switch { 1 => 2,, }", // (1,19): error CS8504: Pattern missing // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 19), // (1,19): error CS1003: Syntax error, '=>' expected // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 19), // (1,19): error CS1525: Invalid expression term ',' // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 19) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ExtraCommaInPropertyPattern() { UsingExpression("e is { A: 1,, }", // (1,13): error CS8504: Pattern missing // e is { A: 1,, } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 13) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact, WorkItem(33054, "https://github.com/dotnet/roslyn/issues/33054")] public void ParenthesizedExpressionInPattern_01() { UsingStatement( @"switch (e) { case (('C') << 24) + (('g') << 16) + (('B') << 8) + 'I': break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.AddExpression); { N(SyntaxKind.AddExpression); { N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "24"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "16"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_02() { UsingStatement( @"switch (e) { case ((2) + (2)): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_03() { UsingStatement( @"switch (e) { case ((2 + 2) - 2): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SubtractExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.MinusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_04() { UsingStatement( @"switch (e) { case (2) | (2): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.BitwiseOrExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BarToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_05() { UsingStatement( @"switch (e) { case ((2 << 2) | 2): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.BitwiseOrExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BarToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ChainedSwitchExpression_01() { UsingExpression("1 switch { 1 => 2 } switch { 2 => 3 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ChainedSwitchExpression_02() { UsingExpression("a < b switch { 1 => 2 } < c switch { 2 => 3 }"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_01() { UsingExpression("a < b switch { true => 1 }"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_02() { // The left-hand-side of a switch is equality, which binds more loosely than the `switch`, // so `b` ends up on the left of the `switch` and the `a ==` expression has a switch on the right. UsingExpression("a == b switch { true => 1 }"); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_03() { UsingExpression("a * b switch {}"); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_04() { UsingExpression("a + b switch {}"); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_05() { UsingExpression("-a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.UnaryMinusExpression); { N(SyntaxKind.MinusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_06() { UsingExpression("(Type)a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_07() { UsingExpression("(Type)a++ switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.PostIncrementExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusPlusToken); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_08() { UsingExpression("+a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_09() { UsingExpression("a switch {}.X", // (1,1): error CS1073: Unexpected token '.' // a switch {}.X Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments(".").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_10() { UsingExpression("a switch {}[i]", // (1,1): error CS1073: Unexpected token '[' // a switch {}[i] Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("[").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_11() { UsingExpression("a switch {}(b)", // (1,1): error CS1073: Unexpected token '(' // a switch {}(b) Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("(").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_12() { UsingExpression("a switch {}!", // (1,1): error CS1073: Unexpected token '!' // a switch {}! Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("!").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_01() { UsingExpression("(e switch {)", // (1,12): error CS1513: } expected // (e switch {) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(1, 12) ); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_02() { UsingExpression("(e switch {,)", // (1,12): error CS8504: Pattern missing // (e switch {,) Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 12), // (1,12): error CS1003: Syntax error, '=>' expected // (e switch {,) Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 12), // (1,12): error CS1525: Invalid expression term ',' // (e switch {,) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 12), // (1,13): error CS1513: } expected // (e switch {,) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(1, 13) ); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_03() { UsingExpression("e switch {,", // (1,11): error CS8504: Pattern missing // e switch {, Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 11), // (1,11): error CS1003: Syntax error, '=>' expected // e switch {, Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 11), // (1,11): error CS1525: Invalid expression term ',' // e switch {, Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 11), // (1,12): error CS1513: } expected // e switch {, Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 12) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33675, "https://github.com/dotnet/roslyn/issues/33675")] public void ParenthesizedNamedConstantPatternInSwitchExpression() { UsingExpression("e switch { (X) => 1 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(34482, "https://github.com/dotnet/roslyn/issues/34482")] public void SwitchCaseArmErrorRecovery_01() { UsingExpression("e switch { 1 => 1; 2 => 2 }", // (1,18): error CS1003: Syntax error, ',' expected // e switch { 1 => 1; 2 => 2 } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(",", ";").WithLocation(1, 18) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(34482, "https://github.com/dotnet/roslyn/issues/34482")] public void SwitchCaseArmErrorRecovery_02() { UsingExpression("e switch { 1 => 1, 2 => 2; }", // (1,26): error CS1003: Syntax error, ',' expected // e switch { 1 => 1, 2 => 2; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(",", ";").WithLocation(1, 26) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(38121, "https://github.com/dotnet/roslyn/issues/38121")] public void GenericPropertyPattern() { UsingExpression("e is A<B> {}"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithDeclarationPattern() { UsingExpression("o is C c + d", // (1,10): error CS1073: Unexpected token '+' // o is C c + d Diagnostic(ErrorCode.ERR_UnexpectedToken, "+").WithArguments("+").WithLocation(1, 10) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithRecursivePattern() { UsingExpression("o is {} + d", // (1,9): error CS1073: Unexpected token '+' // o is {} + d Diagnostic(ErrorCode.ERR_UnexpectedToken, "+").WithArguments("+").WithLocation(1, 9) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact] public void PatternCombinators_01() { UsingStatement("_ = e is a or b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'or pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is a or b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a or b").WithArguments("or pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_02() { UsingStatement("_ = e is a and b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'and pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is a and b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a and b").WithArguments("and pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_03() { UsingStatement("_ = e is not b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is not b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not b").WithArguments("not pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_04() { UsingStatement("_ = e is not null;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is not null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not null").WithArguments("not pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_05() { UsingStatement( @"_ = e switch { a or b => 1, c and d => 2, not e => 3, not null => 4, };", TestOptions.RegularWithoutPatternCombinators, // (2,5): error CS8400: Feature 'or pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // a or b => 1, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a or b").WithArguments("or pattern", "9.0").WithLocation(2, 5), // (3,5): error CS8400: Feature 'and pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // c and d => 2, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "c and d").WithArguments("and pattern", "9.0").WithLocation(3, 5), // (4,5): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // not e => 3, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not e").WithArguments("not pattern", "9.0").WithLocation(4, 5), // (5,5): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // not null => 4, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not null").WithArguments("not pattern", "9.0").WithLocation(5, 5) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPattern_01() { UsingStatement( @"_ = e switch { < 0 => 0, <= 1 => 1, > 2 => 2, >= 3 => 3, == 4 => 4, != 5 => 5, };", TestOptions.RegularWithoutPatternCombinators, // (2,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // < 0 => 0, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "< 0").WithArguments("relational pattern", "9.0").WithLocation(2, 5), // (3,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // <= 1 => 1, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "<= 1").WithArguments("relational pattern", "9.0").WithLocation(3, 5), // (4,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // > 2 => 2, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "> 2").WithArguments("relational pattern", "9.0").WithLocation(4, 5), // (5,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // >= 3 => 3, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, ">= 3").WithArguments("relational pattern", "9.0").WithLocation(5, 5), // (6,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // == 4 => 4, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "== 4").WithArguments("relational pattern", "9.0").WithLocation(6, 5), // (7,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // != 5 => 5, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "!= 5").WithArguments("relational pattern", "9.0").WithLocation(7, 5) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_01() { UsingStatement( @"_ = e switch { < 0 < 0 => 0, == 4 < 4 => 4, != 5 < 5 => 5, };", TestOptions.RegularWithPatternCombinators, // (2,9): error CS1003: Syntax error, '=>' expected // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(2, 9), // (2,9): error CS1525: Invalid expression term '<' // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(2, 9), // (2,13): error CS1003: Syntax error, ',' expected // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(2, 13), // (2,13): error CS8504: Pattern missing // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(2, 13), // (3,10): error CS1003: Syntax error, '=>' expected // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(3, 10), // (3,10): error CS1525: Invalid expression term '<' // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(3, 10), // (3,14): error CS1003: Syntax error, ',' expected // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(3, 14), // (3,14): error CS8504: Pattern missing // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(3, 14), // (4,10): error CS1003: Syntax error, '=>' expected // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(4, 10), // (4,10): error CS1525: Invalid expression term '<' // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(4, 10), // (4,14): error CS1003: Syntax error, ',' expected // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(4, 14), // (4,14): error CS8504: Pattern missing // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(4, 14) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_02() { UsingStatement( @"_ = e switch { < 0 << 0 => 0, == 4 << 4 => 4, != 5 << 5 => 5, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_03() { UsingStatement( @"_ = e is < 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_04() { UsingStatement( @"_ = e is < 4 < 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_05() { UsingStatement( @"_ = e is < 4 << 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void WhenIsNotKeywordInIsExpression() { UsingStatement(@"_ = e is T when;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "when"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void WhenIsNotKeywordInRecursivePattern() { UsingStatement(@"_ = e switch { T(X when) => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "when"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_01() { UsingStatement(@"_ = e is int or long;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_02() { UsingStatement(@"_ = e is int or System.Int64;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_03() { UsingStatement(@"_ = e switch { int or long => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_04() { UsingStatement(@"_ = e switch { int or System.Int64 => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_05() { UsingStatement(@"_ = e switch { T(int) => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_06() { UsingStatement(@"_ = e switch { int => 1, long => 2, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(49354, "https://github.com/dotnet/roslyn/issues/49354")] public void TypePattern_07() { UsingStatement(@"_ = e is (int) or string;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_08() { UsingStatement($"_ = e is (a) or b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CompoundPattern_01() { UsingStatement(@"bool isLetter(char c) => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z';", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.IdentifierToken, "isLetter"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.CharKeyword); } N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_01() { UsingStatement(@"_ = e is int and;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_02() { UsingStatement(@"_ = e is int and < Z;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_03() { UsingStatement(@"_ = e is int and && b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_04() { UsingStatement(@"_ = e is int and int.MaxValue;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "MaxValue"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_05() { UsingStatement(@"_ = e is int and MaxValue;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "MaxValue"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_06() { UsingStatement(@"_ = e is int and ?? Z;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_07() { UsingStatement(@"_ = e is int and ? a : b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithTypeTest() { UsingExpression("o is int + d", // (1,6): error CS1525: Invalid expression term 'int' // o is int + d Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(1, 6) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.AddExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithBlockLambda() { UsingExpression("() => {} + d", // (1,10): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // () => {} + d Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(1, 10) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithAnonymousMethod() { UsingExpression("delegate {} + d", // (1,13): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // delegate {} + d Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(1, 13) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_01() { UsingStatement(@"_ = e is (3);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_02() { UsingStatement(@"_ = e is (A);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_03() { UsingStatement(@"_ = e is (int);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_04() { UsingStatement(@"_ = e is (Item1: int);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_05() { UsingStatement(@"_ = e is (A) x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_06() { UsingStatement(@"_ = e is ((A, A)) x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_01() { UsingStatement(@"_ = e is ();", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_02() { UsingStatement(@"_ = e is () x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_03() { UsingStatement(@"_ = e is () {};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CastExpressionInPattern_01() { UsingStatement(@"_ = e is (int)+1;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [InlineData("or")] [InlineData("and")] [InlineData("not")] public void CastExpressionInPattern_02(string identifier) { UsingStatement($"_ = e is (int){identifier};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, identifier); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CastExpressionInPattern_03( [CombinatorialValues("and", "or")] string left, [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is (int){left} {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, left); } } } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CastExpressionInPattern_04() { UsingStatement($"_ = e is (a)42 or b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "42"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CombinatorAsConstant_00( [CombinatorialValues("and", "or")] string left, [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is {left} {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, left); } } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CombinatorAsConstant_01( [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is (int) {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_02() { UsingStatement($"_ = e is (int) or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_03() { UsingStatement($"_ = e is (int)or or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "or"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_04() { UsingStatement($"_ = e is (int) or or or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "or"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ConjunctiveFollowedByPropertyPattern_01() { UsingStatement(@"switch (e) { case {} and {}: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConjunctiveFollowedByTuplePattern_01() { UsingStatement(@"switch (e) { case {} and (): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_01() { UsingStatement(@"_ = e is (>= 1);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_02() { UsingStatement(@"_ = e switch { (>= 1) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_03() { UsingStatement(@"bool isAsciiLetter(char c) => c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z');", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.IdentifierToken, "isAsciiLetter"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.CharKeyword); } N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_04() { UsingStatement(@"_ = e is (<= 1, >= 2);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void AndPatternAssociativity_01() { UsingStatement(@"_ = e is A and B and C;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OrPatternAssociativity_01() { UsingStatement(@"_ = e is A or B or C;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(43960, "https://github.com/dotnet/roslyn/issues/43960")] public void NamespaceQualifiedEnumConstantInSwitchCase() { var source = @"switch (e) { case global::E.A: break; }"; UsingStatement(source, TestOptions.RegularWithPatternCombinators ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators ); verifyTree(); void verifyTree() { N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "E"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")] public void NamespaceQualifiedEnumConstantInIsPattern() { var source = @"_ = e is global::E.A;"; UsingStatement(source, TestOptions.RegularWithPatternCombinators ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "E"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(45757, "https://github.com/dotnet/roslyn/issues/45757")] public void IncompleteTuplePatternInPropertySubpattern() { var source = @"_ = this is Program { P1: (1, }"; var expectedErrors = new[] { // (1,32): error CS1026: ) expected // _ = this is Program { P1: (1, } Diagnostic(ErrorCode.ERR_CloseParenExpected, "}").WithLocation(1, 32), // (1,33): error CS1002: ; expected // _ = this is Program { P1: (1, } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 33) }; UsingStatement(source, TestOptions.RegularWithPatternCombinators, expectedErrors ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators, expectedErrors ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Program"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } } } M(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(45757, "https://github.com/dotnet/roslyn/issues/45757")] public void IncompleteTuplePattern() { var source = @"_ = i is (1, }"; var expectedErrors = new[] { // (1,1): error CS1073: Unexpected token '}' // _ = i is (1, } Diagnostic(ErrorCode.ERR_UnexpectedToken, "_ = i is (1, ").WithArguments("}").WithLocation(1, 1), // (1,16): error CS1026: ) expected // _ = i is (1, } Diagnostic(ErrorCode.ERR_CloseParenExpected, "}").WithLocation(1, 16), // (1,16): error CS1002: ; expected // _ = i is (1, } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(1, 16) }; UsingStatement(source, TestOptions.RegularWithPatternCombinators, expectedErrors ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators, expectedErrors ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseParenToken); } } } } M(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(47614, "https://github.com/dotnet/roslyn/issues/47614")] public void GenericTypeAsTypePatternInSwitchExpression() { UsingStatement(@"_ = e switch { List<X> => 1, List<Y> => 2, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "List"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "List"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_PredefinedType() { UsingStatement(@"_ = e switch { int? => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_PredefinedType() { UsingStatement(@"switch(a) { case int?: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_PredefinedType_Parenthesized() { UsingStatement(@"_ = e switch { (int?) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_PredefinedType_Parenthesized() { UsingStatement(@"switch(a) { case (int?): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression() { UsingStatement(@"_ = e switch { a? => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement() { UsingStatement(@"switch(a) { case a?: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_Parenthesized() { UsingStatement(@"_ = e switch { (a?) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_Parenthesized() { UsingStatement(@"switch(a) { case (a?): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchExpression() { UsingStatement(@"_ = e switch { (a?x:y) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchStatement() { UsingStatement(@"switch(a) { case a?x:y: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchStatement_Parenthesized() { UsingStatement(@"switch(a) { case (a?x:y): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/Core/xlf/EditorFeaturesResources.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="../EditorFeaturesResources.resx"> <body> <trans-unit id="All_methods"> <source>All methods</source> <target state="translated">Todos os métodos</target> <note /> </trans-unit> <trans-unit id="Always_for_clarity"> <source>Always for clarity</source> <target state="translated">Sempre para esclarecimento</target> <note /> </trans-unit> <trans-unit id="An_inline_rename_session_is_active_for_identifier_0"> <source>An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time.</source> <target state="translated">Uma sessão de renomeação embutida está ativa para o identificador '{0}'. Invoque a renomeação embutida novamente para acessar opções adicionais. Você pode continuar a editar o identificador que está sendo renomeado a qualquer momento.</target> <note>For screenreaders. {0} is the identifier being renamed.</note> </trans-unit> <trans-unit id="Applying_changes"> <source>Applying changes</source> <target state="translated">Aplicando mudanças</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters"> <source>Avoid unused parameters</source> <target state="translated">Evitar parâmetros não utilizados</target> <note /> </trans-unit> <trans-unit id="Change_configuration"> <source>Change configuration</source> <target state="translated">Alterar configuração</target> <note /> </trans-unit> <trans-unit id="Code_cleanup_is_not_configured"> <source>Code cleanup is not configured</source> <target state="translated">A limpeza de código não está configurada</target> <note /> </trans-unit> <trans-unit id="Configure_it_now"> <source>Configure it now</source> <target state="translated">Configurar agora</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_this_or_Me"> <source>Do not prefer 'this.' or 'Me.'</source> <target state="translated">Não preferir 'this.' nem 'Me'.</target> <note /> </trans-unit> <trans-unit id="Do_not_show_this_message_again"> <source>Do not show this message again</source> <target state="translated">Não mostrar esta mensagem novamente</target> <note /> </trans-unit> <trans-unit id="Do_you_still_want_to_proceed_This_may_produce_broken_code"> <source>Do you still want to proceed? This may produce broken code.</source> <target state="translated">Ainda quer continuar? Isso pode produzir código desfeito.</target> <note /> </trans-unit> <trans-unit id="Expander_display_text"> <source>items from unimported namespaces</source> <target state="translated">itens de namespaces não importados</target> <note /> </trans-unit> <trans-unit id="Expander_image_element"> <source>Expander</source> <target state="translated">Expansor</target> <note /> </trans-unit> <trans-unit id="Extract_method_encountered_the_following_issues"> <source>Extract method encountered the following issues:</source> <target state="translated">O método de extração encontrou os seguintes problemas:</target> <note /> </trans-unit> <trans-unit id="Filter_image_element"> <source>Filter</source> <target state="translated">Filtrar</target> <note>Caption/tooltip for "Filter" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="For_locals_parameters_and_members"> <source>For locals, parameters and members</source> <target state="translated">Para locais, parâmetros e membros</target> <note /> </trans-unit> <trans-unit id="For_member_access_expressions"> <source>For member access expressions</source> <target state="translated">Para expressões de acesso de membro</target> <note /> </trans-unit> <trans-unit id="Format_document_performed_additional_cleanup"> <source>Format Document performed additional cleanup</source> <target state="translated">A Formatação do Documento executou uma limpeza adicional</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0"> <source>Get help for '{0}'</source> <target state="translated">Obter ajuda para '{0}'</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0_from_Bing"> <source>Get help for '{0}' from Bing</source> <target state="translated">Obter ajuda para o '{0}' do Bing</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_0"> <source>Gathering Suggestions - '{0}'</source> <target state="translated">Obtendo Sugestões – '{0}'</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_Waiting_for_the_solution_to_fully_load"> <source>Gathering Suggestions - Waiting for the solution to fully load</source> <target state="translated">Obtendo Sugestões – aguardando a solução carregar totalmente</target> <note /> </trans-unit> <trans-unit id="Go_To_Base"> <source>Go To Base</source> <target state="translated">Ir Para a Base</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators</source> <target state="translated">Em operadores aritméticos</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators</source> <target state="translated">Em outros operadores binários</target> <note /> </trans-unit> <trans-unit id="In_other_operators"> <source>In other operators</source> <target state="translated">Em outros operadores</target> <note /> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators</source> <target state="translated">Em operadores relacionais</target> <note /> </trans-unit> <trans-unit id="Indentation_Size"> <source>Indentation Size</source> <target state="translated">Tamanho do Recuo</target> <note /> </trans-unit> <trans-unit id="Inline_Hints"> <source>Inline Hints</source> <target state="translated">Dicas Embutidas</target> <note /> </trans-unit> <trans-unit id="Insert_Final_Newline"> <source>Insert Final Newline</source> <target state="translated">Inserir Nova Linha Final</target> <note /> </trans-unit> <trans-unit id="Invalid_assembly_name"> <source>Invalid assembly name</source> <target state="translated">Nome do assembly inválido</target> <note /> </trans-unit> <trans-unit id="Invalid_characters_in_assembly_name"> <source>Invalid characters in assembly name</source> <target state="translated">Caracteres inválidos no nome do assembly</target> <note /> </trans-unit> <trans-unit id="Keyword_Control"> <source>Keyword - Control</source> <target state="translated">Palavra-chave – Controle</target> <note /> </trans-unit> <trans-unit id="Locating_bases"> <source>Locating bases...</source> <target state="translated">Localizando as bases...</target> <note /> </trans-unit> <trans-unit id="Never_if_unnecessary"> <source>Never if unnecessary</source> <target state="translated">Nunca se desnecessário</target> <note /> </trans-unit> <trans-unit id="New_Line"> <source>New Line</source> <target state="translated">Nova Linha</target> <note /> </trans-unit> <trans-unit id="No"> <source>No</source> <target state="translated">Não</target> <note /> </trans-unit> <trans-unit id="Non_public_methods"> <source>Non-public methods</source> <target state="translated">Métodos não públicos</target> <note /> </trans-unit> <trans-unit id="Operator_Overloaded"> <source>Operator - Overloaded</source> <target state="translated">Operador – Sobrecarregado</target> <note /> </trans-unit> <trans-unit id="Paste_Tracking"> <source>Paste Tracking</source> <target state="translated">Colar Acompanhamento</target> <note /> </trans-unit> <trans-unit id="Prefer_System_HashCode_in_GetHashCode"> <source>Prefer 'System.HashCode' in 'GetHashCode'</source> <target state="translated">Prefira 'System.HashCode' em 'GetHashCode'</target> <note /> </trans-unit> <trans-unit id="Prefer_coalesce_expression"> <source>Prefer coalesce expression</source> <target state="translated">Preferir a expressão de união</target> <note /> </trans-unit> <trans-unit id="Prefer_collection_initializer"> <source>Prefer collection initializer</source> <target state="translated">Preferir o inicializador de coleção</target> <note /> </trans-unit> <trans-unit id="Prefer_compound_assignments"> <source>Prefer compound assignments</source> <target state="translated">Preferir atribuições de compostos</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_assignments"> <source>Prefer conditional expression over 'if' with assignments</source> <target state="translated">Preferir expressão condicional em vez de 'if' com atribuições</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_returns"> <source>Prefer conditional expression over 'if' with returns</source> <target state="translated">Preferir expressão condicional em vez de 'if' com retornos</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_tuple_name"> <source>Prefer explicit tuple name</source> <target state="translated">Preferir nome de tupla explícito</target> <note /> </trans-unit> <trans-unit id="Prefer_framework_type"> <source>Prefer framework type</source> <target state="translated">Preferir tipo de estrutura</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_anonymous_type_member_names"> <source>Prefer inferred anonymous type member names</source> <target state="translated">Prefira usar nomes de membro inferidos do tipo anônimo</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_tuple_names"> <source>Prefer inferred tuple element names</source> <target state="translated">Preferir usar nomes de elementos inferidos de tupla</target> <note /> </trans-unit> <trans-unit id="Prefer_is_null_for_reference_equality_checks"> <source>Prefer 'is null' for reference equality checks</source> <target state="translated">Preferir 'is null' para as verificações de igualdade de referência</target> <note /> </trans-unit> <trans-unit id="Prefer_null_propagation"> <source>Prefer null propagation</source> <target state="translated">Preferir tratamento simplificado de nulo</target> <note /> </trans-unit> <trans-unit id="Prefer_object_initializer"> <source>Prefer object initializer</source> <target state="translated">Preferir inicializador de objeto</target> <note /> </trans-unit> <trans-unit id="Prefer_predefined_type"> <source>Prefer predefined type</source> <target state="translated">Preferir tipo predefinido</target> <note /> </trans-unit> <trans-unit id="Prefer_readonly_fields"> <source>Prefer readonly fields</source> <target state="translated">Preferir campos readonly</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_boolean_expressions"> <source>Prefer simplified boolean expressions</source> <target state="translated">Preferir expressões boolianas simplificadas</target> <note /> </trans-unit> <trans-unit id="Prefer_this_or_Me"> <source>Prefer 'this.' or 'Me.'</source> <target state="translated">Preferir 'this.' ou 'Me.'</target> <note /> </trans-unit> <trans-unit id="Preprocessor_Text"> <source>Preprocessor Text</source> <target state="translated">Texto de Pré-Processador</target> <note /> </trans-unit> <trans-unit id="Punctuation"> <source>Punctuation</source> <target state="translated">Pontuação</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_this_or_Me"> <source>Qualify event access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de evento com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_this_or_Me"> <source>Qualify field access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de campo com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_this_or_Me"> <source>Qualify method access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de método com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_this_or_Me"> <source>Qualify property access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de propriedade com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Reassigned_variable"> <source>Reassigned variable</source> <target state="new">Reassigned variable</target> <note /> </trans-unit> <trans-unit id="Rename_file_name_doesnt_match"> <source>Rename _file (type does not match file name)</source> <target state="translated">Renomear _arquivo (o tipo não corresponde ao nome do arquivo)</target> <note /> </trans-unit> <trans-unit id="Rename_file_partial_type"> <source>Rename _file (not allowed on partial types)</source> <target state="translated">Renomear _arquivo (não permitido em tipos parciais)</target> <note>Disabled text status for file rename</note> </trans-unit> <trans-unit id="Rename_symbols_file"> <source>Rename symbol's _file</source> <target state="translated">Renomear o _arquivo do símbolo</target> <note>Indicates that the file a symbol is defined in will also be renamed</note> </trans-unit> <trans-unit id="Split_comment"> <source>Split comment</source> <target state="translated">Dividir o comentário</target> <note /> </trans-unit> <trans-unit id="String_Escape_Character"> <source>String - Escape Character</source> <target state="translated">String - caractere de Escape</target> <note /> </trans-unit> <trans-unit id="Symbol_Static"> <source>Symbol - Static</source> <target state="translated">Símbolo – Estático</target> <note /> </trans-unit> <trans-unit id="Tab_Size"> <source>Tab Size</source> <target state="translated">Tamanho da Tabulação</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_base"> <source>The symbol has no base.</source> <target state="translated">O símbolo não tem nenhuma base.</target> <note /> </trans-unit> <trans-unit id="Toggle_Block_Comment"> <source>Toggle Block Comment</source> <target state="translated">Ativar/Desativar Comentário de Bloco</target> <note /> </trans-unit> <trans-unit id="Toggle_Line_Comment"> <source>Toggle Line Comment</source> <target state="translated">Ativar/Desativar Comentário de Linha</target> <note /> </trans-unit> <trans-unit id="Toggling_block_comment"> <source>Toggling block comment...</source> <target state="translated">Ativando/desativando o comentário de bloco...</target> <note /> </trans-unit> <trans-unit id="Toggling_line_comment"> <source>Toggling line comment...</source> <target state="translated">Ativando/desativando o comentário de linha...</target> <note /> </trans-unit> <trans-unit id="Use_Tabs"> <source>Use Tabs</source> <target state="translated">Usar Tabulações</target> <note /> </trans-unit> <trans-unit id="User_Members_Constants"> <source>User Members - Constants</source> <target state="translated">Membros de Usuário – Constantes</target> <note /> </trans-unit> <trans-unit id="User_Members_Enum_Members"> <source>User Members - Enum Members</source> <target state="translated">Membros de Usuário – Membros Enum</target> <note /> </trans-unit> <trans-unit id="User_Members_Events"> <source>User Members - Events</source> <target state="translated">Membros de Usuário – Eventos</target> <note /> </trans-unit> <trans-unit id="User_Members_Extension_Methods"> <source>User Members - Extension Methods</source> <target state="translated">Membros de Usuário – Métodos de Extensão</target> <note /> </trans-unit> <trans-unit id="User_Members_Fields"> <source>User Members - Fields</source> <target state="translated">Membros de Usuário – Campos</target> <note /> </trans-unit> <trans-unit id="User_Members_Labels"> <source>User Members - Labels</source> <target state="translated">Membros de Usuário – Rótulos</target> <note /> </trans-unit> <trans-unit id="User_Members_Locals"> <source>User Members - Locals</source> <target state="translated">Membros de Usuário – Locais</target> <note /> </trans-unit> <trans-unit id="User_Members_Methods"> <source>User Members - Methods</source> <target state="translated">Membros de Usuário – Métodos</target> <note /> </trans-unit> <trans-unit id="User_Members_Namespaces"> <source>User Members - Namespaces</source> <target state="translated">Membros de Usuário – Namespaces</target> <note /> </trans-unit> <trans-unit id="User_Members_Parameters"> <source>User Members - Parameters</source> <target state="translated">Membros de Usuário – Parâmetros</target> <note /> </trans-unit> <trans-unit id="User_Members_Properties"> <source>User Members - Properties</source> <target state="translated">Membros de Usuário – Propriedades</target> <note /> </trans-unit> <trans-unit id="User_Types_Classes"> <source>User Types - Classes</source> <target state="translated">Tipos de Usuário - Classes</target> <note /> </trans-unit> <trans-unit id="User_Types_Delegates"> <source>User Types - Delegates</source> <target state="translated">Tipos de Usuário - Representantes</target> <note /> </trans-unit> <trans-unit id="User_Types_Enums"> <source>User Types - Enums</source> <target state="translated">Tipos de Usuário - Enums</target> <note /> </trans-unit> <trans-unit id="User_Types_Interfaces"> <source>User Types - Interfaces</source> <target state="translated">Tipos de Usuário - Interfaces</target> <note /> </trans-unit> <trans-unit id="User_Types_Record_Structs"> <source>User Types - Record Structs</source> <target state="translated">Tipos de usuário - Registro de structs</target> <note /> </trans-unit> <trans-unit id="User_Types_Records"> <source>User Types - Records</source> <target state="translated">Tipos de Usuário – Registros</target> <note /> </trans-unit> <trans-unit id="User_Types_Structures"> <source>User Types - Structures</source> <target state="translated">Tipos de Usuário - Estruturas</target> <note /> </trans-unit> <trans-unit id="User_Types_Type_Parameters"> <source>User Types - Type Parameters</source> <target state="translated">Tipos de Usuário - Parâmetros de Tipo</target> <note /> </trans-unit> <trans-unit id="String_Verbatim"> <source>String - Verbatim</source> <target state="translated">Cadeia de caracteres - Textual</target> <note /> </trans-unit> <trans-unit id="Waiting_for_background_work_to_finish"> <source>Waiting for background work to finish...</source> <target state="translated">Aguardando a conclusão do trabalho em segundo plano...</target> <note /> </trans-unit> <trans-unit id="Warning_image_element"> <source>Warning</source> <target state="translated">Aviso</target> <note>Caption/tooltip for "Warning" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Name"> <source>XML Doc Comments - Attribute Name</source> <target state="translated">Comentário da documentação XML - Nome de Atributo</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_CData_Section"> <source>XML Doc Comments - CData Section</source> <target state="translated">Comentário da documentação XML - Seção CData</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Text"> <source>XML Doc Comments - Text</source> <target state="translated">Comentário da documentação XML - Texto</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Delimiter"> <source>XML Doc Comments - Delimiter</source> <target state="translated">Comentário da documentação XML - Delimitador</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Comment"> <source>XML Doc Comments - Comment</source> <target state="translated">Comentário da documentação XML - Comentário</target> <note /> </trans-unit> <trans-unit id="User_Types_Modules"> <source>User Types - Modules</source> <target state="translated">Tipos de Usuário - Módulos</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Name"> <source>VB XML Literals - Attribute Name</source> <target state="translated">Literais XML do VB - Nome de Atributo</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Quotes"> <source>VB XML Literals - Attribute Quotes</source> <target state="translated">Literais XML do VB - Aspas de Atributo</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Value"> <source>VB XML Literals - Attribute Value</source> <target state="translated">Literais XML do VB - Valor de Atributo</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_CData_Section"> <source>VB XML Literals - CData Section</source> <target state="translated">Literais XML do VB - Seção CData</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Comment"> <source>VB XML Literals - Comment</source> <target state="translated">Literais XML do VB - Comentário</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Delimiter"> <source>VB XML Literals - Delimiter</source> <target state="translated">Literais XML do VB - Delimitador</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Embedded_Expression"> <source>VB XML Literals - Embedded Expression</source> <target state="translated">Literais XML do VB - Expressão Inserida</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Entity_Reference"> <source>VB XML Literals - Entity Reference</source> <target state="translated">Literais XML do VB - Referência de Entidade</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Name"> <source>VB XML Literals - Name</source> <target state="translated">Literais XML do VB - Nome</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Processing_Instruction"> <source>VB XML Literals - Processing Instruction</source> <target state="translated">Literais XML do VB - Instrução de Processamento</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Text"> <source>VB XML Literals - Text</source> <target state="translated">Literais XML do VB - Texto</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Quotes"> <source>XML Doc Comments - Attribute Quotes</source> <target state="translated">Comentário da documentação XML - Aspas de Atributo</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Value"> <source>XML Doc Comments - Attribute Value</source> <target state="translated">Comentário da documentação XML - Valor de Atributo</target> <note /> </trans-unit> <trans-unit id="Unnecessary_Code"> <source>Unnecessary Code</source> <target state="translated">Código Desnecessário</target> <note /> </trans-unit> <trans-unit id="Rude_Edit"> <source>Rude Edit</source> <target state="translated">Edição Rudimentar</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_1_reference_in_1_file"> <source>Rename will update 1 reference in 1 file.</source> <target state="translated">Renomear atualizará 1 referência em 1 arquivo.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_file"> <source>Rename will update {0} references in 1 file.</source> <target state="translated">Renomear atualizará {0} referências em 1 arquivo.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_files"> <source>Rename will update {0} references in {1} files.</source> <target state="translated">Renomear atualizará {0} referências em {1} arquivos.</target> <note /> </trans-unit> <trans-unit id="Yes"> <source>Yes</source> <target state="translated">Sim</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_contained_in_a_read_only_file"> <source>You cannot rename this element because it is contained in a read-only file.</source> <target state="translated">Você não pode renomear este elemento porque ele está contido em um arquivo somente leitura.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_in_a_location_that_cannot_be_navigated_to"> <source>You cannot rename this element because it is in a location that cannot be navigated to.</source> <target state="translated">Você não pode renomear este elemento porque ele está em um local para o qual não é possível navegar.</target> <note /> </trans-unit> <trans-unit id="_0_bases"> <source>'{0}' bases</source> <target state="translated">Bases '{0}'</target> <note /> </trans-unit> <trans-unit id="_0_conflict_s_will_be_resolved"> <source>{0} conflict(s) will be resolved</source> <target state="translated">{0} conflito(s) será(ão) resolvido(s)</target> <note /> </trans-unit> <trans-unit id="_0_implemented_members"> <source>'{0}' implemented members</source> <target state="translated">'{0}' membros implementados</target> <note /> </trans-unit> <trans-unit id="_0_unresolvable_conflict_s"> <source>{0} unresolvable conflict(s)</source> <target state="translated">{0} conflito(s) não solucionável(is)</target> <note /> </trans-unit> <trans-unit id="Applying_0"> <source>Applying "{0}"...</source> <target state="translated">Aplicando "{0}"...</target> <note /> </trans-unit> <trans-unit id="Adding_0_to_1_with_content_colon"> <source>Adding '{0}' to '{1}' with content:</source> <target state="translated">Adicionando "{0}" a "{1}" com conteúdo:</target> <note /> </trans-unit> <trans-unit id="Adding_project_0"> <source>Adding project '{0}'</source> <target state="translated">Adicionando projeto "{0}"</target> <note /> </trans-unit> <trans-unit id="Removing_project_0"> <source>Removing project '{0}'</source> <target state="translated">Removendo projeto "{0}"</target> <note /> </trans-unit> <trans-unit id="Changing_project_references_for_0"> <source>Changing project references for '{0}'</source> <target state="translated">Alterar referências de projeto para "{0}"</target> <note /> </trans-unit> <trans-unit id="Adding_reference_0_to_1"> <source>Adding reference '{0}' to '{1}'</source> <target state="translated">Adicionando referência "{0}" a "{1}"</target> <note /> </trans-unit> <trans-unit id="Removing_reference_0_from_1"> <source>Removing reference '{0}' from '{1}'</source> <target state="translated">Removendo referência "{0}" de "{1}"</target> <note /> </trans-unit> <trans-unit id="Adding_analyzer_reference_0_to_1"> <source>Adding analyzer reference '{0}' to '{1}'</source> <target state="translated">Adicionando referência de analisador "{0}" a "{1}"</target> <note /> </trans-unit> <trans-unit id="Removing_analyzer_reference_0_from_1"> <source>Removing analyzer reference '{0}' from '{1}'</source> <target state="translated">Removendo referência do analisador "{0}" de "{1}"</target> <note /> </trans-unit> <trans-unit id="XML_End_Tag_Completion"> <source>XML End Tag Completion</source> <target state="translated">Conclusão da Marca de Fim do XML</target> <note /> </trans-unit> <trans-unit id="Completing_Tag"> <source>Completing Tag</source> <target state="translated">Completando a Tag</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field"> <source>Encapsulate Field</source> <target state="translated">Encapsular Campo</target> <note /> </trans-unit> <trans-unit id="Applying_Encapsulate_Field_refactoring"> <source>Applying "Encapsulate Field" refactoring...</source> <target state="translated">Aplicando refatoração "Encapsular Campo"...</target> <note /> </trans-unit> <trans-unit id="Please_select_the_definition_of_the_field_to_encapsulate"> <source>Please select the definition of the field to encapsulate.</source> <target state="translated">Selecione a definição do campo a encapsular.</target> <note /> </trans-unit> <trans-unit id="Given_Workspace_doesn_t_support_Undo"> <source>Given Workspace doesn't support Undo</source> <target state="translated">Workspace fornecido não suporta Desfazer</target> <note /> </trans-unit> <trans-unit id="Searching"> <source>Searching...</source> <target state="translated">Pesquisando...</target> <note /> </trans-unit> <trans-unit id="Canceled"> <source>Canceled.</source> <target state="translated">Cancelado.</target> <note /> </trans-unit> <trans-unit id="No_information_found"> <source>No information found.</source> <target state="translated">Nenhuma informação encontrada.</target> <note /> </trans-unit> <trans-unit id="No_usages_found"> <source>No usages found.</source> <target state="translated">Nenhum uso encontrado.</target> <note /> </trans-unit> <trans-unit id="Implements_"> <source>Implements</source> <target state="translated">Implementos</target> <note /> </trans-unit> <trans-unit id="Implemented_By"> <source>Implemented By</source> <target state="translated">Implementado por</target> <note /> </trans-unit> <trans-unit id="Overrides_"> <source>Overrides</source> <target state="translated">Substitui</target> <note /> </trans-unit> <trans-unit id="Overridden_By"> <source>Overridden By</source> <target state="translated">Substituído por</target> <note /> </trans-unit> <trans-unit id="Directly_Called_In"> <source>Directly Called In</source> <target state="translated">Chamado Diretamente</target> <note /> </trans-unit> <trans-unit id="Indirectly_Called_In"> <source>Indirectly Called In</source> <target state="translated">Chamado Indiretamente </target> <note /> </trans-unit> <trans-unit id="Called_In"> <source>Called In</source> <target state="translated">Chamado Em</target> <note /> </trans-unit> <trans-unit id="Referenced_In"> <source>Referenced In</source> <target state="translated">Referenciado Em</target> <note /> </trans-unit> <trans-unit id="No_references_found"> <source>No references found.</source> <target state="translated">Nenhuma referência encontrada.</target> <note /> </trans-unit> <trans-unit id="No_derived_types_found"> <source>No derived types found.</source> <target state="translated">Nenhum tipo derivado encontrado.</target> <note /> </trans-unit> <trans-unit id="No_implementations_found"> <source>No implementations found.</source> <target state="translated">Nenhuma implementação encontrada.</target> <note /> </trans-unit> <trans-unit id="_0_Line_1"> <source>{0} - (Line {1})</source> <target state="translated">{0} - (Linha {1})</target> <note /> </trans-unit> <trans-unit id="Class_Parts"> <source>Class Parts</source> <target state="translated">Partes de Classe</target> <note /> </trans-unit> <trans-unit id="Struct_Parts"> <source>Struct Parts</source> <target state="translated">Partes de Struct</target> <note /> </trans-unit> <trans-unit id="Interface_Parts"> <source>Interface Parts</source> <target state="translated">Componentes da Interface</target> <note /> </trans-unit> <trans-unit id="Type_Parts"> <source>Type Parts</source> <target state="translated">Partes do Tipo</target> <note /> </trans-unit> <trans-unit id="Inherits_"> <source>Inherits</source> <target state="translated">Herda</target> <note /> </trans-unit> <trans-unit id="Inherited_By"> <source>Inherited By</source> <target state="translated">Herdado por</target> <note /> </trans-unit> <trans-unit id="Already_tracking_document_with_identical_key"> <source>Already tracking document with identical key</source> <target state="translated">Já está a rastrear o documento com chave idêntica</target> <note /> </trans-unit> <trans-unit id="analyzer_Prefer_auto_properties"> <source>Prefer auto properties</source> <target state="translated">Preferir propriedades automáticas</target> <note /> </trans-unit> <trans-unit id="document_is_not_currently_being_tracked"> <source>document is not currently being tracked</source> <target state="translated">documento não está sendo rastreado no momento</target> <note /> </trans-unit> <trans-unit id="Computing_Rename_information"> <source>Computing Rename information...</source> <target state="translated">Computando informações de Renomeação...</target> <note /> </trans-unit> <trans-unit id="Updating_files"> <source>Updating files...</source> <target state="translated">Atualizando arquivos...</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_cancelled_or_is_not_valid"> <source>Rename operation was cancelled or is not valid</source> <target state="translated">A operação de renomear foi cancelada ou não é válida</target> <note /> </trans-unit> <trans-unit id="Rename_Symbol"> <source>Rename Symbol</source> <target state="translated">Renomear Símbolo</target> <note /> </trans-unit> <trans-unit id="Text_Buffer_Change"> <source>Text Buffer Change</source> <target state="translated">Alteração no Buffer de Texto</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_not_properly_completed_Some_file_might_not_have_been_updated"> <source>Rename operation was not properly completed. Some file might not have been updated.</source> <target state="translated">A operação de renomear não foi corretamente concluída. Algum arquivo pode não ter sido atualizado.</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename '{0}' to '{1}'</source> <target state="translated">Renomear "{0}" para "{1}"</target> <note /> </trans-unit> <trans-unit id="Preview_Warning"> <source>Preview Warning</source> <target state="translated">Aviso de Visualização</target> <note /> </trans-unit> <trans-unit id="external"> <source>(external)</source> <target state="translated">(externo)</target> <note /> </trans-unit> <trans-unit id="Automatic_Line_Ender"> <source>Automatic Line Ender</source> <target state="translated">Finalizador de Linha Automático</target> <note /> </trans-unit> <trans-unit id="Automatically_completing"> <source>Automatically completing...</source> <target state="translated">Concluindo automaticamente...</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion"> <source>Automatic Pair Completion</source> <target state="translated">Conclusão de Pares Automática</target> <note /> </trans-unit> <trans-unit id="An_active_inline_rename_session_is_still_active_Complete_it_before_starting_a_new_one"> <source>An active inline rename session is still active. Complete it before starting a new one.</source> <target state="translated">Uma sessão de renomeação embutida ativa ainda está ativa. Conclua-a antes de iniciar uma nova.</target> <note /> </trans-unit> <trans-unit id="The_buffer_is_not_part_of_a_workspace"> <source>The buffer is not part of a workspace.</source> <target state="translated">O buffer não é parte de um workspace.</target> <note /> </trans-unit> <trans-unit id="The_token_is_not_contained_in_the_workspace"> <source>The token is not contained in the workspace.</source> <target state="translated">O token não está contido no workspace.</target> <note /> </trans-unit> <trans-unit id="You_must_rename_an_identifier"> <source>You must rename an identifier.</source> <target state="translated">Você deve renomear um identificador.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element"> <source>You cannot rename this element.</source> <target state="translated">Você não pode renomear este elemento.</target> <note /> </trans-unit> <trans-unit id="Please_resolve_errors_in_your_code_before_renaming_this_element"> <source>Please resolve errors in your code before renaming this element.</source> <target state="translated">Resolva erros em seu código antes de renomear este elemento.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_operators"> <source>You cannot rename operators.</source> <target state="translated">Você não pode renomear operadores.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_that_are_defined_in_metadata"> <source>You cannot rename elements that are defined in metadata.</source> <target state="translated">Você não pode renomear elementos que estão definidos nos metadados.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_from_previous_submissions"> <source>You cannot rename elements from previous submissions.</source> <target state="translated">Você não pode renomear elementos de envios anteriores.</target> <note /> </trans-unit> <trans-unit id="Navigation_Bars"> <source>Navigation Bars</source> <target state="translated">Barras de Navegação</target> <note /> </trans-unit> <trans-unit id="Refreshing_navigation_bars"> <source>Refreshing navigation bars...</source> <target state="translated">Atualizando barras de navegação...</target> <note /> </trans-unit> <trans-unit id="Format_Token"> <source>Format Token</source> <target state="translated">Token de Formato</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">Recuo Inteligente</target> <note /> </trans-unit> <trans-unit id="Find_References"> <source>Find References</source> <target state="translated">Localizar Referências</target> <note /> </trans-unit> <trans-unit id="Finding_references"> <source>Finding references...</source> <target state="translated">Localizando referências...</target> <note /> </trans-unit> <trans-unit id="Finding_references_of_0"> <source>Finding references of "{0}"...</source> <target state="translated">Localizando referências de "{0}"...</target> <note /> </trans-unit> <trans-unit id="Comment_Selection"> <source>Comment Selection</source> <target state="translated">Comentar Seleção</target> <note /> </trans-unit> <trans-unit id="Uncomment_Selection"> <source>Uncomment Selection</source> <target state="translated">Remover Comentários da Seleção</target> <note /> </trans-unit> <trans-unit id="Commenting_currently_selected_text"> <source>Commenting currently selected text...</source> <target state="translated">Comentando o texto selecionado no momento...</target> <note /> </trans-unit> <trans-unit id="Uncommenting_currently_selected_text"> <source>Uncommenting currently selected text...</source> <target state="translated">Removendo marca de comentário do texto selecionado no momento...</target> <note /> </trans-unit> <trans-unit id="Insert_new_line"> <source>Insert new line</source> <target state="translated">Inserir Nova Linha</target> <note /> </trans-unit> <trans-unit id="Documentation_Comment"> <source>Documentation Comment</source> <target state="translated">Comentário de Documentação</target> <note /> </trans-unit> <trans-unit id="Inserting_documentation_comment"> <source>Inserting documentation comment...</source> <target state="translated">Inserindo comentário da documentação...</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="Applying_Extract_Method_refactoring"> <source>Applying "Extract Method" refactoring...</source> <target state="translated">Aplicando refatoração "Extrair Método"...</target> <note /> </trans-unit> <trans-unit id="Format_Document"> <source>Format Document</source> <target state="translated">Formatar 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="Formatting"> <source>Formatting</source> <target state="translated">Formatação</target> <note /> </trans-unit> <trans-unit id="Format_Selection"> <source>Format Selection</source> <target state="translated">Formatar Seleção</target> <note /> </trans-unit> <trans-unit id="Formatting_currently_selected_text"> <source>Formatting currently selected text...</source> <target state="translated">Formatando texto selecionado no momento...</target> <note /> </trans-unit> <trans-unit id="Cannot_navigate_to_the_symbol_under_the_caret"> <source>Cannot navigate to the symbol under the caret.</source> <target state="translated">Não é possível navegar para o símbolo sob o cursor.</target> <note /> </trans-unit> <trans-unit id="Go_to_Definition"> <source>Go to Definition</source> <target state="translated">Ir para Definição</target> <note /> </trans-unit> <trans-unit id="Navigating_to_definition"> <source>Navigating to definition...</source> <target state="translated">Navegando para definição...</target> <note /> </trans-unit> <trans-unit id="Organize_Document"> <source>Organize Document</source> <target state="translated">Organizar Documento</target> <note /> </trans-unit> <trans-unit id="Organizing_document"> <source>Organizing document...</source> <target state="translated">Organizando documento...</target> <note /> </trans-unit> <trans-unit id="Highlighted_Definition"> <source>Highlighted Definition</source> <target state="translated">Definição Realçada</target> <note /> </trans-unit> <trans-unit id="The_new_name_is_not_a_valid_identifier"> <source>The new name is not a valid identifier.</source> <target state="translated">O novo nome não é um identificador válido.</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Fixup"> <source>Inline Rename Fixup</source> <target state="translated">Correção de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Resolved_Conflict"> <source>Inline Rename Resolved Conflict</source> <target state="translated">Conflito de Renomeação Embutida Resolvido </target> <note /> </trans-unit> <trans-unit id="Inline_Rename"> <source>Inline Rename</source> <target state="translated">Renomeação embutida</target> <note /> </trans-unit> <trans-unit id="Rename"> <source>Rename</source> <target state="translated">renomear</target> <note /> </trans-unit> <trans-unit id="Start_Rename"> <source>Start Rename</source> <target state="translated">Iniciar Renomeação</target> <note /> </trans-unit> <trans-unit id="Display_conflict_resolutions"> <source>Display conflict resolutions</source> <target state="translated">Exibir resoluções de conflitos</target> <note /> </trans-unit> <trans-unit id="Finding_token_to_rename"> <source>Finding token to rename...</source> <target state="translated">Localizando token para renomear...</target> <note /> </trans-unit> <trans-unit id="Conflict"> <source>Conflict</source> <target state="translated">Conflito</target> <note /> </trans-unit> <trans-unit id="Text_Navigation"> <source>Text Navigation</source> <target state="translated">Navegação de Texto</target> <note /> </trans-unit> <trans-unit id="Finding_word_extent"> <source>Finding word extent...</source> <target state="translated">Localizando de extensão de palavra...</target> <note /> </trans-unit> <trans-unit id="Finding_enclosing_span"> <source>Finding enclosing span...</source> <target state="translated">Localizando alcance de delimitação...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_next_sibling"> <source>Finding span of next sibling...</source> <target state="translated">Localizando a extensão do próximo irmão...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_previous_sibling"> <source>Finding span of previous sibling...</source> <target state="translated">Localizando a extensão do irmão anterior...</target> <note /> </trans-unit> <trans-unit id="Rename_colon_0"> <source>Rename: {0}</source> <target state="translated">Renomear: {0}</target> <note /> </trans-unit> <trans-unit id="Light_bulb_session_is_already_dismissed"> <source>Light bulb session is already dismissed.</source> <target state="translated">A sessão de lâmpada já foi descartada.</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion_End_Point_Marker_Color"> <source>Automatic Pair Completion End Point Marker Color</source> <target state="translated">Cor do Marcador de Ponto Final da Conclusão de Pares Automática</target> <note /> </trans-unit> <trans-unit id="Renaming_anonymous_type_members_is_not_yet_supported"> <source>Renaming anonymous type members is not yet supported.</source> <target state="translated">Renomear membros de tipo anônimo ainda não é suportado.</target> <note /> </trans-unit> <trans-unit id="Engine_must_be_attached_to_an_Interactive_Window"> <source>Engine must be attached to an Interactive Window.</source> <target state="translated">O Mecanismo deve ser anexado a uma Janela Interativa.</target> <note /> </trans-unit> <trans-unit id="Changes_the_current_prompt_settings"> <source>Changes the current prompt settings.</source> <target state="translated">Altera as configurações de prompt atuais.</target> <note /> </trans-unit> <trans-unit id="Unexpected_text_colon_0"> <source>Unexpected text: '{0}'</source> <target state="translated">Texto inesperado: "{0}"</target> <note /> </trans-unit> <trans-unit id="The_triggerSpan_is_not_included_in_the_given_workspace"> <source>The triggerSpan is not included in the given workspace.</source> <target state="translated">O triggerSpan não está incluído no workspace fornecido.</target> <note /> </trans-unit> <trans-unit id="This_session_has_already_been_dismissed"> <source>This session has already been dismissed.</source> <target state="translated">Esta sessão já foi descartada.</target> <note /> </trans-unit> <trans-unit id="The_transaction_is_already_complete"> <source>The transaction is already complete.</source> <target state="translated">A transação já está concluída.</target> <note /> </trans-unit> <trans-unit id="Not_a_source_error_line_column_unavailable"> <source>Not a source error, line/column unavailable</source> <target state="translated">Não é um erro de origem, linha/coluna disponível</target> <note /> </trans-unit> <trans-unit id="Can_t_compare_positions_from_different_text_snapshots"> <source>Can't compare positions from different text snapshots</source> <target state="translated">Não é possível comparar as posições de instantâneos de textos diferentes</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Entity_Reference"> <source>XML Doc Comments - Entity Reference</source> <target state="translated">Comentário da documentação XML - Referência de Entidade</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Name"> <source>XML Doc Comments - Name</source> <target state="translated">Comentário da documentação XML - Nome</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Processing_Instruction"> <source>XML Doc Comments - Processing Instruction</source> <target state="translated">Comentário da documentação XML - Instrução de Processamento</target> <note /> </trans-unit> <trans-unit id="Active_Statement"> <source>Active Statement</source> <target state="translated">Instrução Ativa</target> <note /> </trans-unit> <trans-unit id="Loading_Peek_information"> <source>Loading Peek information...</source> <target state="translated">Carregando informações de Espiada...</target> <note /> </trans-unit> <trans-unit id="Peek"> <source>Peek</source> <target state="translated">Espiada</target> <note /> </trans-unit> <trans-unit id="Apply1"> <source>_Apply</source> <target state="translated">_Aplicar</target> <note /> </trans-unit> <trans-unit id="Include_overload_s"> <source>Include _overload(s)</source> <target state="translated">Incluir _overload(s)</target> <note /> </trans-unit> <trans-unit id="Include_comments"> <source>Include _comments</source> <target state="translated">Incluir _comments</target> <note /> </trans-unit> <trans-unit id="Include_strings"> <source>Include _strings</source> <target state="translated">Incluir _strings</target> <note /> </trans-unit> <trans-unit id="Apply2"> <source>Apply</source> <target state="translated">Aplicar</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="Preview_Changes_0"> <source>Preview Changes - {0}</source> <target state="translated">Visualizar Alterações - {0}</target> <note /> </trans-unit> <trans-unit id="Preview_Code_Changes_colon"> <source>Preview Code Changes:</source> <target state="translated">Visualizar Alterações de Código:</target> <note /> </trans-unit> <trans-unit id="Preview_Changes"> <source>Preview Changes</source> <target state="translated">Visualizar Alterações</target> <note /> </trans-unit> <trans-unit id="Format_Paste"> <source>Format Paste</source> <target state="translated">Colar Formato</target> <note /> </trans-unit> <trans-unit id="Formatting_pasted_text"> <source>Formatting pasted text...</source> <target state="translated">Formatando texto colado...</target> <note /> </trans-unit> <trans-unit id="The_definition_of_the_object_is_hidden"> <source>The definition of the object is hidden.</source> <target state="translated">A definição do objeto está oculta.</target> <note /> </trans-unit> <trans-unit id="Automatic_Formatting"> <source>Automatic Formatting</source> <target state="translated">Formatação Automática</target> <note /> </trans-unit> <trans-unit id="We_can_fix_the_error_by_not_making_struct_out_ref_parameter_s_Do_you_want_to_proceed"> <source>We can fix the error by not making struct "out/ref" parameter(s). Do you want to proceed?</source> <target state="translated">Podemos corrigir o erro ao não fazer struct de parâmetro(s) "out/ref". Deseja continuar?</target> <note /> </trans-unit> <trans-unit id="Change_Signature_colon"> <source>Change Signature:</source> <target state="translated">Alterar Assinatura:</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1_colon"> <source>Rename '{0}' to '{1}':</source> <target state="translated">Renomear '{0}' para '{1}':</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field_colon"> <source>Encapsulate Field:</source> <target state="translated">Encapsular Campo:</target> <note /> </trans-unit> <trans-unit id="Call_Hierarchy"> <source>Call Hierarchy</source> <target state="translated">Hierarquia de Chamada</target> <note /> </trans-unit> <trans-unit id="Calls_To_0"> <source>Calls To '{0}'</source> <target state="translated">Chamadas para '{0}'</target> <note /> </trans-unit> <trans-unit id="Calls_To_Base_Member_0"> <source>Calls To Base Member '{0}'</source> <target state="translated">Chamadas para Membro Base '{0}'</target> <note /> </trans-unit> <trans-unit id="Calls_To_Interface_Implementation_0"> <source>Calls To Interface Implementation '{0}'</source> <target state="translated">Chamadas para Implementação de Interface '{0}'</target> <note /> </trans-unit> <trans-unit id="Computing_Call_Hierarchy_Information"> <source>Computing Call Hierarchy Information</source> <target state="translated">Informações sobre Hierarquia de Chamada de Computação</target> <note /> </trans-unit> <trans-unit id="Implements_0"> <source>Implements '{0}'</source> <target state="translated">Implementa '{0}'</target> <note /> </trans-unit> <trans-unit id="Initializers"> <source>Initializers</source> <target state="translated">Inicializadores</target> <note /> </trans-unit> <trans-unit id="References_To_Field_0"> <source>References To Field '{0}'</source> <target state="translated">Referências ao Campo '{0}'</target> <note /> </trans-unit> <trans-unit id="Calls_To_Overrides"> <source>Calls To Overrides</source> <target state="translated">Chamadas para Substituições</target> <note /> </trans-unit> <trans-unit id="Preview_changes1"> <source>_Preview changes</source> <target state="translated">Alterações de _Preview</target> <note /> </trans-unit> <trans-unit id="Apply3"> <source>Apply</source> <target state="translated">Aplicar</target> <note /> </trans-unit> <trans-unit id="Cancel"> <source>Cancel</source> <target state="translated">Cancelar</target> <note /> </trans-unit> <trans-unit id="Changes"> <source>Changes</source> <target state="translated">Alterações</target> <note /> </trans-unit> <trans-unit id="Preview_changes2"> <source>Preview changes</source> <target state="translated">Visualizar alterações</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="IntelliSense_Commit_Formatting"> <source>IntelliSense Commit Formatting</source> <target state="translated">Formatação de Confirmação IntelliSense</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking"> <source>Rename Tracking</source> <target state="translated">Renomear Acompanhamento</target> <note /> </trans-unit> <trans-unit id="Removing_0_from_1_with_content_colon"> <source>Removing '{0}' from '{1}' with content:</source> <target state="translated">Removendo '{0}' de '{1}' com conteúdo:</target> <note /> </trans-unit> <trans-unit id="_0_does_not_support_the_1_operation_However_it_may_contain_nested_2_s_see_2_3_that_support_this_operation"> <source>'{0}' does not support the '{1}' operation. However, it may contain nested '{2}'s (see '{2}.{3}') that support this operation.</source> <target state="translated">'{0}' não dá suporte à operação '{1}'. No entanto, ele pode conter '{2}'s aninhados (consulte '{2}.{3}') que dá suporte a esta operação.</target> <note /> </trans-unit> <trans-unit id="Brace_Completion"> <source>Brace Completion</source> <target state="translated">Preenchimento de Chaves</target> <note /> </trans-unit> <trans-unit id="Cannot_apply_operation_while_a_rename_session_is_active"> <source>Cannot apply operation while a rename session is active.</source> <target state="translated">Não é possível aplicar a operação enquanto uma sessão de renomeação está ativa.</target> <note /> </trans-unit> <trans-unit id="The_rename_tracking_session_was_cancelled_and_is_no_longer_available"> <source>The rename tracking session was cancelled and is no longer available.</source> <target state="translated">A sessão de acompanhamento de renomeação foi cancelada e não está mais disponível.</target> <note /> </trans-unit> <trans-unit id="Highlighted_Written_Reference"> <source>Highlighted Written Reference</source> <target state="translated">Referência Escrita Realçada</target> <note /> </trans-unit> <trans-unit id="Cursor_must_be_on_a_member_name"> <source>Cursor must be on a member name.</source> <target state="translated">O cursor deve estar em um nome do membro.</target> <note /> </trans-unit> <trans-unit id="Brace_Matching"> <source>Brace Matching</source> <target state="translated">Correspondência de Chaves</target> <note /> </trans-unit> <trans-unit id="Locating_implementations"> <source>Locating implementations...</source> <target state="translated">Localizando implementações...</target> <note /> </trans-unit> <trans-unit id="Go_To_Implementation"> <source>Go To Implementation</source> <target state="translated">Ir Para Implementação</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_implementations"> <source>The symbol has no implementations.</source> <target state="translated">O símbolo não tem implementações.</target> <note /> </trans-unit> <trans-unit id="New_name_colon_0"> <source>New name: {0}</source> <target state="translated">Novo nome: {0}</target> <note /> </trans-unit> <trans-unit id="Modify_any_highlighted_location_to_begin_renaming"> <source>Modify any highlighted location to begin renaming.</source> <target state="translated">Modifique qualquer local realçado para iniciar a renomeação.</target> <note /> </trans-unit> <trans-unit id="Paste"> <source>Paste</source> <target state="translated">Colar</target> <note /> </trans-unit> <trans-unit id="Navigating"> <source>Navigating...</source> <target state="translated">Navegando...</target> <note /> </trans-unit> <trans-unit id="Suggestion_ellipses"> <source>Suggestion ellipses (…)</source> <target state="translated">Reticências de sugestão (…)</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>'{0}' references</source> <target state="translated">'{0}' referências</target> <note /> </trans-unit> <trans-unit id="_0_implementations"> <source>'{0}' implementations</source> <target state="translated">'Implementações de '{0}'</target> <note /> </trans-unit> <trans-unit id="_0_declarations"> <source>'{0}' declarations</source> <target state="translated">'Declarações de '{0}'</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Conflict"> <source>Inline Rename Conflict</source> <target state="translated">Conflito de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Background_and_Border"> <source>Inline Rename Field Background and Border</source> <target state="translated">Borda e Tela de Fundo do Campo de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Text"> <source>Inline Rename Field Text</source> <target state="translated">Texto do Campo de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Block_Comment_Editing"> <source>Block Comment Editing</source> <target state="translated">Bloquear Edição de Comentário</target> <note /> </trans-unit> <trans-unit id="Comment_Uncomment_Selection"> <source>Comment/Uncomment Selection</source> <target state="translated">Comentar/Remover Marca de Comentário da Seleção</target> <note /> </trans-unit> <trans-unit id="Code_Completion"> <source>Code Completion</source> <target state="translated">Conclusão de Código</target> <note /> </trans-unit> <trans-unit id="Execute_In_Interactive"> <source>Execute In Interactive</source> <target state="translated">Executar em Interativo</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="Go_To_Adjacent_Member"> <source>Go To Adjacent Member</source> <target state="translated">Ir para Membro Adjacente</target> <note /> </trans-unit> <trans-unit id="Interactive"> <source>Interactive</source> <target state="translated">Interativo</target> <note /> </trans-unit> <trans-unit id="Paste_in_Interactive"> <source>Paste in Interactive</source> <target state="translated">Colar em Interativo</target> <note /> </trans-unit> <trans-unit id="Navigate_To_Highlight_Reference"> <source>Navigate To Highlighted Reference</source> <target state="translated">Navegar para Referência Realçada</target> <note /> </trans-unit> <trans-unit id="Outlining"> <source>Outlining</source> <target state="translated">Estrutura de Tópicos</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking_Cancellation"> <source>Rename Tracking Cancellation</source> <target state="translated">Renomear Cancelamento de Acompanhamento</target> <note /> </trans-unit> <trans-unit id="Signature_Help"> <source>Signature Help</source> <target state="translated">Ajuda da Assinatura</target> <note /> </trans-unit> <trans-unit id="Smart_Token_Formatter"> <source>Smart Token Formatter</source> <target state="translated">Formatador de Token Inteligente</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="../EditorFeaturesResources.resx"> <body> <trans-unit id="All_methods"> <source>All methods</source> <target state="translated">Todos os métodos</target> <note /> </trans-unit> <trans-unit id="Always_for_clarity"> <source>Always for clarity</source> <target state="translated">Sempre para esclarecimento</target> <note /> </trans-unit> <trans-unit id="An_inline_rename_session_is_active_for_identifier_0"> <source>An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time.</source> <target state="translated">Uma sessão de renomeação embutida está ativa para o identificador '{0}'. Invoque a renomeação embutida novamente para acessar opções adicionais. Você pode continuar a editar o identificador que está sendo renomeado a qualquer momento.</target> <note>For screenreaders. {0} is the identifier being renamed.</note> </trans-unit> <trans-unit id="Applying_changes"> <source>Applying changes</source> <target state="translated">Aplicando mudanças</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters"> <source>Avoid unused parameters</source> <target state="translated">Evitar parâmetros não utilizados</target> <note /> </trans-unit> <trans-unit id="Change_configuration"> <source>Change configuration</source> <target state="translated">Alterar configuração</target> <note /> </trans-unit> <trans-unit id="Code_cleanup_is_not_configured"> <source>Code cleanup is not configured</source> <target state="translated">A limpeza de código não está configurada</target> <note /> </trans-unit> <trans-unit id="Configure_it_now"> <source>Configure it now</source> <target state="translated">Configurar agora</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_this_or_Me"> <source>Do not prefer 'this.' or 'Me.'</source> <target state="translated">Não preferir 'this.' nem 'Me'.</target> <note /> </trans-unit> <trans-unit id="Do_not_show_this_message_again"> <source>Do not show this message again</source> <target state="translated">Não mostrar esta mensagem novamente</target> <note /> </trans-unit> <trans-unit id="Do_you_still_want_to_proceed_This_may_produce_broken_code"> <source>Do you still want to proceed? This may produce broken code.</source> <target state="translated">Ainda quer continuar? Isso pode produzir código desfeito.</target> <note /> </trans-unit> <trans-unit id="Expander_display_text"> <source>items from unimported namespaces</source> <target state="translated">itens de namespaces não importados</target> <note /> </trans-unit> <trans-unit id="Expander_image_element"> <source>Expander</source> <target state="translated">Expansor</target> <note /> </trans-unit> <trans-unit id="Extract_method_encountered_the_following_issues"> <source>Extract method encountered the following issues:</source> <target state="translated">O método de extração encontrou os seguintes problemas:</target> <note /> </trans-unit> <trans-unit id="Filter_image_element"> <source>Filter</source> <target state="translated">Filtrar</target> <note>Caption/tooltip for "Filter" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="For_locals_parameters_and_members"> <source>For locals, parameters and members</source> <target state="translated">Para locais, parâmetros e membros</target> <note /> </trans-unit> <trans-unit id="For_member_access_expressions"> <source>For member access expressions</source> <target state="translated">Para expressões de acesso de membro</target> <note /> </trans-unit> <trans-unit id="Format_document_performed_additional_cleanup"> <source>Format Document performed additional cleanup</source> <target state="translated">A Formatação do Documento executou uma limpeza adicional</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0"> <source>Get help for '{0}'</source> <target state="translated">Obter ajuda para '{0}'</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0_from_Bing"> <source>Get help for '{0}' from Bing</source> <target state="translated">Obter ajuda para o '{0}' do Bing</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_0"> <source>Gathering Suggestions - '{0}'</source> <target state="translated">Obtendo Sugestões – '{0}'</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_Waiting_for_the_solution_to_fully_load"> <source>Gathering Suggestions - Waiting for the solution to fully load</source> <target state="translated">Obtendo Sugestões – aguardando a solução carregar totalmente</target> <note /> </trans-unit> <trans-unit id="Go_To_Base"> <source>Go To Base</source> <target state="translated">Ir Para a Base</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators</source> <target state="translated">Em operadores aritméticos</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators</source> <target state="translated">Em outros operadores binários</target> <note /> </trans-unit> <trans-unit id="In_other_operators"> <source>In other operators</source> <target state="translated">Em outros operadores</target> <note /> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators</source> <target state="translated">Em operadores relacionais</target> <note /> </trans-unit> <trans-unit id="Indentation_Size"> <source>Indentation Size</source> <target state="translated">Tamanho do Recuo</target> <note /> </trans-unit> <trans-unit id="Inline_Hints"> <source>Inline Hints</source> <target state="translated">Dicas Embutidas</target> <note /> </trans-unit> <trans-unit id="Insert_Final_Newline"> <source>Insert Final Newline</source> <target state="translated">Inserir Nova Linha Final</target> <note /> </trans-unit> <trans-unit id="Invalid_assembly_name"> <source>Invalid assembly name</source> <target state="translated">Nome do assembly inválido</target> <note /> </trans-unit> <trans-unit id="Invalid_characters_in_assembly_name"> <source>Invalid characters in assembly name</source> <target state="translated">Caracteres inválidos no nome do assembly</target> <note /> </trans-unit> <trans-unit id="Keyword_Control"> <source>Keyword - Control</source> <target state="translated">Palavra-chave – Controle</target> <note /> </trans-unit> <trans-unit id="Locating_bases"> <source>Locating bases...</source> <target state="translated">Localizando as bases...</target> <note /> </trans-unit> <trans-unit id="Never_if_unnecessary"> <source>Never if unnecessary</source> <target state="translated">Nunca se desnecessário</target> <note /> </trans-unit> <trans-unit id="New_Line"> <source>New Line</source> <target state="translated">Nova Linha</target> <note /> </trans-unit> <trans-unit id="No"> <source>No</source> <target state="translated">Não</target> <note /> </trans-unit> <trans-unit id="Non_public_methods"> <source>Non-public methods</source> <target state="translated">Métodos não públicos</target> <note /> </trans-unit> <trans-unit id="Operator_Overloaded"> <source>Operator - Overloaded</source> <target state="translated">Operador – Sobrecarregado</target> <note /> </trans-unit> <trans-unit id="Paste_Tracking"> <source>Paste Tracking</source> <target state="translated">Colar Acompanhamento</target> <note /> </trans-unit> <trans-unit id="Prefer_System_HashCode_in_GetHashCode"> <source>Prefer 'System.HashCode' in 'GetHashCode'</source> <target state="translated">Prefira 'System.HashCode' em 'GetHashCode'</target> <note /> </trans-unit> <trans-unit id="Prefer_coalesce_expression"> <source>Prefer coalesce expression</source> <target state="translated">Preferir a expressão de união</target> <note /> </trans-unit> <trans-unit id="Prefer_collection_initializer"> <source>Prefer collection initializer</source> <target state="translated">Preferir o inicializador de coleção</target> <note /> </trans-unit> <trans-unit id="Prefer_compound_assignments"> <source>Prefer compound assignments</source> <target state="translated">Preferir atribuições de compostos</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_assignments"> <source>Prefer conditional expression over 'if' with assignments</source> <target state="translated">Preferir expressão condicional em vez de 'if' com atribuições</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_returns"> <source>Prefer conditional expression over 'if' with returns</source> <target state="translated">Preferir expressão condicional em vez de 'if' com retornos</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_tuple_name"> <source>Prefer explicit tuple name</source> <target state="translated">Preferir nome de tupla explícito</target> <note /> </trans-unit> <trans-unit id="Prefer_framework_type"> <source>Prefer framework type</source> <target state="translated">Preferir tipo de estrutura</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_anonymous_type_member_names"> <source>Prefer inferred anonymous type member names</source> <target state="translated">Prefira usar nomes de membro inferidos do tipo anônimo</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_tuple_names"> <source>Prefer inferred tuple element names</source> <target state="translated">Preferir usar nomes de elementos inferidos de tupla</target> <note /> </trans-unit> <trans-unit id="Prefer_is_null_for_reference_equality_checks"> <source>Prefer 'is null' for reference equality checks</source> <target state="translated">Preferir 'is null' para as verificações de igualdade de referência</target> <note /> </trans-unit> <trans-unit id="Prefer_null_propagation"> <source>Prefer null propagation</source> <target state="translated">Preferir tratamento simplificado de nulo</target> <note /> </trans-unit> <trans-unit id="Prefer_object_initializer"> <source>Prefer object initializer</source> <target state="translated">Preferir inicializador de objeto</target> <note /> </trans-unit> <trans-unit id="Prefer_predefined_type"> <source>Prefer predefined type</source> <target state="translated">Preferir tipo predefinido</target> <note /> </trans-unit> <trans-unit id="Prefer_readonly_fields"> <source>Prefer readonly fields</source> <target state="translated">Preferir campos readonly</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_boolean_expressions"> <source>Prefer simplified boolean expressions</source> <target state="translated">Preferir expressões boolianas simplificadas</target> <note /> </trans-unit> <trans-unit id="Prefer_this_or_Me"> <source>Prefer 'this.' or 'Me.'</source> <target state="translated">Preferir 'this.' ou 'Me.'</target> <note /> </trans-unit> <trans-unit id="Preprocessor_Text"> <source>Preprocessor Text</source> <target state="translated">Texto de Pré-Processador</target> <note /> </trans-unit> <trans-unit id="Punctuation"> <source>Punctuation</source> <target state="translated">Pontuação</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_this_or_Me"> <source>Qualify event access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de evento com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_this_or_Me"> <source>Qualify field access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de campo com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_this_or_Me"> <source>Qualify method access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de método com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_this_or_Me"> <source>Qualify property access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de propriedade com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Reassigned_variable"> <source>Reassigned variable</source> <target state="new">Reassigned variable</target> <note /> </trans-unit> <trans-unit id="Rename_file_name_doesnt_match"> <source>Rename _file (type does not match file name)</source> <target state="translated">Renomear _arquivo (o tipo não corresponde ao nome do arquivo)</target> <note /> </trans-unit> <trans-unit id="Rename_file_partial_type"> <source>Rename _file (not allowed on partial types)</source> <target state="translated">Renomear _arquivo (não permitido em tipos parciais)</target> <note>Disabled text status for file rename</note> </trans-unit> <trans-unit id="Rename_symbols_file"> <source>Rename symbol's _file</source> <target state="translated">Renomear o _arquivo do símbolo</target> <note>Indicates that the file a symbol is defined in will also be renamed</note> </trans-unit> <trans-unit id="Split_comment"> <source>Split comment</source> <target state="translated">Dividir o comentário</target> <note /> </trans-unit> <trans-unit id="String_Escape_Character"> <source>String - Escape Character</source> <target state="translated">String - caractere de Escape</target> <note /> </trans-unit> <trans-unit id="Symbol_Static"> <source>Symbol - Static</source> <target state="translated">Símbolo – Estático</target> <note /> </trans-unit> <trans-unit id="Tab_Size"> <source>Tab Size</source> <target state="translated">Tamanho da Tabulação</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_base"> <source>The symbol has no base.</source> <target state="translated">O símbolo não tem nenhuma base.</target> <note /> </trans-unit> <trans-unit id="Toggle_Block_Comment"> <source>Toggle Block Comment</source> <target state="translated">Ativar/Desativar Comentário de Bloco</target> <note /> </trans-unit> <trans-unit id="Toggle_Line_Comment"> <source>Toggle Line Comment</source> <target state="translated">Ativar/Desativar Comentário de Linha</target> <note /> </trans-unit> <trans-unit id="Toggling_block_comment"> <source>Toggling block comment...</source> <target state="translated">Ativando/desativando o comentário de bloco...</target> <note /> </trans-unit> <trans-unit id="Toggling_line_comment"> <source>Toggling line comment...</source> <target state="translated">Ativando/desativando o comentário de linha...</target> <note /> </trans-unit> <trans-unit id="Use_Tabs"> <source>Use Tabs</source> <target state="translated">Usar Tabulações</target> <note /> </trans-unit> <trans-unit id="User_Members_Constants"> <source>User Members - Constants</source> <target state="translated">Membros de Usuário – Constantes</target> <note /> </trans-unit> <trans-unit id="User_Members_Enum_Members"> <source>User Members - Enum Members</source> <target state="translated">Membros de Usuário – Membros Enum</target> <note /> </trans-unit> <trans-unit id="User_Members_Events"> <source>User Members - Events</source> <target state="translated">Membros de Usuário – Eventos</target> <note /> </trans-unit> <trans-unit id="User_Members_Extension_Methods"> <source>User Members - Extension Methods</source> <target state="translated">Membros de Usuário – Métodos de Extensão</target> <note /> </trans-unit> <trans-unit id="User_Members_Fields"> <source>User Members - Fields</source> <target state="translated">Membros de Usuário – Campos</target> <note /> </trans-unit> <trans-unit id="User_Members_Labels"> <source>User Members - Labels</source> <target state="translated">Membros de Usuário – Rótulos</target> <note /> </trans-unit> <trans-unit id="User_Members_Locals"> <source>User Members - Locals</source> <target state="translated">Membros de Usuário – Locais</target> <note /> </trans-unit> <trans-unit id="User_Members_Methods"> <source>User Members - Methods</source> <target state="translated">Membros de Usuário – Métodos</target> <note /> </trans-unit> <trans-unit id="User_Members_Namespaces"> <source>User Members - Namespaces</source> <target state="translated">Membros de Usuário – Namespaces</target> <note /> </trans-unit> <trans-unit id="User_Members_Parameters"> <source>User Members - Parameters</source> <target state="translated">Membros de Usuário – Parâmetros</target> <note /> </trans-unit> <trans-unit id="User_Members_Properties"> <source>User Members - Properties</source> <target state="translated">Membros de Usuário – Propriedades</target> <note /> </trans-unit> <trans-unit id="User_Types_Classes"> <source>User Types - Classes</source> <target state="translated">Tipos de Usuário - Classes</target> <note /> </trans-unit> <trans-unit id="User_Types_Delegates"> <source>User Types - Delegates</source> <target state="translated">Tipos de Usuário - Representantes</target> <note /> </trans-unit> <trans-unit id="User_Types_Enums"> <source>User Types - Enums</source> <target state="translated">Tipos de Usuário - Enums</target> <note /> </trans-unit> <trans-unit id="User_Types_Interfaces"> <source>User Types - Interfaces</source> <target state="translated">Tipos de Usuário - Interfaces</target> <note /> </trans-unit> <trans-unit id="User_Types_Record_Structs"> <source>User Types - Record Structs</source> <target state="translated">Tipos de usuário - Registro de structs</target> <note /> </trans-unit> <trans-unit id="User_Types_Records"> <source>User Types - Records</source> <target state="translated">Tipos de Usuário – Registros</target> <note /> </trans-unit> <trans-unit id="User_Types_Structures"> <source>User Types - Structures</source> <target state="translated">Tipos de Usuário - Estruturas</target> <note /> </trans-unit> <trans-unit id="User_Types_Type_Parameters"> <source>User Types - Type Parameters</source> <target state="translated">Tipos de Usuário - Parâmetros de Tipo</target> <note /> </trans-unit> <trans-unit id="String_Verbatim"> <source>String - Verbatim</source> <target state="translated">Cadeia de caracteres - Textual</target> <note /> </trans-unit> <trans-unit id="Waiting_for_background_work_to_finish"> <source>Waiting for background work to finish...</source> <target state="translated">Aguardando a conclusão do trabalho em segundo plano...</target> <note /> </trans-unit> <trans-unit id="Warning_image_element"> <source>Warning</source> <target state="translated">Aviso</target> <note>Caption/tooltip for "Warning" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Name"> <source>XML Doc Comments - Attribute Name</source> <target state="translated">Comentário da documentação XML - Nome de Atributo</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_CData_Section"> <source>XML Doc Comments - CData Section</source> <target state="translated">Comentário da documentação XML - Seção CData</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Text"> <source>XML Doc Comments - Text</source> <target state="translated">Comentário da documentação XML - Texto</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Delimiter"> <source>XML Doc Comments - Delimiter</source> <target state="translated">Comentário da documentação XML - Delimitador</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Comment"> <source>XML Doc Comments - Comment</source> <target state="translated">Comentário da documentação XML - Comentário</target> <note /> </trans-unit> <trans-unit id="User_Types_Modules"> <source>User Types - Modules</source> <target state="translated">Tipos de Usuário - Módulos</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Name"> <source>VB XML Literals - Attribute Name</source> <target state="translated">Literais XML do VB - Nome de Atributo</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Quotes"> <source>VB XML Literals - Attribute Quotes</source> <target state="translated">Literais XML do VB - Aspas de Atributo</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Value"> <source>VB XML Literals - Attribute Value</source> <target state="translated">Literais XML do VB - Valor de Atributo</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_CData_Section"> <source>VB XML Literals - CData Section</source> <target state="translated">Literais XML do VB - Seção CData</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Comment"> <source>VB XML Literals - Comment</source> <target state="translated">Literais XML do VB - Comentário</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Delimiter"> <source>VB XML Literals - Delimiter</source> <target state="translated">Literais XML do VB - Delimitador</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Embedded_Expression"> <source>VB XML Literals - Embedded Expression</source> <target state="translated">Literais XML do VB - Expressão Inserida</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Entity_Reference"> <source>VB XML Literals - Entity Reference</source> <target state="translated">Literais XML do VB - Referência de Entidade</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Name"> <source>VB XML Literals - Name</source> <target state="translated">Literais XML do VB - Nome</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Processing_Instruction"> <source>VB XML Literals - Processing Instruction</source> <target state="translated">Literais XML do VB - Instrução de Processamento</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Text"> <source>VB XML Literals - Text</source> <target state="translated">Literais XML do VB - Texto</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Quotes"> <source>XML Doc Comments - Attribute Quotes</source> <target state="translated">Comentário da documentação XML - Aspas de Atributo</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Value"> <source>XML Doc Comments - Attribute Value</source> <target state="translated">Comentário da documentação XML - Valor de Atributo</target> <note /> </trans-unit> <trans-unit id="Unnecessary_Code"> <source>Unnecessary Code</source> <target state="translated">Código Desnecessário</target> <note /> </trans-unit> <trans-unit id="Rude_Edit"> <source>Rude Edit</source> <target state="translated">Edição Rudimentar</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_1_reference_in_1_file"> <source>Rename will update 1 reference in 1 file.</source> <target state="translated">Renomear atualizará 1 referência em 1 arquivo.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_file"> <source>Rename will update {0} references in 1 file.</source> <target state="translated">Renomear atualizará {0} referências em 1 arquivo.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_files"> <source>Rename will update {0} references in {1} files.</source> <target state="translated">Renomear atualizará {0} referências em {1} arquivos.</target> <note /> </trans-unit> <trans-unit id="Yes"> <source>Yes</source> <target state="translated">Sim</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_contained_in_a_read_only_file"> <source>You cannot rename this element because it is contained in a read-only file.</source> <target state="translated">Você não pode renomear este elemento porque ele está contido em um arquivo somente leitura.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_in_a_location_that_cannot_be_navigated_to"> <source>You cannot rename this element because it is in a location that cannot be navigated to.</source> <target state="translated">Você não pode renomear este elemento porque ele está em um local para o qual não é possível navegar.</target> <note /> </trans-unit> <trans-unit id="_0_bases"> <source>'{0}' bases</source> <target state="translated">Bases '{0}'</target> <note /> </trans-unit> <trans-unit id="_0_conflict_s_will_be_resolved"> <source>{0} conflict(s) will be resolved</source> <target state="translated">{0} conflito(s) será(ão) resolvido(s)</target> <note /> </trans-unit> <trans-unit id="_0_implemented_members"> <source>'{0}' implemented members</source> <target state="translated">'{0}' membros implementados</target> <note /> </trans-unit> <trans-unit id="_0_unresolvable_conflict_s"> <source>{0} unresolvable conflict(s)</source> <target state="translated">{0} conflito(s) não solucionável(is)</target> <note /> </trans-unit> <trans-unit id="Applying_0"> <source>Applying "{0}"...</source> <target state="translated">Aplicando "{0}"...</target> <note /> </trans-unit> <trans-unit id="Adding_0_to_1_with_content_colon"> <source>Adding '{0}' to '{1}' with content:</source> <target state="translated">Adicionando "{0}" a "{1}" com conteúdo:</target> <note /> </trans-unit> <trans-unit id="Adding_project_0"> <source>Adding project '{0}'</source> <target state="translated">Adicionando projeto "{0}"</target> <note /> </trans-unit> <trans-unit id="Removing_project_0"> <source>Removing project '{0}'</source> <target state="translated">Removendo projeto "{0}"</target> <note /> </trans-unit> <trans-unit id="Changing_project_references_for_0"> <source>Changing project references for '{0}'</source> <target state="translated">Alterar referências de projeto para "{0}"</target> <note /> </trans-unit> <trans-unit id="Adding_reference_0_to_1"> <source>Adding reference '{0}' to '{1}'</source> <target state="translated">Adicionando referência "{0}" a "{1}"</target> <note /> </trans-unit> <trans-unit id="Removing_reference_0_from_1"> <source>Removing reference '{0}' from '{1}'</source> <target state="translated">Removendo referência "{0}" de "{1}"</target> <note /> </trans-unit> <trans-unit id="Adding_analyzer_reference_0_to_1"> <source>Adding analyzer reference '{0}' to '{1}'</source> <target state="translated">Adicionando referência de analisador "{0}" a "{1}"</target> <note /> </trans-unit> <trans-unit id="Removing_analyzer_reference_0_from_1"> <source>Removing analyzer reference '{0}' from '{1}'</source> <target state="translated">Removendo referência do analisador "{0}" de "{1}"</target> <note /> </trans-unit> <trans-unit id="XML_End_Tag_Completion"> <source>XML End Tag Completion</source> <target state="translated">Conclusão da Marca de Fim do XML</target> <note /> </trans-unit> <trans-unit id="Completing_Tag"> <source>Completing Tag</source> <target state="translated">Completando a Tag</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field"> <source>Encapsulate Field</source> <target state="translated">Encapsular Campo</target> <note /> </trans-unit> <trans-unit id="Applying_Encapsulate_Field_refactoring"> <source>Applying "Encapsulate Field" refactoring...</source> <target state="translated">Aplicando refatoração "Encapsular Campo"...</target> <note /> </trans-unit> <trans-unit id="Please_select_the_definition_of_the_field_to_encapsulate"> <source>Please select the definition of the field to encapsulate.</source> <target state="translated">Selecione a definição do campo a encapsular.</target> <note /> </trans-unit> <trans-unit id="Given_Workspace_doesn_t_support_Undo"> <source>Given Workspace doesn't support Undo</source> <target state="translated">Workspace fornecido não suporta Desfazer</target> <note /> </trans-unit> <trans-unit id="Searching"> <source>Searching...</source> <target state="translated">Pesquisando...</target> <note /> </trans-unit> <trans-unit id="Canceled"> <source>Canceled.</source> <target state="translated">Cancelado.</target> <note /> </trans-unit> <trans-unit id="No_information_found"> <source>No information found.</source> <target state="translated">Nenhuma informação encontrada.</target> <note /> </trans-unit> <trans-unit id="No_usages_found"> <source>No usages found.</source> <target state="translated">Nenhum uso encontrado.</target> <note /> </trans-unit> <trans-unit id="Implements_"> <source>Implements</source> <target state="translated">Implementos</target> <note /> </trans-unit> <trans-unit id="Implemented_By"> <source>Implemented By</source> <target state="translated">Implementado por</target> <note /> </trans-unit> <trans-unit id="Overrides_"> <source>Overrides</source> <target state="translated">Substitui</target> <note /> </trans-unit> <trans-unit id="Overridden_By"> <source>Overridden By</source> <target state="translated">Substituído por</target> <note /> </trans-unit> <trans-unit id="Directly_Called_In"> <source>Directly Called In</source> <target state="translated">Chamado Diretamente</target> <note /> </trans-unit> <trans-unit id="Indirectly_Called_In"> <source>Indirectly Called In</source> <target state="translated">Chamado Indiretamente </target> <note /> </trans-unit> <trans-unit id="Called_In"> <source>Called In</source> <target state="translated">Chamado Em</target> <note /> </trans-unit> <trans-unit id="Referenced_In"> <source>Referenced In</source> <target state="translated">Referenciado Em</target> <note /> </trans-unit> <trans-unit id="No_references_found"> <source>No references found.</source> <target state="translated">Nenhuma referência encontrada.</target> <note /> </trans-unit> <trans-unit id="No_derived_types_found"> <source>No derived types found.</source> <target state="translated">Nenhum tipo derivado encontrado.</target> <note /> </trans-unit> <trans-unit id="No_implementations_found"> <source>No implementations found.</source> <target state="translated">Nenhuma implementação encontrada.</target> <note /> </trans-unit> <trans-unit id="_0_Line_1"> <source>{0} - (Line {1})</source> <target state="translated">{0} - (Linha {1})</target> <note /> </trans-unit> <trans-unit id="Class_Parts"> <source>Class Parts</source> <target state="translated">Partes de Classe</target> <note /> </trans-unit> <trans-unit id="Struct_Parts"> <source>Struct Parts</source> <target state="translated">Partes de Struct</target> <note /> </trans-unit> <trans-unit id="Interface_Parts"> <source>Interface Parts</source> <target state="translated">Componentes da Interface</target> <note /> </trans-unit> <trans-unit id="Type_Parts"> <source>Type Parts</source> <target state="translated">Partes do Tipo</target> <note /> </trans-unit> <trans-unit id="Inherits_"> <source>Inherits</source> <target state="translated">Herda</target> <note /> </trans-unit> <trans-unit id="Inherited_By"> <source>Inherited By</source> <target state="translated">Herdado por</target> <note /> </trans-unit> <trans-unit id="Already_tracking_document_with_identical_key"> <source>Already tracking document with identical key</source> <target state="translated">Já está a rastrear o documento com chave idêntica</target> <note /> </trans-unit> <trans-unit id="analyzer_Prefer_auto_properties"> <source>Prefer auto properties</source> <target state="translated">Preferir propriedades automáticas</target> <note /> </trans-unit> <trans-unit id="document_is_not_currently_being_tracked"> <source>document is not currently being tracked</source> <target state="translated">documento não está sendo rastreado no momento</target> <note /> </trans-unit> <trans-unit id="Computing_Rename_information"> <source>Computing Rename information...</source> <target state="translated">Computando informações de Renomeação...</target> <note /> </trans-unit> <trans-unit id="Updating_files"> <source>Updating files...</source> <target state="translated">Atualizando arquivos...</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_cancelled_or_is_not_valid"> <source>Rename operation was cancelled or is not valid</source> <target state="translated">A operação de renomear foi cancelada ou não é válida</target> <note /> </trans-unit> <trans-unit id="Rename_Symbol"> <source>Rename Symbol</source> <target state="translated">Renomear Símbolo</target> <note /> </trans-unit> <trans-unit id="Text_Buffer_Change"> <source>Text Buffer Change</source> <target state="translated">Alteração no Buffer de Texto</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_not_properly_completed_Some_file_might_not_have_been_updated"> <source>Rename operation was not properly completed. Some file might not have been updated.</source> <target state="translated">A operação de renomear não foi corretamente concluída. Algum arquivo pode não ter sido atualizado.</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename '{0}' to '{1}'</source> <target state="translated">Renomear "{0}" para "{1}"</target> <note /> </trans-unit> <trans-unit id="Preview_Warning"> <source>Preview Warning</source> <target state="translated">Aviso de Visualização</target> <note /> </trans-unit> <trans-unit id="external"> <source>(external)</source> <target state="translated">(externo)</target> <note /> </trans-unit> <trans-unit id="Automatic_Line_Ender"> <source>Automatic Line Ender</source> <target state="translated">Finalizador de Linha Automático</target> <note /> </trans-unit> <trans-unit id="Automatically_completing"> <source>Automatically completing...</source> <target state="translated">Concluindo automaticamente...</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion"> <source>Automatic Pair Completion</source> <target state="translated">Conclusão de Pares Automática</target> <note /> </trans-unit> <trans-unit id="An_active_inline_rename_session_is_still_active_Complete_it_before_starting_a_new_one"> <source>An active inline rename session is still active. Complete it before starting a new one.</source> <target state="translated">Uma sessão de renomeação embutida ativa ainda está ativa. Conclua-a antes de iniciar uma nova.</target> <note /> </trans-unit> <trans-unit id="The_buffer_is_not_part_of_a_workspace"> <source>The buffer is not part of a workspace.</source> <target state="translated">O buffer não é parte de um workspace.</target> <note /> </trans-unit> <trans-unit id="The_token_is_not_contained_in_the_workspace"> <source>The token is not contained in the workspace.</source> <target state="translated">O token não está contido no workspace.</target> <note /> </trans-unit> <trans-unit id="You_must_rename_an_identifier"> <source>You must rename an identifier.</source> <target state="translated">Você deve renomear um identificador.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element"> <source>You cannot rename this element.</source> <target state="translated">Você não pode renomear este elemento.</target> <note /> </trans-unit> <trans-unit id="Please_resolve_errors_in_your_code_before_renaming_this_element"> <source>Please resolve errors in your code before renaming this element.</source> <target state="translated">Resolva erros em seu código antes de renomear este elemento.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_operators"> <source>You cannot rename operators.</source> <target state="translated">Você não pode renomear operadores.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_that_are_defined_in_metadata"> <source>You cannot rename elements that are defined in metadata.</source> <target state="translated">Você não pode renomear elementos que estão definidos nos metadados.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_from_previous_submissions"> <source>You cannot rename elements from previous submissions.</source> <target state="translated">Você não pode renomear elementos de envios anteriores.</target> <note /> </trans-unit> <trans-unit id="Navigation_Bars"> <source>Navigation Bars</source> <target state="translated">Barras de Navegação</target> <note /> </trans-unit> <trans-unit id="Refreshing_navigation_bars"> <source>Refreshing navigation bars...</source> <target state="translated">Atualizando barras de navegação...</target> <note /> </trans-unit> <trans-unit id="Format_Token"> <source>Format Token</source> <target state="translated">Token de Formato</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">Recuo Inteligente</target> <note /> </trans-unit> <trans-unit id="Find_References"> <source>Find References</source> <target state="translated">Localizar Referências</target> <note /> </trans-unit> <trans-unit id="Finding_references"> <source>Finding references...</source> <target state="translated">Localizando referências...</target> <note /> </trans-unit> <trans-unit id="Finding_references_of_0"> <source>Finding references of "{0}"...</source> <target state="translated">Localizando referências de "{0}"...</target> <note /> </trans-unit> <trans-unit id="Comment_Selection"> <source>Comment Selection</source> <target state="translated">Comentar Seleção</target> <note /> </trans-unit> <trans-unit id="Uncomment_Selection"> <source>Uncomment Selection</source> <target state="translated">Remover Comentários da Seleção</target> <note /> </trans-unit> <trans-unit id="Commenting_currently_selected_text"> <source>Commenting currently selected text...</source> <target state="translated">Comentando o texto selecionado no momento...</target> <note /> </trans-unit> <trans-unit id="Uncommenting_currently_selected_text"> <source>Uncommenting currently selected text...</source> <target state="translated">Removendo marca de comentário do texto selecionado no momento...</target> <note /> </trans-unit> <trans-unit id="Insert_new_line"> <source>Insert new line</source> <target state="translated">Inserir Nova Linha</target> <note /> </trans-unit> <trans-unit id="Documentation_Comment"> <source>Documentation Comment</source> <target state="translated">Comentário de Documentação</target> <note /> </trans-unit> <trans-unit id="Inserting_documentation_comment"> <source>Inserting documentation comment...</source> <target state="translated">Inserindo comentário da documentação...</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="Applying_Extract_Method_refactoring"> <source>Applying "Extract Method" refactoring...</source> <target state="translated">Aplicando refatoração "Extrair Método"...</target> <note /> </trans-unit> <trans-unit id="Format_Document"> <source>Format Document</source> <target state="translated">Formatar 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="Formatting"> <source>Formatting</source> <target state="translated">Formatação</target> <note /> </trans-unit> <trans-unit id="Format_Selection"> <source>Format Selection</source> <target state="translated">Formatar Seleção</target> <note /> </trans-unit> <trans-unit id="Formatting_currently_selected_text"> <source>Formatting currently selected text...</source> <target state="translated">Formatando texto selecionado no momento...</target> <note /> </trans-unit> <trans-unit id="Cannot_navigate_to_the_symbol_under_the_caret"> <source>Cannot navigate to the symbol under the caret.</source> <target state="translated">Não é possível navegar para o símbolo sob o cursor.</target> <note /> </trans-unit> <trans-unit id="Go_to_Definition"> <source>Go to Definition</source> <target state="translated">Ir para Definição</target> <note /> </trans-unit> <trans-unit id="Navigating_to_definition"> <source>Navigating to definition...</source> <target state="translated">Navegando para definição...</target> <note /> </trans-unit> <trans-unit id="Organize_Document"> <source>Organize Document</source> <target state="translated">Organizar Documento</target> <note /> </trans-unit> <trans-unit id="Organizing_document"> <source>Organizing document...</source> <target state="translated">Organizando documento...</target> <note /> </trans-unit> <trans-unit id="Highlighted_Definition"> <source>Highlighted Definition</source> <target state="translated">Definição Realçada</target> <note /> </trans-unit> <trans-unit id="The_new_name_is_not_a_valid_identifier"> <source>The new name is not a valid identifier.</source> <target state="translated">O novo nome não é um identificador válido.</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Fixup"> <source>Inline Rename Fixup</source> <target state="translated">Correção de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Resolved_Conflict"> <source>Inline Rename Resolved Conflict</source> <target state="translated">Conflito de Renomeação Embutida Resolvido </target> <note /> </trans-unit> <trans-unit id="Inline_Rename"> <source>Inline Rename</source> <target state="translated">Renomeação embutida</target> <note /> </trans-unit> <trans-unit id="Rename"> <source>Rename</source> <target state="translated">renomear</target> <note /> </trans-unit> <trans-unit id="Start_Rename"> <source>Start Rename</source> <target state="translated">Iniciar Renomeação</target> <note /> </trans-unit> <trans-unit id="Display_conflict_resolutions"> <source>Display conflict resolutions</source> <target state="translated">Exibir resoluções de conflitos</target> <note /> </trans-unit> <trans-unit id="Finding_token_to_rename"> <source>Finding token to rename...</source> <target state="translated">Localizando token para renomear...</target> <note /> </trans-unit> <trans-unit id="Conflict"> <source>Conflict</source> <target state="translated">Conflito</target> <note /> </trans-unit> <trans-unit id="Text_Navigation"> <source>Text Navigation</source> <target state="translated">Navegação de Texto</target> <note /> </trans-unit> <trans-unit id="Finding_word_extent"> <source>Finding word extent...</source> <target state="translated">Localizando de extensão de palavra...</target> <note /> </trans-unit> <trans-unit id="Finding_enclosing_span"> <source>Finding enclosing span...</source> <target state="translated">Localizando alcance de delimitação...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_next_sibling"> <source>Finding span of next sibling...</source> <target state="translated">Localizando a extensão do próximo irmão...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_previous_sibling"> <source>Finding span of previous sibling...</source> <target state="translated">Localizando a extensão do irmão anterior...</target> <note /> </trans-unit> <trans-unit id="Rename_colon_0"> <source>Rename: {0}</source> <target state="translated">Renomear: {0}</target> <note /> </trans-unit> <trans-unit id="Light_bulb_session_is_already_dismissed"> <source>Light bulb session is already dismissed.</source> <target state="translated">A sessão de lâmpada já foi descartada.</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion_End_Point_Marker_Color"> <source>Automatic Pair Completion End Point Marker Color</source> <target state="translated">Cor do Marcador de Ponto Final da Conclusão de Pares Automática</target> <note /> </trans-unit> <trans-unit id="Renaming_anonymous_type_members_is_not_yet_supported"> <source>Renaming anonymous type members is not yet supported.</source> <target state="translated">Renomear membros de tipo anônimo ainda não é suportado.</target> <note /> </trans-unit> <trans-unit id="Engine_must_be_attached_to_an_Interactive_Window"> <source>Engine must be attached to an Interactive Window.</source> <target state="translated">O Mecanismo deve ser anexado a uma Janela Interativa.</target> <note /> </trans-unit> <trans-unit id="Changes_the_current_prompt_settings"> <source>Changes the current prompt settings.</source> <target state="translated">Altera as configurações de prompt atuais.</target> <note /> </trans-unit> <trans-unit id="Unexpected_text_colon_0"> <source>Unexpected text: '{0}'</source> <target state="translated">Texto inesperado: "{0}"</target> <note /> </trans-unit> <trans-unit id="The_triggerSpan_is_not_included_in_the_given_workspace"> <source>The triggerSpan is not included in the given workspace.</source> <target state="translated">O triggerSpan não está incluído no workspace fornecido.</target> <note /> </trans-unit> <trans-unit id="This_session_has_already_been_dismissed"> <source>This session has already been dismissed.</source> <target state="translated">Esta sessão já foi descartada.</target> <note /> </trans-unit> <trans-unit id="The_transaction_is_already_complete"> <source>The transaction is already complete.</source> <target state="translated">A transação já está concluída.</target> <note /> </trans-unit> <trans-unit id="Not_a_source_error_line_column_unavailable"> <source>Not a source error, line/column unavailable</source> <target state="translated">Não é um erro de origem, linha/coluna disponível</target> <note /> </trans-unit> <trans-unit id="Can_t_compare_positions_from_different_text_snapshots"> <source>Can't compare positions from different text snapshots</source> <target state="translated">Não é possível comparar as posições de instantâneos de textos diferentes</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Entity_Reference"> <source>XML Doc Comments - Entity Reference</source> <target state="translated">Comentário da documentação XML - Referência de Entidade</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Name"> <source>XML Doc Comments - Name</source> <target state="translated">Comentário da documentação XML - Nome</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Processing_Instruction"> <source>XML Doc Comments - Processing Instruction</source> <target state="translated">Comentário da documentação XML - Instrução de Processamento</target> <note /> </trans-unit> <trans-unit id="Active_Statement"> <source>Active Statement</source> <target state="translated">Instrução Ativa</target> <note /> </trans-unit> <trans-unit id="Loading_Peek_information"> <source>Loading Peek information...</source> <target state="translated">Carregando informações de Espiada...</target> <note /> </trans-unit> <trans-unit id="Peek"> <source>Peek</source> <target state="translated">Espiada</target> <note /> </trans-unit> <trans-unit id="Apply1"> <source>_Apply</source> <target state="translated">_Aplicar</target> <note /> </trans-unit> <trans-unit id="Include_overload_s"> <source>Include _overload(s)</source> <target state="translated">Incluir _overload(s)</target> <note /> </trans-unit> <trans-unit id="Include_comments"> <source>Include _comments</source> <target state="translated">Incluir _comments</target> <note /> </trans-unit> <trans-unit id="Include_strings"> <source>Include _strings</source> <target state="translated">Incluir _strings</target> <note /> </trans-unit> <trans-unit id="Apply2"> <source>Apply</source> <target state="translated">Aplicar</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="Preview_Changes_0"> <source>Preview Changes - {0}</source> <target state="translated">Visualizar Alterações - {0}</target> <note /> </trans-unit> <trans-unit id="Preview_Code_Changes_colon"> <source>Preview Code Changes:</source> <target state="translated">Visualizar Alterações de Código:</target> <note /> </trans-unit> <trans-unit id="Preview_Changes"> <source>Preview Changes</source> <target state="translated">Visualizar Alterações</target> <note /> </trans-unit> <trans-unit id="Format_Paste"> <source>Format Paste</source> <target state="translated">Colar Formato</target> <note /> </trans-unit> <trans-unit id="Formatting_pasted_text"> <source>Formatting pasted text...</source> <target state="translated">Formatando texto colado...</target> <note /> </trans-unit> <trans-unit id="The_definition_of_the_object_is_hidden"> <source>The definition of the object is hidden.</source> <target state="translated">A definição do objeto está oculta.</target> <note /> </trans-unit> <trans-unit id="Automatic_Formatting"> <source>Automatic Formatting</source> <target state="translated">Formatação Automática</target> <note /> </trans-unit> <trans-unit id="We_can_fix_the_error_by_not_making_struct_out_ref_parameter_s_Do_you_want_to_proceed"> <source>We can fix the error by not making struct "out/ref" parameter(s). Do you want to proceed?</source> <target state="translated">Podemos corrigir o erro ao não fazer struct de parâmetro(s) "out/ref". Deseja continuar?</target> <note /> </trans-unit> <trans-unit id="Change_Signature_colon"> <source>Change Signature:</source> <target state="translated">Alterar Assinatura:</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1_colon"> <source>Rename '{0}' to '{1}':</source> <target state="translated">Renomear '{0}' para '{1}':</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field_colon"> <source>Encapsulate Field:</source> <target state="translated">Encapsular Campo:</target> <note /> </trans-unit> <trans-unit id="Call_Hierarchy"> <source>Call Hierarchy</source> <target state="translated">Hierarquia de Chamada</target> <note /> </trans-unit> <trans-unit id="Calls_To_0"> <source>Calls To '{0}'</source> <target state="translated">Chamadas para '{0}'</target> <note /> </trans-unit> <trans-unit id="Calls_To_Base_Member_0"> <source>Calls To Base Member '{0}'</source> <target state="translated">Chamadas para Membro Base '{0}'</target> <note /> </trans-unit> <trans-unit id="Calls_To_Interface_Implementation_0"> <source>Calls To Interface Implementation '{0}'</source> <target state="translated">Chamadas para Implementação de Interface '{0}'</target> <note /> </trans-unit> <trans-unit id="Computing_Call_Hierarchy_Information"> <source>Computing Call Hierarchy Information</source> <target state="translated">Informações sobre Hierarquia de Chamada de Computação</target> <note /> </trans-unit> <trans-unit id="Implements_0"> <source>Implements '{0}'</source> <target state="translated">Implementa '{0}'</target> <note /> </trans-unit> <trans-unit id="Initializers"> <source>Initializers</source> <target state="translated">Inicializadores</target> <note /> </trans-unit> <trans-unit id="References_To_Field_0"> <source>References To Field '{0}'</source> <target state="translated">Referências ao Campo '{0}'</target> <note /> </trans-unit> <trans-unit id="Calls_To_Overrides"> <source>Calls To Overrides</source> <target state="translated">Chamadas para Substituições</target> <note /> </trans-unit> <trans-unit id="Preview_changes1"> <source>_Preview changes</source> <target state="translated">Alterações de _Preview</target> <note /> </trans-unit> <trans-unit id="Apply3"> <source>Apply</source> <target state="translated">Aplicar</target> <note /> </trans-unit> <trans-unit id="Cancel"> <source>Cancel</source> <target state="translated">Cancelar</target> <note /> </trans-unit> <trans-unit id="Changes"> <source>Changes</source> <target state="translated">Alterações</target> <note /> </trans-unit> <trans-unit id="Preview_changes2"> <source>Preview changes</source> <target state="translated">Visualizar alterações</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="IntelliSense_Commit_Formatting"> <source>IntelliSense Commit Formatting</source> <target state="translated">Formatação de Confirmação IntelliSense</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking"> <source>Rename Tracking</source> <target state="translated">Renomear Acompanhamento</target> <note /> </trans-unit> <trans-unit id="Removing_0_from_1_with_content_colon"> <source>Removing '{0}' from '{1}' with content:</source> <target state="translated">Removendo '{0}' de '{1}' com conteúdo:</target> <note /> </trans-unit> <trans-unit id="_0_does_not_support_the_1_operation_However_it_may_contain_nested_2_s_see_2_3_that_support_this_operation"> <source>'{0}' does not support the '{1}' operation. However, it may contain nested '{2}'s (see '{2}.{3}') that support this operation.</source> <target state="translated">'{0}' não dá suporte à operação '{1}'. No entanto, ele pode conter '{2}'s aninhados (consulte '{2}.{3}') que dá suporte a esta operação.</target> <note /> </trans-unit> <trans-unit id="Brace_Completion"> <source>Brace Completion</source> <target state="translated">Preenchimento de Chaves</target> <note /> </trans-unit> <trans-unit id="Cannot_apply_operation_while_a_rename_session_is_active"> <source>Cannot apply operation while a rename session is active.</source> <target state="translated">Não é possível aplicar a operação enquanto uma sessão de renomeação está ativa.</target> <note /> </trans-unit> <trans-unit id="The_rename_tracking_session_was_cancelled_and_is_no_longer_available"> <source>The rename tracking session was cancelled and is no longer available.</source> <target state="translated">A sessão de acompanhamento de renomeação foi cancelada e não está mais disponível.</target> <note /> </trans-unit> <trans-unit id="Highlighted_Written_Reference"> <source>Highlighted Written Reference</source> <target state="translated">Referência Escrita Realçada</target> <note /> </trans-unit> <trans-unit id="Cursor_must_be_on_a_member_name"> <source>Cursor must be on a member name.</source> <target state="translated">O cursor deve estar em um nome do membro.</target> <note /> </trans-unit> <trans-unit id="Brace_Matching"> <source>Brace Matching</source> <target state="translated">Correspondência de Chaves</target> <note /> </trans-unit> <trans-unit id="Locating_implementations"> <source>Locating implementations...</source> <target state="translated">Localizando implementações...</target> <note /> </trans-unit> <trans-unit id="Go_To_Implementation"> <source>Go To Implementation</source> <target state="translated">Ir Para Implementação</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_implementations"> <source>The symbol has no implementations.</source> <target state="translated">O símbolo não tem implementações.</target> <note /> </trans-unit> <trans-unit id="New_name_colon_0"> <source>New name: {0}</source> <target state="translated">Novo nome: {0}</target> <note /> </trans-unit> <trans-unit id="Modify_any_highlighted_location_to_begin_renaming"> <source>Modify any highlighted location to begin renaming.</source> <target state="translated">Modifique qualquer local realçado para iniciar a renomeação.</target> <note /> </trans-unit> <trans-unit id="Paste"> <source>Paste</source> <target state="translated">Colar</target> <note /> </trans-unit> <trans-unit id="Navigating"> <source>Navigating...</source> <target state="translated">Navegando...</target> <note /> </trans-unit> <trans-unit id="Suggestion_ellipses"> <source>Suggestion ellipses (…)</source> <target state="translated">Reticências de sugestão (…)</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>'{0}' references</source> <target state="translated">'{0}' referências</target> <note /> </trans-unit> <trans-unit id="_0_implementations"> <source>'{0}' implementations</source> <target state="translated">'Implementações de '{0}'</target> <note /> </trans-unit> <trans-unit id="_0_declarations"> <source>'{0}' declarations</source> <target state="translated">'Declarações de '{0}'</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Conflict"> <source>Inline Rename Conflict</source> <target state="translated">Conflito de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Background_and_Border"> <source>Inline Rename Field Background and Border</source> <target state="translated">Borda e Tela de Fundo do Campo de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Text"> <source>Inline Rename Field Text</source> <target state="translated">Texto do Campo de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Block_Comment_Editing"> <source>Block Comment Editing</source> <target state="translated">Bloquear Edição de Comentário</target> <note /> </trans-unit> <trans-unit id="Comment_Uncomment_Selection"> <source>Comment/Uncomment Selection</source> <target state="translated">Comentar/Remover Marca de Comentário da Seleção</target> <note /> </trans-unit> <trans-unit id="Code_Completion"> <source>Code Completion</source> <target state="translated">Conclusão de Código</target> <note /> </trans-unit> <trans-unit id="Execute_In_Interactive"> <source>Execute In Interactive</source> <target state="translated">Executar em Interativo</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="Go_To_Adjacent_Member"> <source>Go To Adjacent Member</source> <target state="translated">Ir para Membro Adjacente</target> <note /> </trans-unit> <trans-unit id="Interactive"> <source>Interactive</source> <target state="translated">Interativo</target> <note /> </trans-unit> <trans-unit id="Paste_in_Interactive"> <source>Paste in Interactive</source> <target state="translated">Colar em Interativo</target> <note /> </trans-unit> <trans-unit id="Navigate_To_Highlight_Reference"> <source>Navigate To Highlighted Reference</source> <target state="translated">Navegar para Referência Realçada</target> <note /> </trans-unit> <trans-unit id="Outlining"> <source>Outlining</source> <target state="translated">Estrutura de Tópicos</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking_Cancellation"> <source>Rename Tracking Cancellation</source> <target state="translated">Renomear Cancelamento de Acompanhamento</target> <note /> </trans-unit> <trans-unit id="Signature_Help"> <source>Signature Help</source> <target state="translated">Ajuda da Assinatura</target> <note /> </trans-unit> <trans-unit id="Smart_Token_Formatter"> <source>Smart Token Formatter</source> <target state="translated">Formatador de Token Inteligente</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Def/Implementation/LanguageService/AbstractLanguageService`2.VsLanguageDebugInfo.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.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; using IVsDebugName = Microsoft.VisualStudio.TextManager.Interop.IVsDebugName; using IVsEnumBSTR = Microsoft.VisualStudio.TextManager.Interop.IVsEnumBSTR; using IVsTextBuffer = Microsoft.VisualStudio.TextManager.Interop.IVsTextBuffer; using RESOLVENAMEFLAGS = Microsoft.VisualStudio.TextManager.Interop.RESOLVENAMEFLAGS; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService { internal abstract partial class AbstractLanguageService<TPackage, TLanguageService> { internal sealed class VsLanguageDebugInfo : IVsLanguageDebugInfo { private readonly Guid _languageId; private readonly TLanguageService _languageService; private readonly ILanguageDebugInfoService? _languageDebugInfo; private readonly IBreakpointResolutionService? _breakpointService; private readonly IProximityExpressionsService? _proximityExpressionsService; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; public VsLanguageDebugInfo( Guid languageId, TLanguageService languageService, HostLanguageServices languageServiceProvider, IUIThreadOperationExecutor uiThreadOperationExecutor) { Contract.ThrowIfNull(languageService); Contract.ThrowIfNull(languageServiceProvider); _languageId = languageId; _languageService = languageService; _languageDebugInfo = languageServiceProvider.GetService<ILanguageDebugInfoService>(); _breakpointService = languageServiceProvider.GetService<IBreakpointResolutionService>(); _proximityExpressionsService = languageServiceProvider.GetService<IProximityExpressionsService>(); _uiThreadOperationExecutor = uiThreadOperationExecutor; } public int GetLanguageID(IVsTextBuffer pBuffer, int iLine, int iCol, out Guid pguidLanguageID) { pguidLanguageID = _languageId; return VSConstants.S_OK; } public int GetLocationOfName(string pszName, out string? pbstrMkDoc, out VsTextSpan pspanLocation) { pbstrMkDoc = null; pspanLocation = default; return VSConstants.E_NOTIMPL; } public int GetNameOfLocation(IVsTextBuffer pBuffer, int iLine, int iCol, out string? pbstrName, out int piLineOffset) { using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_GetNameOfLocation, CancellationToken.None)) { string? name = null; var lineOffset = 0; if (_languageDebugInfo != null) { _uiThreadOperationExecutor.Execute( title: ServicesVSResources.Debugger, defaultDescription: ServicesVSResources.Determining_breakpoint_location, allowCancellation: true, showProgress: false, action: waitContext => { var cancellationToken = waitContext.UserCancellationToken; var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer); if (textBuffer != null) { var nullablePoint = textBuffer.CurrentSnapshot.TryGetPoint(iLine, iCol); if (nullablePoint.HasValue) { var point = nullablePoint.Value; var document = point.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { // NOTE(cyrusn): We have to wait here because the debuggers' // GetNameOfLocation is a blocking call. In the future, it // would be nice if they could make it async. var debugLocationInfo = _languageDebugInfo.GetLocationInfoAsync(document, point, cancellationToken).WaitAndGetResult(cancellationToken); if (!debugLocationInfo.IsDefault) { name = debugLocationInfo.Name; lineOffset = debugLocationInfo.LineOffset; } } } } }); if (name != null) { pbstrName = name; piLineOffset = lineOffset; return VSConstants.S_OK; } } // Note(DustinCa): Docs say that GetNameOfLocation should return S_FALSE if a name could not be found. // Also, that's what the old native code does, so we should do it here. pbstrName = null; piLineOffset = 0; return VSConstants.S_FALSE; } } public int GetProximityExpressions(IVsTextBuffer pBuffer, int iLine, int iCol, int cLines, out IVsEnumBSTR? ppEnum) { // NOTE(cyrusn): cLines is ignored. This is to match existing dev10 behavior. using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_GetProximityExpressions, CancellationToken.None)) { VsEnumBSTR? enumBSTR = null; if (_proximityExpressionsService != null) { _uiThreadOperationExecutor.Execute( title: ServicesVSResources.Debugger, defaultDescription: ServicesVSResources.Determining_autos, allowCancellation: true, showProgress: false, action: context => { var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer); if (textBuffer != null) { var snapshot = textBuffer.CurrentSnapshot; var nullablePoint = snapshot.TryGetPoint(iLine, iCol); if (nullablePoint.HasValue) { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var point = nullablePoint.Value; var proximityExpressions = _proximityExpressionsService.GetProximityExpressionsAsync(document, point.Position, context.UserCancellationToken).WaitAndGetResult(context.UserCancellationToken); if (proximityExpressions != null) { enumBSTR = new VsEnumBSTR(proximityExpressions); } } } } }); } ppEnum = enumBSTR; return ppEnum != null ? VSConstants.S_OK : VSConstants.E_FAIL; } } public int IsMappedLocation(IVsTextBuffer pBuffer, int iLine, int iCol) => VSConstants.E_NOTIMPL; public int ResolveName(string pszName, uint dwFlags, out IVsEnumDebugName? ppNames) { using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_ResolveName, CancellationToken.None)) { // In VS, this method frequently get's called with an empty string to test if the language service // supports this method (some language services, like F#, implement IVsLanguageDebugInfo but don't // implement this method). In that scenario, there's no sense doing work, so we'll just return // S_FALSE (as the old VB language service did). if (string.IsNullOrEmpty(pszName)) { ppNames = null; return VSConstants.S_FALSE; } VsEnumDebugName? enumName = null; _uiThreadOperationExecutor.Execute( title: ServicesVSResources.Debugger, defaultDescription: ServicesVSResources.Resolving_breakpoint_location, allowCancellation: true, showProgress: false, action: waitContext => { var cancellationToken = waitContext.UserCancellationToken; if (dwFlags == (uint)RESOLVENAMEFLAGS.RNF_BREAKPOINT) { var solution = _languageService.Workspace.CurrentSolution; // NOTE(cyrusn): We have to wait here because the debuggers' ResolveName // call is synchronous. In the future it would be nice to make it async. if (_breakpointService != null) { var breakpoints = _breakpointService.ResolveBreakpointsAsync(solution, pszName, cancellationToken).WaitAndGetResult(cancellationToken); var debugNames = breakpoints.Select(bp => CreateDebugName(bp, solution, cancellationToken)).WhereNotNull().ToList(); enumName = new VsEnumDebugName(debugNames); } } }); ppNames = enumName; return ppNames != null ? VSConstants.S_OK : VSConstants.E_NOTIMPL; } } private IVsDebugName CreateDebugName(BreakpointResolutionResult breakpoint, Solution solution, CancellationToken cancellationToken) { var document = breakpoint.Document; var filePath = _languageService.Workspace.GetFilePath(document.Id); var text = document.GetTextSynchronously(cancellationToken); var span = text.GetVsTextSpanForSpan(breakpoint.TextSpan); // If we're inside an Venus code nugget, we need to map the span to the surface buffer. // Otherwise, we'll just use the original span. if (!span.TryMapSpanFromSecondaryBufferToPrimaryBuffer(solution.Workspace, document.Id, out var mappedSpan)) { mappedSpan = span; } return new VsDebugName(breakpoint.LocationNameOpt, filePath, mappedSpan); } public int ValidateBreakpointLocation(IVsTextBuffer pBuffer, int iLine, int iCol, VsTextSpan[] pCodeSpan) { using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_ValidateBreakpointLocation, CancellationToken.None)) { var result = VSConstants.E_NOTIMPL; _uiThreadOperationExecutor.Execute( title: ServicesVSResources.Debugger, defaultDescription: ServicesVSResources.Validating_breakpoint_location, allowCancellation: true, showProgress: false, action: waitContext => { result = ValidateBreakpointLocationWorker(pBuffer, iLine, iCol, pCodeSpan, waitContext.UserCancellationToken); }); return result; } } private int ValidateBreakpointLocationWorker( IVsTextBuffer pBuffer, int iLine, int iCol, VsTextSpan[] pCodeSpan, CancellationToken cancellationToken) { if (_breakpointService == null) { return VSConstants.E_FAIL; } var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer); if (textBuffer != null) { var snapshot = textBuffer.CurrentSnapshot; var nullablePoint = snapshot.TryGetPoint(iLine, iCol); if (nullablePoint == null) { // The point disappeared between sessions. Do not allow a breakpoint here. return VSConstants.E_FAIL; } var document = snapshot.AsText().GetDocumentWithFrozenPartialSemantics(cancellationToken); if (document != null) { var point = nullablePoint.Value; var length = 0; if (pCodeSpan != null && pCodeSpan.Length > 0) { // If we have a non-empty span then it means that the debugger is asking us to adjust an // existing span. In Everett we didn't do this so we had some good and some bad // behavior. For example if you had a breakpoint on: "int i = 1;" and you changed it to "int // i = 1, j = 2;", then the breakpoint wouldn't adjust. That was bad. However, if you had the // breakpoint on an open or close curly brace then it would always "stick" to that brace // which was good. // // So we want to keep the best parts of both systems. We want to appropriately "stick" // to tokens and we also want to adjust spans intelligently. // // However, it turns out the latter is hard to do when there are parse errors in the // code. Things like missing name nodes cause a lot of havoc and make it difficult to // track a closing curly brace. // // So the way we do this is that we default to not intelligently adjusting the spans // while there are parse errors. But when there are no parse errors then the span is // adjusted. var initialBreakpointSpan = snapshot.GetSpan(pCodeSpan[0]); if (initialBreakpointSpan.Length > 0 && document.SupportsSyntaxTree) { var tree = document.GetSyntaxTreeSynchronously(cancellationToken); Contract.ThrowIfNull(tree); if (tree.GetDiagnostics(cancellationToken).Any(d => d.Severity == DiagnosticSeverity.Error)) { // Keep the span as is. return VSConstants.S_OK; } } // If a span is provided, and the requested position falls in that span, then just // move the requested position to the start of the span. // Length will be used to determine if we need further analysis, which is only required when text spans multiple lines. if (initialBreakpointSpan.Contains(point)) { point = initialBreakpointSpan.Start; length = pCodeSpan[0].iEndLine > pCodeSpan[0].iStartLine ? initialBreakpointSpan.Length : 0; } } // NOTE(cyrusn): we need to wait here because ValidateBreakpointLocation is // synchronous. In the future, it would be nice for the debugger to provide // an async entry point for this. var breakpoint = _breakpointService.ResolveBreakpointAsync(document, new TextSpan(point.Position, length), cancellationToken).WaitAndGetResult(cancellationToken); if (breakpoint == null) { // There should *not* be a breakpoint here. E_FAIL to let the debugger know // that. return VSConstants.E_FAIL; } if (breakpoint.IsLineBreakpoint) { // Let the debugger take care of this. They'll put a line breakpoint // here. This is useful for when the user does something like put a // breakpoint in inactive code. We want to allow this as they might // just have different defines during editing versus debugging. // TODO(cyrusn): Do we need to set the pCodeSpan in this case? return VSConstants.E_NOTIMPL; } // There should be a breakpoint at the location passed back. if (pCodeSpan != null && pCodeSpan.Length > 0) { pCodeSpan[0] = breakpoint.TextSpan.ToSnapshotSpan(snapshot).ToVsTextSpan(); } return VSConstants.S_OK; } } return VSConstants.E_NOTIMPL; } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; using IVsDebugName = Microsoft.VisualStudio.TextManager.Interop.IVsDebugName; using IVsEnumBSTR = Microsoft.VisualStudio.TextManager.Interop.IVsEnumBSTR; using IVsTextBuffer = Microsoft.VisualStudio.TextManager.Interop.IVsTextBuffer; using RESOLVENAMEFLAGS = Microsoft.VisualStudio.TextManager.Interop.RESOLVENAMEFLAGS; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService { internal abstract partial class AbstractLanguageService<TPackage, TLanguageService> { internal sealed class VsLanguageDebugInfo : IVsLanguageDebugInfo { private readonly Guid _languageId; private readonly TLanguageService _languageService; private readonly ILanguageDebugInfoService? _languageDebugInfo; private readonly IBreakpointResolutionService? _breakpointService; private readonly IProximityExpressionsService? _proximityExpressionsService; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; public VsLanguageDebugInfo( Guid languageId, TLanguageService languageService, HostLanguageServices languageServiceProvider, IUIThreadOperationExecutor uiThreadOperationExecutor) { Contract.ThrowIfNull(languageService); Contract.ThrowIfNull(languageServiceProvider); _languageId = languageId; _languageService = languageService; _languageDebugInfo = languageServiceProvider.GetService<ILanguageDebugInfoService>(); _breakpointService = languageServiceProvider.GetService<IBreakpointResolutionService>(); _proximityExpressionsService = languageServiceProvider.GetService<IProximityExpressionsService>(); _uiThreadOperationExecutor = uiThreadOperationExecutor; } public int GetLanguageID(IVsTextBuffer pBuffer, int iLine, int iCol, out Guid pguidLanguageID) { pguidLanguageID = _languageId; return VSConstants.S_OK; } public int GetLocationOfName(string pszName, out string? pbstrMkDoc, out VsTextSpan pspanLocation) { pbstrMkDoc = null; pspanLocation = default; return VSConstants.E_NOTIMPL; } public int GetNameOfLocation(IVsTextBuffer pBuffer, int iLine, int iCol, out string? pbstrName, out int piLineOffset) { using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_GetNameOfLocation, CancellationToken.None)) { string? name = null; var lineOffset = 0; if (_languageDebugInfo != null) { _uiThreadOperationExecutor.Execute( title: ServicesVSResources.Debugger, defaultDescription: ServicesVSResources.Determining_breakpoint_location, allowCancellation: true, showProgress: false, action: waitContext => { var cancellationToken = waitContext.UserCancellationToken; var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer); if (textBuffer != null) { var nullablePoint = textBuffer.CurrentSnapshot.TryGetPoint(iLine, iCol); if (nullablePoint.HasValue) { var point = nullablePoint.Value; var document = point.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { // NOTE(cyrusn): We have to wait here because the debuggers' // GetNameOfLocation is a blocking call. In the future, it // would be nice if they could make it async. var debugLocationInfo = _languageDebugInfo.GetLocationInfoAsync(document, point, cancellationToken).WaitAndGetResult(cancellationToken); if (!debugLocationInfo.IsDefault) { name = debugLocationInfo.Name; lineOffset = debugLocationInfo.LineOffset; } } } } }); if (name != null) { pbstrName = name; piLineOffset = lineOffset; return VSConstants.S_OK; } } // Note(DustinCa): Docs say that GetNameOfLocation should return S_FALSE if a name could not be found. // Also, that's what the old native code does, so we should do it here. pbstrName = null; piLineOffset = 0; return VSConstants.S_FALSE; } } public int GetProximityExpressions(IVsTextBuffer pBuffer, int iLine, int iCol, int cLines, out IVsEnumBSTR? ppEnum) { // NOTE(cyrusn): cLines is ignored. This is to match existing dev10 behavior. using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_GetProximityExpressions, CancellationToken.None)) { VsEnumBSTR? enumBSTR = null; if (_proximityExpressionsService != null) { _uiThreadOperationExecutor.Execute( title: ServicesVSResources.Debugger, defaultDescription: ServicesVSResources.Determining_autos, allowCancellation: true, showProgress: false, action: context => { var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer); if (textBuffer != null) { var snapshot = textBuffer.CurrentSnapshot; var nullablePoint = snapshot.TryGetPoint(iLine, iCol); if (nullablePoint.HasValue) { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var point = nullablePoint.Value; var proximityExpressions = _proximityExpressionsService.GetProximityExpressionsAsync(document, point.Position, context.UserCancellationToken).WaitAndGetResult(context.UserCancellationToken); if (proximityExpressions != null) { enumBSTR = new VsEnumBSTR(proximityExpressions); } } } } }); } ppEnum = enumBSTR; return ppEnum != null ? VSConstants.S_OK : VSConstants.E_FAIL; } } public int IsMappedLocation(IVsTextBuffer pBuffer, int iLine, int iCol) => VSConstants.E_NOTIMPL; public int ResolveName(string pszName, uint dwFlags, out IVsEnumDebugName? ppNames) { using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_ResolveName, CancellationToken.None)) { // In VS, this method frequently get's called with an empty string to test if the language service // supports this method (some language services, like F#, implement IVsLanguageDebugInfo but don't // implement this method). In that scenario, there's no sense doing work, so we'll just return // S_FALSE (as the old VB language service did). if (string.IsNullOrEmpty(pszName)) { ppNames = null; return VSConstants.S_FALSE; } VsEnumDebugName? enumName = null; _uiThreadOperationExecutor.Execute( title: ServicesVSResources.Debugger, defaultDescription: ServicesVSResources.Resolving_breakpoint_location, allowCancellation: true, showProgress: false, action: waitContext => { var cancellationToken = waitContext.UserCancellationToken; if (dwFlags == (uint)RESOLVENAMEFLAGS.RNF_BREAKPOINT) { var solution = _languageService.Workspace.CurrentSolution; // NOTE(cyrusn): We have to wait here because the debuggers' ResolveName // call is synchronous. In the future it would be nice to make it async. if (_breakpointService != null) { var breakpoints = _breakpointService.ResolveBreakpointsAsync(solution, pszName, cancellationToken).WaitAndGetResult(cancellationToken); var debugNames = breakpoints.Select(bp => CreateDebugName(bp, solution, cancellationToken)).WhereNotNull().ToList(); enumName = new VsEnumDebugName(debugNames); } } }); ppNames = enumName; return ppNames != null ? VSConstants.S_OK : VSConstants.E_NOTIMPL; } } private IVsDebugName CreateDebugName(BreakpointResolutionResult breakpoint, Solution solution, CancellationToken cancellationToken) { var document = breakpoint.Document; var filePath = _languageService.Workspace.GetFilePath(document.Id); var text = document.GetTextSynchronously(cancellationToken); var span = text.GetVsTextSpanForSpan(breakpoint.TextSpan); // If we're inside an Venus code nugget, we need to map the span to the surface buffer. // Otherwise, we'll just use the original span. if (!span.TryMapSpanFromSecondaryBufferToPrimaryBuffer(solution.Workspace, document.Id, out var mappedSpan)) { mappedSpan = span; } return new VsDebugName(breakpoint.LocationNameOpt, filePath, mappedSpan); } public int ValidateBreakpointLocation(IVsTextBuffer pBuffer, int iLine, int iCol, VsTextSpan[] pCodeSpan) { using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_ValidateBreakpointLocation, CancellationToken.None)) { var result = VSConstants.E_NOTIMPL; _uiThreadOperationExecutor.Execute( title: ServicesVSResources.Debugger, defaultDescription: ServicesVSResources.Validating_breakpoint_location, allowCancellation: true, showProgress: false, action: waitContext => { result = ValidateBreakpointLocationWorker(pBuffer, iLine, iCol, pCodeSpan, waitContext.UserCancellationToken); }); return result; } } private int ValidateBreakpointLocationWorker( IVsTextBuffer pBuffer, int iLine, int iCol, VsTextSpan[] pCodeSpan, CancellationToken cancellationToken) { if (_breakpointService == null) { return VSConstants.E_FAIL; } var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer); if (textBuffer != null) { var snapshot = textBuffer.CurrentSnapshot; var nullablePoint = snapshot.TryGetPoint(iLine, iCol); if (nullablePoint == null) { // The point disappeared between sessions. Do not allow a breakpoint here. return VSConstants.E_FAIL; } var document = snapshot.AsText().GetDocumentWithFrozenPartialSemantics(cancellationToken); if (document != null) { var point = nullablePoint.Value; var length = 0; if (pCodeSpan != null && pCodeSpan.Length > 0) { // If we have a non-empty span then it means that the debugger is asking us to adjust an // existing span. In Everett we didn't do this so we had some good and some bad // behavior. For example if you had a breakpoint on: "int i = 1;" and you changed it to "int // i = 1, j = 2;", then the breakpoint wouldn't adjust. That was bad. However, if you had the // breakpoint on an open or close curly brace then it would always "stick" to that brace // which was good. // // So we want to keep the best parts of both systems. We want to appropriately "stick" // to tokens and we also want to adjust spans intelligently. // // However, it turns out the latter is hard to do when there are parse errors in the // code. Things like missing name nodes cause a lot of havoc and make it difficult to // track a closing curly brace. // // So the way we do this is that we default to not intelligently adjusting the spans // while there are parse errors. But when there are no parse errors then the span is // adjusted. var initialBreakpointSpan = snapshot.GetSpan(pCodeSpan[0]); if (initialBreakpointSpan.Length > 0 && document.SupportsSyntaxTree) { var tree = document.GetSyntaxTreeSynchronously(cancellationToken); Contract.ThrowIfNull(tree); if (tree.GetDiagnostics(cancellationToken).Any(d => d.Severity == DiagnosticSeverity.Error)) { // Keep the span as is. return VSConstants.S_OK; } } // If a span is provided, and the requested position falls in that span, then just // move the requested position to the start of the span. // Length will be used to determine if we need further analysis, which is only required when text spans multiple lines. if (initialBreakpointSpan.Contains(point)) { point = initialBreakpointSpan.Start; length = pCodeSpan[0].iEndLine > pCodeSpan[0].iStartLine ? initialBreakpointSpan.Length : 0; } } // NOTE(cyrusn): we need to wait here because ValidateBreakpointLocation is // synchronous. In the future, it would be nice for the debugger to provide // an async entry point for this. var breakpoint = _breakpointService.ResolveBreakpointAsync(document, new TextSpan(point.Position, length), cancellationToken).WaitAndGetResult(cancellationToken); if (breakpoint == null) { // There should *not* be a breakpoint here. E_FAIL to let the debugger know // that. return VSConstants.E_FAIL; } if (breakpoint.IsLineBreakpoint) { // Let the debugger take care of this. They'll put a line breakpoint // here. This is useful for when the user does something like put a // breakpoint in inactive code. We want to allow this as they might // just have different defines during editing versus debugging. // TODO(cyrusn): Do we need to set the pCodeSpan in this case? return VSConstants.E_NOTIMPL; } // There should be a breakpoint at the location passed back. if (pCodeSpan != null && pCodeSpan.Length > 0) { pCodeSpan[0] = breakpoint.TextSpan.ToSnapshotSpan(snapshot).ToVsTextSpan(); } return VSConstants.S_OK; } } return VSConstants.E_NOTIMPL; } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/TestUtilities/Formatting/CoreFormatterTestsBase.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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.Formatting; using Microsoft.CodeAnalysis.Editor.Implementation.SmartIndent; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Projection; using Moq; using Roslyn.Test.EditorUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Formatting { public abstract class CoreFormatterTestsBase { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(TestFormattingRuleFactoryServiceFactory)); private readonly ITestOutputHelper _output; protected CoreFormatterTestsBase(ITestOutputHelper output) => _output = output; protected abstract string GetLanguageName(); protected abstract SyntaxNode ParseCompilationUnit(string expected); protected static void TestIndentation( int point, int? expectedIndentation, ITextView textView, TestHostDocument subjectDocument) { var textUndoHistory = new Mock<ITextUndoHistoryRegistry>(); var editorOperationsFactory = new Mock<IEditorOperationsFactoryService>(); var editorOperations = new Mock<IEditorOperations>(); editorOperationsFactory.Setup(x => x.GetEditorOperations(textView)).Returns(editorOperations.Object); var snapshot = subjectDocument.GetTextBuffer().CurrentSnapshot; var indentationLineFromBuffer = snapshot.GetLineFromPosition(point); var provider = new SmartIndent(textView); var actualIndentation = provider.GetDesiredIndentation(indentationLineFromBuffer); Assert.Equal(expectedIndentation, actualIndentation.Value); } protected static void TestIndentation(TestWorkspace workspace, int indentationLine, int? expectedIndentation) { var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot; var bufferGraph = new Mock<IBufferGraph>(MockBehavior.Strict); bufferGraph.Setup(x => x.MapUpToSnapshot(It.IsAny<SnapshotPoint>(), It.IsAny<PointTrackingMode>(), It.IsAny<PositionAffinity>(), It.IsAny<ITextSnapshot>())) .Returns<SnapshotPoint, PointTrackingMode, PositionAffinity, ITextSnapshot>((p, m, a, s) => { if (workspace.Services.GetService<IHostDependentFormattingRuleFactoryService>() is TestFormattingRuleFactoryServiceFactory.Factory factory && factory.BaseIndentation != 0 && factory.TextSpan.Contains(p.Position)) { var line = p.GetContainingLine(); var projectedOffset = line.GetFirstNonWhitespaceOffset().Value - factory.BaseIndentation; return new SnapshotPoint(p.Snapshot, p.Position - projectedOffset); } return p; }); var projectionBuffer = new Mock<ITextBuffer>(MockBehavior.Strict); projectionBuffer.Setup(x => x.ContentType.DisplayName).Returns("None"); var textView = new Mock<ITextView>(MockBehavior.Strict); textView.Setup(x => x.Options).Returns(TestEditorOptions.Instance); textView.Setup(x => x.BufferGraph).Returns(bufferGraph.Object); textView.SetupGet(x => x.TextSnapshot.TextBuffer).Returns(projectionBuffer.Object); var provider = new SmartIndent(textView.Object); var indentationLineFromBuffer = snapshot.GetLineFromLineNumber(indentationLine); var actualIndentation = provider.GetDesiredIndentation(indentationLineFromBuffer); Assert.Equal(expectedIndentation, actualIndentation); } private protected void AssertFormatWithView(string expectedWithMarker, string codeWithMarker, params (PerLanguageOption2<bool> option, bool enabled)[] options) { using var workspace = CreateWorkspace(codeWithMarker); if (options != null) { var optionSet = workspace.Options; foreach (var option in options) { optionSet = optionSet.WithChangedOption(option.option, GetLanguageName(), option.enabled); } workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet)); } // set up caret position var testDocument = workspace.Documents.Single(); var view = testDocument.GetTextView(); view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); // get original buffer var buffer = workspace.Documents.First().GetTextBuffer(); var commandHandler = workspace.GetService<FormatCommandHandler>(); var commandArgs = new FormatDocumentCommandArgs(view, view.TextBuffer); commandHandler.ExecuteCommand(commandArgs, TestCommandExecutionContext.Create()); MarkupTestFile.GetPosition(expectedWithMarker, out var expected, out int expectedPosition); Assert.Equal(expected, view.TextSnapshot.GetText()); var caretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == caretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition)); } private TestWorkspace CreateWorkspace(string codeWithMarker) => this.GetLanguageName() == LanguageNames.CSharp ? TestWorkspace.CreateCSharp(codeWithMarker, composition: s_composition) : TestWorkspace.CreateVisualBasic(codeWithMarker, composition: s_composition); internal void AssertFormatWithTransformation(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, SyntaxNode root) { var newRootNode = Formatter.Format(root, SpecializedCollections.SingletonEnumerable(root.FullSpan), workspace, optionSet, rules, CancellationToken.None); Assert.Equal(expected, newRootNode.ToFullString()); // test doesn't use parsing option. add one if needed later var newRootNodeFromString = ParseCompilationUnit(expected); // simple check to see whether two nodes are equivalent each other. Assert.True(newRootNodeFromString.IsEquivalentTo(newRootNode)); } internal static void AssertFormat(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, ITextBuffer clonedBuffer, SyntaxNode root) { var changes = Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(root.FullSpan), workspace, optionSet, rules, CancellationToken.None); var actual = ApplyResultAndGetFormattedText(clonedBuffer, changes); Assert.Equal(expected, actual); } private static string ApplyResultAndGetFormattedText(ITextBuffer buffer, IList<TextChange> changes) { using (var edit = buffer.CreateEdit()) { foreach (var change in changes) { edit.Replace(change.Span.ToSpan(), change.NewText); } edit.Apply(); } return buffer.CurrentSnapshot.GetText(); } protected async Task AssertFormatAsync(string expected, string code, IEnumerable<TextSpan> spans, Dictionary<OptionKey, object> changedOptionSet = null, int? baseIndentation = null) { using var workspace = CreateWorkspace(code); var hostdoc = workspace.Documents.First(); var buffer = hostdoc.GetTextBuffer(); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var syntaxTree = await document.GetSyntaxTreeAsync(); // create new buffer with cloned content var clonedBuffer = EditorFactory.CreateBuffer( workspace.ExportProvider, buffer.ContentType, buffer.CurrentSnapshot.GetText()); var formattingRuleProvider = workspace.Services.GetService<IHostDependentFormattingRuleFactoryService>(); if (baseIndentation.HasValue) { var factory = (TestFormattingRuleFactoryServiceFactory.Factory)formattingRuleProvider; factory.BaseIndentation = baseIndentation.Value; factory.TextSpan = spans.First(); } var options = workspace.Options; if (changedOptionSet != null) { foreach (var entry in changedOptionSet) { options = options.WithChangedOption(entry.Key, entry.Value); } } var root = await syntaxTree.GetRootAsync(); var rules = formattingRuleProvider.CreateRule(workspace.CurrentSolution.GetDocument(syntaxTree), 0).Concat(Formatter.GetDefaultFormattingRules(workspace, root.Language)); AssertFormat(workspace, expected, options, rules, clonedBuffer, root, spans); // format with node and transform AssertFormatWithTransformation(workspace, expected, options, rules, root, spans); } internal void AssertFormatWithTransformation(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, SyntaxNode root, IEnumerable<TextSpan> spans) { var newRootNode = Formatter.Format(root, spans, workspace, optionSet, rules, CancellationToken.None); Assert.Equal(expected, newRootNode.ToFullString()); // test doesn't use parsing option. add one if needed later var newRootNodeFromString = ParseCompilationUnit(expected); // simple check to see whether two nodes are equivalent each other. Assert.True(newRootNodeFromString.IsEquivalentTo(newRootNode)); } internal void AssertFormat(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, ITextBuffer clonedBuffer, SyntaxNode root, IEnumerable<TextSpan> spans) { var result = Formatter.GetFormattedTextChanges(root, spans, workspace, optionSet, rules, CancellationToken.None); var actual = ApplyResultAndGetFormattedText(clonedBuffer, result); if (actual != expected) { _output.WriteLine(actual); Assert.Equal(expected, actual); } } protected void AssertFormatWithPasteOrReturn(string expectedWithMarker, string codeWithMarker, bool allowDocumentChanges, bool isPaste = true) { using var workspace = CreateWorkspace(codeWithMarker); workspace.CanApplyChangeDocument = allowDocumentChanges; // set up caret position var testDocument = workspace.Documents.Single(); var view = testDocument.GetTextView(); view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); // get original buffer var buffer = workspace.Documents.First().GetTextBuffer(); if (isPaste) { var commandHandler = workspace.GetService<FormatCommandHandler>(); var commandArgs = new PasteCommandArgs(view, view.TextBuffer); commandHandler.ExecuteCommand(commandArgs, () => { }, TestCommandExecutionContext.Create()); } else { // Return Key Command var commandHandler = workspace.GetService<FormatCommandHandler>(); var commandArgs = new ReturnKeyCommandArgs(view, view.TextBuffer); commandHandler.ExecuteCommand(commandArgs, () => { }, TestCommandExecutionContext.Create()); } MarkupTestFile.GetPosition(expectedWithMarker, out var expected, out int expectedPosition); Assert.Equal(expected, view.TextSnapshot.GetText()); var caretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == caretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition)); } protected async Task AssertFormatWithBaseIndentAsync( string expected, string markupCode, int baseIndentation, Dictionary<OptionKey, object> options = null) { MarkupTestFile.GetSpan(markupCode, out var code, out var span); await AssertFormatAsync( expected, code, new List<TextSpan> { span }, changedOptionSet: options, baseIndentation: baseIndentation); } /// <summary> /// Asserts formatting on an arbitrary <see cref="SyntaxNode"/> that is not part of a <see cref="SyntaxTree"/> /// </summary> /// <param name="node">the <see cref="SyntaxNode"/> to format.</param> /// <remarks>uses an <see cref="AdhocWorkspace"/> for formatting context, since the <paramref name="node"/> is not associated with a <see cref="SyntaxTree"/> </remarks> protected static void AssertFormatOnArbitraryNode(SyntaxNode node, string expected) { var result = Formatter.Format(node, new AdhocWorkspace()); var actual = result.GetText().ToString(); Assert.Equal(expected, actual); } } }
// Licensed to the .NET Foundation under one or more 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.Formatting; using Microsoft.CodeAnalysis.Editor.Implementation.SmartIndent; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Projection; using Moq; using Roslyn.Test.EditorUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Formatting { public abstract class CoreFormatterTestsBase { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(TestFormattingRuleFactoryServiceFactory)); private readonly ITestOutputHelper _output; protected CoreFormatterTestsBase(ITestOutputHelper output) => _output = output; protected abstract string GetLanguageName(); protected abstract SyntaxNode ParseCompilationUnit(string expected); protected static void TestIndentation( int point, int? expectedIndentation, ITextView textView, TestHostDocument subjectDocument) { var textUndoHistory = new Mock<ITextUndoHistoryRegistry>(); var editorOperationsFactory = new Mock<IEditorOperationsFactoryService>(); var editorOperations = new Mock<IEditorOperations>(); editorOperationsFactory.Setup(x => x.GetEditorOperations(textView)).Returns(editorOperations.Object); var snapshot = subjectDocument.GetTextBuffer().CurrentSnapshot; var indentationLineFromBuffer = snapshot.GetLineFromPosition(point); var provider = new SmartIndent(textView); var actualIndentation = provider.GetDesiredIndentation(indentationLineFromBuffer); Assert.Equal(expectedIndentation, actualIndentation.Value); } protected static void TestIndentation(TestWorkspace workspace, int indentationLine, int? expectedIndentation) { var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot; var bufferGraph = new Mock<IBufferGraph>(MockBehavior.Strict); bufferGraph.Setup(x => x.MapUpToSnapshot(It.IsAny<SnapshotPoint>(), It.IsAny<PointTrackingMode>(), It.IsAny<PositionAffinity>(), It.IsAny<ITextSnapshot>())) .Returns<SnapshotPoint, PointTrackingMode, PositionAffinity, ITextSnapshot>((p, m, a, s) => { if (workspace.Services.GetService<IHostDependentFormattingRuleFactoryService>() is TestFormattingRuleFactoryServiceFactory.Factory factory && factory.BaseIndentation != 0 && factory.TextSpan.Contains(p.Position)) { var line = p.GetContainingLine(); var projectedOffset = line.GetFirstNonWhitespaceOffset().Value - factory.BaseIndentation; return new SnapshotPoint(p.Snapshot, p.Position - projectedOffset); } return p; }); var projectionBuffer = new Mock<ITextBuffer>(MockBehavior.Strict); projectionBuffer.Setup(x => x.ContentType.DisplayName).Returns("None"); var textView = new Mock<ITextView>(MockBehavior.Strict); textView.Setup(x => x.Options).Returns(TestEditorOptions.Instance); textView.Setup(x => x.BufferGraph).Returns(bufferGraph.Object); textView.SetupGet(x => x.TextSnapshot.TextBuffer).Returns(projectionBuffer.Object); var provider = new SmartIndent(textView.Object); var indentationLineFromBuffer = snapshot.GetLineFromLineNumber(indentationLine); var actualIndentation = provider.GetDesiredIndentation(indentationLineFromBuffer); Assert.Equal(expectedIndentation, actualIndentation); } private protected void AssertFormatWithView(string expectedWithMarker, string codeWithMarker, params (PerLanguageOption2<bool> option, bool enabled)[] options) { using var workspace = CreateWorkspace(codeWithMarker); if (options != null) { var optionSet = workspace.Options; foreach (var option in options) { optionSet = optionSet.WithChangedOption(option.option, GetLanguageName(), option.enabled); } workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet)); } // set up caret position var testDocument = workspace.Documents.Single(); var view = testDocument.GetTextView(); view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); // get original buffer var buffer = workspace.Documents.First().GetTextBuffer(); var commandHandler = workspace.GetService<FormatCommandHandler>(); var commandArgs = new FormatDocumentCommandArgs(view, view.TextBuffer); commandHandler.ExecuteCommand(commandArgs, TestCommandExecutionContext.Create()); MarkupTestFile.GetPosition(expectedWithMarker, out var expected, out int expectedPosition); Assert.Equal(expected, view.TextSnapshot.GetText()); var caretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == caretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition)); } private TestWorkspace CreateWorkspace(string codeWithMarker) => this.GetLanguageName() == LanguageNames.CSharp ? TestWorkspace.CreateCSharp(codeWithMarker, composition: s_composition) : TestWorkspace.CreateVisualBasic(codeWithMarker, composition: s_composition); internal void AssertFormatWithTransformation(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, SyntaxNode root) { var newRootNode = Formatter.Format(root, SpecializedCollections.SingletonEnumerable(root.FullSpan), workspace, optionSet, rules, CancellationToken.None); Assert.Equal(expected, newRootNode.ToFullString()); // test doesn't use parsing option. add one if needed later var newRootNodeFromString = ParseCompilationUnit(expected); // simple check to see whether two nodes are equivalent each other. Assert.True(newRootNodeFromString.IsEquivalentTo(newRootNode)); } internal static void AssertFormat(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, ITextBuffer clonedBuffer, SyntaxNode root) { var changes = Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(root.FullSpan), workspace, optionSet, rules, CancellationToken.None); var actual = ApplyResultAndGetFormattedText(clonedBuffer, changes); Assert.Equal(expected, actual); } private static string ApplyResultAndGetFormattedText(ITextBuffer buffer, IList<TextChange> changes) { using (var edit = buffer.CreateEdit()) { foreach (var change in changes) { edit.Replace(change.Span.ToSpan(), change.NewText); } edit.Apply(); } return buffer.CurrentSnapshot.GetText(); } protected async Task AssertFormatAsync(string expected, string code, IEnumerable<TextSpan> spans, Dictionary<OptionKey, object> changedOptionSet = null, int? baseIndentation = null) { using var workspace = CreateWorkspace(code); var hostdoc = workspace.Documents.First(); var buffer = hostdoc.GetTextBuffer(); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var syntaxTree = await document.GetSyntaxTreeAsync(); // create new buffer with cloned content var clonedBuffer = EditorFactory.CreateBuffer( workspace.ExportProvider, buffer.ContentType, buffer.CurrentSnapshot.GetText()); var formattingRuleProvider = workspace.Services.GetService<IHostDependentFormattingRuleFactoryService>(); if (baseIndentation.HasValue) { var factory = (TestFormattingRuleFactoryServiceFactory.Factory)formattingRuleProvider; factory.BaseIndentation = baseIndentation.Value; factory.TextSpan = spans.First(); } var options = workspace.Options; if (changedOptionSet != null) { foreach (var entry in changedOptionSet) { options = options.WithChangedOption(entry.Key, entry.Value); } } var root = await syntaxTree.GetRootAsync(); var rules = formattingRuleProvider.CreateRule(workspace.CurrentSolution.GetDocument(syntaxTree), 0).Concat(Formatter.GetDefaultFormattingRules(workspace, root.Language)); AssertFormat(workspace, expected, options, rules, clonedBuffer, root, spans); // format with node and transform AssertFormatWithTransformation(workspace, expected, options, rules, root, spans); } internal void AssertFormatWithTransformation(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, SyntaxNode root, IEnumerable<TextSpan> spans) { var newRootNode = Formatter.Format(root, spans, workspace, optionSet, rules, CancellationToken.None); Assert.Equal(expected, newRootNode.ToFullString()); // test doesn't use parsing option. add one if needed later var newRootNodeFromString = ParseCompilationUnit(expected); // simple check to see whether two nodes are equivalent each other. Assert.True(newRootNodeFromString.IsEquivalentTo(newRootNode)); } internal void AssertFormat(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, ITextBuffer clonedBuffer, SyntaxNode root, IEnumerable<TextSpan> spans) { var result = Formatter.GetFormattedTextChanges(root, spans, workspace, optionSet, rules, CancellationToken.None); var actual = ApplyResultAndGetFormattedText(clonedBuffer, result); if (actual != expected) { _output.WriteLine(actual); Assert.Equal(expected, actual); } } protected void AssertFormatWithPasteOrReturn(string expectedWithMarker, string codeWithMarker, bool allowDocumentChanges, bool isPaste = true) { using var workspace = CreateWorkspace(codeWithMarker); workspace.CanApplyChangeDocument = allowDocumentChanges; // set up caret position var testDocument = workspace.Documents.Single(); var view = testDocument.GetTextView(); view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); // get original buffer var buffer = workspace.Documents.First().GetTextBuffer(); if (isPaste) { var commandHandler = workspace.GetService<FormatCommandHandler>(); var commandArgs = new PasteCommandArgs(view, view.TextBuffer); commandHandler.ExecuteCommand(commandArgs, () => { }, TestCommandExecutionContext.Create()); } else { // Return Key Command var commandHandler = workspace.GetService<FormatCommandHandler>(); var commandArgs = new ReturnKeyCommandArgs(view, view.TextBuffer); commandHandler.ExecuteCommand(commandArgs, () => { }, TestCommandExecutionContext.Create()); } MarkupTestFile.GetPosition(expectedWithMarker, out var expected, out int expectedPosition); Assert.Equal(expected, view.TextSnapshot.GetText()); var caretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == caretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition)); } protected async Task AssertFormatWithBaseIndentAsync( string expected, string markupCode, int baseIndentation, Dictionary<OptionKey, object> options = null) { MarkupTestFile.GetSpan(markupCode, out var code, out var span); await AssertFormatAsync( expected, code, new List<TextSpan> { span }, changedOptionSet: options, baseIndentation: baseIndentation); } /// <summary> /// Asserts formatting on an arbitrary <see cref="SyntaxNode"/> that is not part of a <see cref="SyntaxTree"/> /// </summary> /// <param name="node">the <see cref="SyntaxNode"/> to format.</param> /// <remarks>uses an <see cref="AdhocWorkspace"/> for formatting context, since the <paramref name="node"/> is not associated with a <see cref="SyntaxTree"/> </remarks> protected static void AssertFormatOnArbitraryNode(SyntaxNode node, string expected) { var result = Formatter.Format(node, new AdhocWorkspace()); var actual = result.GetText().ToString(); Assert.Equal(expected, actual); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAwaitForeachTests.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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { [CompilerTrait(CompilerFeature.AsyncStreams)] public class CodeGenAwaitForeachTests : EmitMetadataTestBase { [Fact] public void TestWithCSharp7_3() { string source = @" using System.Collections.Generic; class C : IAsyncEnumerable<int> { public static async System.Threading.Tasks.Task Main() { await foreach (int i in new C()) { } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; }"; var expected = new[] { // (7,9): error CS8652: The feature 'async streams' is not available in C# 7.3. Please use language version 8.0 or greater. // await foreach (int i in new C()) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "await").WithArguments("async streams", "8.0").WithLocation(7, 9) }; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(expected); comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void TestWithMissingValueTask() { string lib_cs = @" using System.Collections.Generic; public class C : IAsyncEnumerable<int> { IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; }"; var lib = CreateCompilationWithTasksExtensions(new[] { lib_cs, s_IAsyncEnumerable }); lib.VerifyDiagnostics(); string source = @" class D { public static async System.Threading.Tasks.Task Main() { await foreach (int i in new C()) { } } } "; var comp = CreateCompilationWithTasksExtensions(source, references: new[] { lib.EmitToImageReference() }); comp.MakeTypeMissing(WellKnownType.System_Threading_Tasks_ValueTask); comp.VerifyDiagnostics( // (6,9): error CS0518: Predefined type 'System.Threading.Tasks.ValueTask' is not defined or imported // await foreach (int i in new C()) { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await foreach (int i in new C()) { }").WithArguments("System.Threading.Tasks.ValueTask").WithLocation(6, 9) ); } [Fact] public void TestWithIAsyncEnumerator() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; public class C { async Task M(IAsyncEnumerator<int> enumerator) { await foreach (int i in enumerator) { } } } "; var comp_checked = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp_checked.VerifyDiagnostics( // (8,33): error CS8411: Async foreach statement cannot operate on variables of type 'IAsyncEnumerator<int>' because 'IAsyncEnumerator<int>' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (int i in enumerator) { } Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "enumerator").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestWithUIntToIntConversion() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; public class C : IAsyncEnumerable<uint> { public static async Task Main() { try { REPLACE { await foreach (int i in new C()) { System.Console.Write($""0x{i:X8}""); } } } catch (System.OverflowException) { System.Console.Write(""overflow""); } } public IAsyncEnumerator<uint> GetAsyncEnumerator(System.Threading.CancellationToken token) => new AsyncEnumerator(); public sealed class AsyncEnumerator : IAsyncEnumerator<uint> { bool firstValue = true; public uint Current => 0xFFFFFFFF; public async ValueTask<bool> MoveNextAsync() { await Task.Yield(); bool result = firstValue; firstValue = false; return result; } public async ValueTask DisposeAsync() { await Task.Yield(); } } } "; var comp_checked = CreateCompilationWithTasksExtensions(new[] { source.Replace("REPLACE", "checked"), s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp_checked.VerifyDiagnostics(); CompileAndVerify(comp_checked, expectedOutput: "overflow"); var comp_unchecked = CreateCompilationWithTasksExtensions(new[] { source.Replace("REPLACE", "unchecked"), s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp_unchecked.VerifyDiagnostics(); CompileAndVerify(comp_unchecked, expectedOutput: "0xFFFFFFFF"); } [Fact] public void TestWithTwoIAsyncEnumerableImplementations() { string source = @" using System.Collections.Generic; class C : IAsyncEnumerable<int>, IAsyncEnumerable<string> { public static async System.Threading.Tasks.Task Main() { await foreach (int i in new C()) { } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; IAsyncEnumerator<string> IAsyncEnumerable<string>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics( // (7,33): error CS8413: Async foreach statement cannot operate on variables of type 'C' because it implements multiple instantiations of 'IAsyncEnumerable<T>'; try casting to a specific interface instantiation // await foreach (int i in new C()) Diagnostic(ErrorCode.ERR_MultipleIAsyncEnumOfT, "new C()").WithArguments("C", "System.Collections.Generic.IAsyncEnumerable<T>").WithLocation(7, 33) ); } [Fact] public void TestWithMissingPattern() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8411: Async foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(6, 33) ); } [Fact] public void TestWithStaticGetEnumerator() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public static Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token) { throw null; } public sealed class Enumerator { } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8411: Async foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(6, 33) ); } [Fact] public void TestWithInaccessibleGetEnumerator() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } internal Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } public sealed class Enumerator { } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): warning CS0279: 'C' does not implement the 'async streams' pattern. 'C.GetAsyncEnumerator(System.Threading.CancellationToken)' is not a public instance or extension method. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "new C()").WithArguments("C", "async streams", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33), // (6,33): error CS8411: Async foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(6, 33) ); } [Fact] public void TestWithObsoletePatternMethods() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } [System.Obsolete] public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } public sealed class Enumerator { [System.Obsolete] public System.Threading.Tasks.Task<bool> MoveNextAsync() { throw null; } [System.Obsolete] public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,15): warning CS0612: 'C.GetAsyncEnumerator(CancellationToken)' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 15), // (6,15): warning CS0612: 'C.Enumerator.MoveNextAsync()' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.Enumerator.MoveNextAsync()").WithLocation(6, 15), // (6,15): warning CS0612: 'C.Enumerator.Current' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.Enumerator.Current").WithLocation(6, 15) ); } [Fact] public void TestWithMoveNextAsync_ReturnsValueTaskOfObject() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<object> MoveNextAsync() => throw null; public int Current => throw null; } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator()").WithLocation(6, 33) ); } [Fact] public void TestWithMoveNextAsync_ReturnsObject() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<object> MoveNextAsync() => throw null; // returns Task<object> public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator()").WithLocation(6, 33) ); } [Fact] public void TestWithMoveNextAsync_Static() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } public sealed class Enumerator { public static System.Threading.Tasks.Task<bool> MoveNextAsync() { throw null; } public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33) ); } [Fact] public void TestWithCurrent_Static() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public static int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator()").WithLocation(6, 33) ); } [Fact] public void TestWithMoveNextAsync_NonPublic() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { internal System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current => throw null; } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator()").WithLocation(6, 33) ); } [Fact] public void TestWithCurrent_NonPublicProperty() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; private int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS0122: 'C.Enumerator.Current' is inaccessible due to its protection level // await foreach (var i in new C()) { } Diagnostic(ErrorCode.ERR_BadAccess, "new C()").WithArguments("C.Enumerator.Current").WithLocation(6, 33), // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33) ); } [Fact] public void TestWithCurrent_NonPublicGetter() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { private get => throw null; set => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator()").WithLocation(6, 33) ); } [Fact] public void TestWithCurrent_MissingGetter() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { set => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33) ); } [Fact] public void TestWithCurrent_MissingGetterOnInterface() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task M(C c) { await foreach (var i in c) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default); } public interface IAsyncEnumerator<out T> : System.IAsyncDisposable { System.Threading.Tasks.Task<bool> MoveNextAsync(); T Current { set; } } } namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } "; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyEmitDiagnostics( // (8,33): error CS8412: Asynchronous foreach requires that the return type 'IAsyncEnumerator<int>' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in c) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "c").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(8, 33), // (24,9): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'IAsyncEnumerator<T>.Current'. 'T' is covariant. // T Current { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("System.Collections.Generic.IAsyncEnumerator<T>.Current", "T", "covariant", "contravariantly").WithLocation(24, 9) ); } [Fact] public void TestWithCurrent_MissingPropertyOnInterface() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task M(C c) { await foreach (var i in c) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default); } public interface IAsyncEnumerator<out T> : System.IAsyncDisposable { System.Threading.Tasks.Task<bool> MoveNextAsync(); } } namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } "; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyEmitDiagnostics( // (8,33): error CS0117: 'IAsyncEnumerator<int>' does not contain a definition for 'Current' // await foreach (var i in c) Diagnostic(ErrorCode.ERR_NoSuchMember, "c").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "Current").WithLocation(8, 33), // (8,33): error CS8412: Asynchronous foreach requires that the return type 'IAsyncEnumerator<int>' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in c) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "c").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(8, 33) ); } [Fact] public void TestMoveNextAsync_ReturnsTask() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } public sealed class Enumerator { public System.Threading.Tasks.Task MoveNextAsync() { throw null; } public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33) ); } [Fact] public void TestMoveNextAsync_ReturnsTaskOfInt() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } public sealed class Enumerator { public System.Threading.Tasks.Task<int> MoveNextAsync() { throw null; } public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33) ); } [Fact] public void TestMoveNextAsync_WithOptionalParameter() { string source = @" public class C { public static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new Enumerator(); } public sealed class Enumerator { public async System.Threading.Tasks.Task<bool> MoveNextAsync(int ok = 1) { System.Console.Write($""MoveNextAsync {ok}""); await System.Threading.Tasks.Task.Yield(); return false; } public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync 1"); } [Fact] public void TestMoveNextAsync_WithParamsParameter() { string source = @" public class C { public static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new Enumerator(); } public sealed class Enumerator { public async System.Threading.Tasks.Task<bool> MoveNextAsync(params int[] ok) { System.Console.Write($""MoveNextAsync {ok.Length}""); await System.Threading.Tasks.Task.Yield(); return false; } public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync 0"); } [Fact] public void TestMoveNextAsync_Missing() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task M(C c) { await foreach (var i in c) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default); } public interface IAsyncEnumerator<out T> : System.IAsyncDisposable { T Current { get; } } } namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } "; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyEmitDiagnostics( // (8,33): error CS0117: 'IAsyncEnumerator<int>' does not contain a definition for 'MoveNextAsync' // await foreach (var i in c) Diagnostic(ErrorCode.ERR_NoSuchMember, "c").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "MoveNextAsync").WithLocation(8, 33), // (8,33): error CS8412: Asynchronous foreach requires that the return type 'IAsyncEnumerator<int>' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in c) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "c").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(8, 33) ); } [Fact] public void TestWithNonConvertibleElementType() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (string i in new C()) { } } public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,15): error CS0030: Cannot convert type 'int' to 'string' // await foreach (string i in new C()) Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("int", "string").WithLocation(6, 15) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.True(info.IsAsynchronous); Assert.Equal("C.Enumerator C.GetAsyncEnumerator()", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<System.Boolean> C.Enumerator.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 C.Enumerator.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Null(info.DisposeMethod); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.NoConversion, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); } [Fact] public void TestWithNonConvertibleElementType2() { string source = @" using System.Threading.Tasks; class C { async Task M() { await foreach (Element i in new C()) { } } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class AsyncEnumerator { public int Current { get => throw null; } public Task<bool> MoveNextAsync() => throw null; public ValueTask DisposeAsync() => throw null; } } class Element { }"; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyDiagnostics( // (7,15): error CS0030: Cannot convert type 'int' to 'Element' // await foreach (Element i in new C()) Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("int", "Element").WithLocation(7, 15) ); } [Fact] public void TestWithExplicitlyConvertibleElementType() { string source = @" using static System.Console; using System.Threading.Tasks; class C { public static async System.Threading.Tasks.Task Main() { await foreach (Element i in new C()) { Write($""Got({i}) ""); } } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new AsyncEnumerator(); } public sealed class AsyncEnumerator : System.IAsyncDisposable { int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async Task<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; bool more = await Task.FromResult(i < 4); return more; } public async ValueTask DisposeAsync() { Write($""Dispose({i}) ""); await Task.Yield(); } } } class Element { int i; public static explicit operator Element(int value) { Write($""Convert({value}) ""); return new Element(value); } private Element(int value) { i = value; } public override string ToString() => i.ToString(); }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Convert(1) Got(1) NextAsync(1) Current(2) Convert(2) Got(2) NextAsync(2) Current(3) Convert(3) Got(3) NextAsync(3) Dispose(4)"); } [Fact] public void TestWithCaptureOfIterationVariable() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async System.Threading.Tasks.Task Main() { System.Action f = null; await foreach (var i in new C()) { Write($""Got({i}) ""); if (f == null) f = () => Write($""Captured({i})""); } f(); } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new AsyncEnumerator(); } public sealed class AsyncEnumerator : System.IAsyncDisposable { int i = 0; public int Current => i; public async Task<bool> MoveNextAsync() { i++; return await Task.FromResult(i < 3); } public async ValueTask DisposeAsync() { await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Got(1) Got(2) Captured(1)"); } [Fact] public void TestWithGenericIterationVariable() { string source = @" using static System.Console; using System.Threading.Tasks; class IntContainer { public int Value { get; set; } } public class Program { public static async System.Threading.Tasks.Task Main() { await foreach (var i in new C<IntContainer>()) { Write($""Got({i.Value}) ""); } } } class C<T> where T : IntContainer, new() { public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new AsyncEnumerator(); } public sealed class AsyncEnumerator : System.IAsyncDisposable { int i = 0; public T Current { get { Write($""Current({i}) ""); var result = new T(); ((IntContainer)result).Value = i; return result; } } public async Task<bool> MoveNextAsync() { i++; Write($""NextAsync({i}) ""); return await Task.FromResult(i < 4); } public async ValueTask DisposeAsync() { Write($""Dispose({i}) ""); await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(1) Current(1) Got(1) NextAsync(2) Current(2) Got(2) NextAsync(3) Current(3) Got(3) NextAsync(4) Dispose(4)"); } [Fact] public void TestWithThrowingGetAsyncEnumerator() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async Task Main() { try { await foreach (var i in new C()) { throw null; } throw null; } catch (System.ArgumentException e) { Write(e.Message); } } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw new System.ArgumentException(""exception""); public sealed class AsyncEnumerator : System.IAsyncDisposable { public int Current => throw null; public Task<bool> MoveNextAsync() => throw null; public ValueTask DisposeAsync() => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "exception"); } [Fact] public void TestWithThrowingMoveNextAsync() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async Task Main() { try { await foreach (var i in new C()) { throw null; } throw null; } catch (System.ArgumentException e) { Write(e.Message); } } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => new AsyncEnumerator(); public sealed class AsyncEnumerator : System.IAsyncDisposable { public int Current => throw null; public Task<bool> MoveNextAsync() => throw new System.ArgumentException(""exception""); public async ValueTask DisposeAsync() { Write(""dispose ""); await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "dispose exception"); } [Fact] public void TestWithThrowingCurrent() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async Task Main() { try { await foreach (var i in new C()) { throw null; } throw null; } catch (System.ArgumentException e) { Write(e.Message); } } public AsyncEnumerator GetAsyncEnumerator() => new AsyncEnumerator(); public sealed class AsyncEnumerator : System.IAsyncDisposable { public int Current => throw new System.ArgumentException(""exception""); public async Task<bool> MoveNextAsync() { Write(""wait ""); await Task.Yield(); return true; } public async ValueTask DisposeAsync() { Write(""dispose ""); await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "wait dispose exception"); } [Fact] public void TestWithThrowingDisposeAsync() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async Task Main() { try { await foreach (var i in new C()) { throw null; } throw null; } catch (System.ArgumentException e) { Write(e.Message); } } public AsyncEnumerator GetAsyncEnumerator() => new AsyncEnumerator(); public sealed class AsyncEnumerator : System.IAsyncDisposable { public int Current => throw null; public async Task<bool> MoveNextAsync() { Write(""wait ""); await Task.Yield(); return false; } public ValueTask DisposeAsync() => throw new System.ArgumentException(""exception""); } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "wait exception"); } [Fact] public void TestWithDynamicCollection() { string source = @" class C { public static async System.Threading.Tasks.Task Main() { await foreach (var i in (dynamic)new C()) { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics( // (6,33): error CS8416: Cannot use a collection of dynamic type in an asynchronous foreach // await foreach (var i in (dynamic)new C()) Diagnostic(ErrorCode.ERR_BadDynamicAwaitForEach, "(dynamic)new C()").WithLocation(6, 33)); } [Fact] public void TestWithIncompleteInterface() { string source = @" namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { } } class C { async System.Threading.Tasks.Task M(System.Collections.Generic.IAsyncEnumerable<int> collection) { await foreach (var i in collection) { } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (12,33): error CS8411: Async foreach statement cannot operate on variables of type 'IAsyncEnumerable<int>' because 'IAsyncEnumerable<int>' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in collection) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "collection").WithArguments("System.Collections.Generic.IAsyncEnumerable<int>", "GetAsyncEnumerator").WithLocation(12, 33) ); } [Fact] public void TestWithIncompleteInterface2() { string source = @" namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default); } public interface IAsyncEnumerator<out T> { System.Threading.Tasks.Task<bool> MoveNextAsync(); } } class C { async System.Threading.Tasks.Task M(System.Collections.Generic.IAsyncEnumerable<int> collection) { await foreach (var i in collection) { } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (18,33): error CS0117: 'IAsyncEnumerator<int>' does not contain a definition for 'Current' // await foreach (var i in collection) Diagnostic(ErrorCode.ERR_NoSuchMember, "collection").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "Current").WithLocation(18, 33), // (18,33): error CS8412: Async foreach requires that the return type 'IAsyncEnumerator<int>' of 'IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken)' must have a suitable public MoveNextAsync method and public Current property // await foreach (var i in collection) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "collection").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "System.Collections.Generic.IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(18, 33) ); } [Fact] public void TestWithIncompleteInterface3() { string source = @" namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default); } public interface IAsyncEnumerator<out T> { T Current { get; } } } class C { async System.Threading.Tasks.Task M(System.Collections.Generic.IAsyncEnumerable<int> collection) { await foreach (var i in collection) { } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (18,33): error CS0117: 'IAsyncEnumerator<int>' does not contain a definition for 'MoveNextAsync' // await foreach (var i in collection) Diagnostic(ErrorCode.ERR_NoSuchMember, "collection").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "MoveNextAsync").WithLocation(18, 33), // (18,33): error CS8412: Async foreach requires that the return type 'IAsyncEnumerator<int>' of 'IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken)' must have a suitable public MoveNextAsync method and public Current property // await foreach (var i in collection) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "collection").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "System.Collections.Generic.IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(18, 33) ); } [Fact] public void TestWithSyncPattern() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetEnumerator() { throw null; } public sealed class Enumerator { bool MoveNext() => throw null; int Current => throw null; } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8411: Async foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(6, 33) ); } [Fact] public void TestRegularForeachWithAsyncPattern() { string source = @" class C { void M() { foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,27): error CS8414: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator'. Did you mean 'await foreach' rather than 'foreach'? // foreach (var i in new C()) Diagnostic(ErrorCode.ERR_ForEachMissingMemberWrongAsync, "new C()").WithArguments("C", "GetEnumerator").WithLocation(6, 27) ); } [Fact] public void TestRegularForeachWithAsyncInterface() { string source = @" using System.Collections.Generic; class C { void M(IAsyncEnumerable<int> collection) { foreach (var i in collection) { } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (7,27): error CS8414: foreach statement cannot operate on variables of type 'IAsyncEnumerable<int>' because 'IAsyncEnumerable<int>' does not contain a public instance or extension definition for 'GetEnumerator'. Did you mean 'await foreach'? // foreach (var i in collection) Diagnostic(ErrorCode.ERR_ForEachMissingMemberWrongAsync, "collection").WithArguments("System.Collections.Generic.IAsyncEnumerable<int>", "GetEnumerator").WithLocation(7, 27) ); } [Fact] public void TestWithSyncInterfaceInRegularMethod() { string source = @" using System.Collections.Generic; class C { void M(IEnumerable<int> collection) { await foreach (var i in collection) { } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (7,9): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // await foreach (var i in collection) Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(7, 9), // (7,33): error CS8415: Asynchronous foreach statement cannot operate on variables of type 'IEnumerable<int>' because 'IEnumerable<int>' does not contain a public instance or extension definition for 'GetAsyncEnumerator'. Did you mean 'foreach' rather than 'await foreach'? // await foreach (var i in collection) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMemberWrongAsync, "collection").WithArguments("System.Collections.Generic.IEnumerable<int>", "GetAsyncEnumerator").WithLocation(7, 33) ); } [Fact] public void TestPatternBasedAsyncEnumerableWithRegularForeach() { string source = @" class C { void M() { foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,27): error CS8414: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator'. Did you mean 'await foreach'? // foreach (var i in new C()) Diagnostic(ErrorCode.ERR_ForEachMissingMemberWrongAsync, "new C()").WithArguments("C", "GetEnumerator").WithLocation(6, 27) ); } [Fact] public void TestPatternBased_GetEnumeratorWithoutCancellationToken() { string source = @" public class C { public static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() // no parameter => new Enumerator(); public sealed class Enumerator { public async System.Threading.Tasks.Task<bool> MoveNextAsync() { System.Console.Write(""MoveNextAsync""); await System.Threading.Tasks.Task.Yield(); return false; } public int Current => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync"); } [Fact] public void TestPatternBasedEnumerableWithAwaitForeach() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator<int> GetEnumerator() => throw null; public class Enumerator<T> { public T Current { get; } public bool MoveNext() => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,33): error CS8415: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetAsyncEnumerator'. Did you mean 'foreach' rather than 'await foreach'? // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMemberWrongAsync, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(6, 33) ); } [Fact] public void TestWithPattern() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() { throw null; } public int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("C.Enumerator C.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<System.Boolean> C.Enumerator.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 C.Enumerator.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Null(info.DisposeMethod); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); var memberModel = model.GetMemberModel(foreachSyntax); BoundForEachStatement boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.False(internalInfo.NeedsDisposal); } [Fact] public void TestWithPattern_Ref() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (ref var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,32): error CS8177: Async methods cannot have by-reference locals // await foreach (ref var i in new C()) Diagnostic(ErrorCode.ERR_BadAsyncLocalType, "i").WithLocation(6, 32)); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); Assert.Equal(default, model.GetForEachStatementInfo(foreachSyntax)); } [Fact] public void TestWithPattern_PointerType() { string source = @" unsafe class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int* Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (6,9): error CS4004: Cannot await in an unsafe context // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await").WithLocation(6, 9)); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); Assert.Equal(default, model.GetForEachStatementInfo(foreachSyntax)); } [Fact] public void TestWithPattern_InaccessibleGetAsyncEnumerator() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new D()) { } } } class D { private Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,33): error CS8411: Async foreach statement cannot operate on variables of type 'D' because 'D' does not contain a public definition for 'GetAsyncEnumerator' // await foreach (var i in new D()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new D()").WithArguments("D", "GetAsyncEnumerator").WithLocation(6, 33) ); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); Assert.Equal(default, model.GetForEachStatementInfo(foreachSyntax)); } [Fact] public void TestWithPattern_InaccessibleMoveNextAsync() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new D()) { } } } class D { public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { private System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,33): error CS0122: 'D.Enumerator.MoveNextAsync()' is inaccessible due to its protection level // await foreach (var i in new D()) Diagnostic(ErrorCode.ERR_BadAccess, "new D()").WithArguments("D.Enumerator.MoveNextAsync()").WithLocation(6, 33), // (6,33): error CS8412: Async foreach requires that the return type 'D.Enumerator' of 'D.GetAsyncEnumerator(System.Threading.CancellationToken)' must have a suitable public MoveNextAsync method and public Current property // await foreach (var i in new D()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new D()").WithArguments("D.Enumerator", "D.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33) ); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); Assert.Equal(default, model.GetForEachStatementInfo(foreachSyntax)); } [Fact] public void TestWithPattern_InaccessibleCurrent() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new D()) { } } } class D { public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; private int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,33): error CS0122: 'D.Enumerator.Current' is inaccessible due to its protection level // await foreach (var i in new D()) { } Diagnostic(ErrorCode.ERR_BadAccess, "new D()").WithArguments("D.Enumerator.Current").WithLocation(6, 33), // (6,33): error CS8412: Async foreach requires that the return type 'D.Enumerator' of 'D.GetAsyncEnumerator(System.Threading.CancellationToken)' must have a suitable public MoveNextAsync method and public Current property // await foreach (var i in new D()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new D()").WithArguments("D.Enumerator", "D.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33) ); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); Assert.Equal(default, model.GetForEachStatementInfo(foreachSyntax)); } [Fact] public void TestWithPattern_InaccessibleCurrentGetter() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new D()) { } } } class D { public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { private get => throw null; set => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,33): error CS8412: Async foreach requires that the return type 'D.Enumerator' of 'D.GetAsyncEnumerator()' must have a suitable public MoveNextAsync method and public Current property // await foreach (var i in new D()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new D()").WithArguments("D.Enumerator", "D.GetAsyncEnumerator()").WithLocation(6, 33) ); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); Assert.Equal(default, model.GetForEachStatementInfo(foreachSyntax)); } [Fact] public void TestWithPattern_RefStruct() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async System.Threading.Tasks.Task Main() { await foreach (var s in new C()) { Write($""{s.ToString()} ""); } Write(""Done""); } public Enumerator GetAsyncEnumerator() => new Enumerator(); public sealed class Enumerator : System.IAsyncDisposable { int i = 0; public int Current => i; public async Task<bool> MoveNextAsync() { i++; return await Task.FromResult(i < 3); } public async ValueTask DisposeAsync() { await Task.Yield(); } } } public ref struct S { int i; public S(int i) { this.i = i; } public override string ToString() => i.ToString(); } "; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2 Done"); } [Fact] public void TestWithPattern_RefReturningCurrent() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async System.Threading.Tasks.Task Main() { await foreach (var s in new C()) { Write($""{s.ToString()} ""); } Write(""Done""); } public Enumerator GetAsyncEnumerator() => new Enumerator(); public sealed class Enumerator { int i = 0; S current; public ref S Current { get { current = new S(i); return ref current; } } public async Task<bool> MoveNextAsync() { i++; return await Task.FromResult(i < 4); } } } public struct S { int i; public S(int i) { this.i = i; } public override string ToString() => i.ToString(); } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2 3 Done", verify: Verification.Fails); } [Fact] public void TestWithPattern_IterationVariableIsReadOnly() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { i = 1; } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics( // (8,13): error CS1656: Cannot assign to 'i' because it is a 'foreach iteration variable' // i = 1; Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "i").WithArguments("i", "foreach iteration variable").WithLocation(8, 13) ); } [Fact] public void TestWithPattern_WithStruct_MoveNextAsyncReturnsTask() { string source = @" using static System.Console; using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } Write($""Done""); } public AsyncEnumerator GetAsyncEnumerator() { return new AsyncEnumerator(0); } public struct AsyncEnumerator { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get { Write($""Current({i}) ""); i++; return i; } } public async Task<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); bool more = await Task.FromResult(i < 4); i = i + 100; // Note: side-effects of async methods in structs are lost return more; } public async ValueTask DisposeAsync() { Write($""DisposeAsync ""); await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(0) Got(1) NextAsync(1) Current(1) Got(2) NextAsync(2) Current(2) Got(3) NextAsync(3) Current(3) Got(4) NextAsync(4) DisposeAsync Done"); } [Fact] public void TestWithPattern_MoveNextAsyncReturnsValueTask() { string source = @" using static System.Console; using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } Write($""Done""); } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new AsyncEnumerator(0); } public class AsyncEnumerator : System.IAsyncDisposable { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public async ValueTask DisposeAsync() { Write($""Dispose({i}) ""); await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Current(3) Got(3) NextAsync(3) Dispose(4) Done"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("System.Threading.Tasks.ValueTask<System.Boolean> C.AsyncEnumerator.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); } [Fact] [WorkItem(31609, "https://github.com/dotnet/roslyn/issues/31609")] public void TestWithPattern_MoveNextAsyncReturnsAwaitable() { string source = @" using static System.Console; using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { Write($""Item({i}) ""); break; } Write($""Done""); } public AsyncEnumerator GetAsyncEnumerator() { return new AsyncEnumerator(); } public class AsyncEnumerator : System.IAsyncDisposable { public int Current => 1; public Awaitable MoveNextAsync() { return new Awaitable(); } public async ValueTask DisposeAsync() { Write(""Dispose ""); await Task.Yield(); } } public class Awaitable { public Awaiter GetAwaiter() { return new Awaiter(); } } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public bool IsCompleted { get { return true; } } public bool GetResult() { return true; } public void OnCompleted(System.Action continuation) { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Item(1) Dispose Done"); var tree = comp.SyntaxTrees.First(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("C.Awaitable C.AsyncEnumerator.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); } [Fact] [WorkItem(31609, "https://github.com/dotnet/roslyn/issues/31609")] public void TestWithPattern_MoveNextAsyncReturnsAwaitable_WithoutGetAwaiter() { string source = @" using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { } } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public class AsyncEnumerator : System.IAsyncDisposable { public int Current => 1; public Awaitable MoveNextAsync() => throw null; public ValueTask DisposeAsync() => throw null; } public class Awaitable { } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,33): error CS1061: 'C.Awaitable' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'C.Awaitable' could be found (are you missing a using directive or an assembly reference?) // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C()").WithArguments("C.Awaitable", "GetAwaiter").WithLocation(7, 33) ); VerifyEmptyForEachStatementInfo(comp); } [Fact] [WorkItem(31609, "https://github.com/dotnet/roslyn/issues/31609")] public void TestWithPattern_MoveNextAsyncReturnsAwaitable_WithoutIsCompleted() { string source = @" using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { } } public AsyncEnumerator GetAsyncEnumerator() => throw null; public class AsyncEnumerator : System.IAsyncDisposable { public int Current => 1; public Awaitable MoveNextAsync() => throw null; public ValueTask DisposeAsync() => throw null; } public class Awaitable { public Awaiter GetAwaiter() => throw null; } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public bool GetResult() { return true; } public void OnCompleted(System.Action continuation) { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,33): error CS0117: 'C.Awaiter' does not contain a definition for 'IsCompleted' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Awaiter", "IsCompleted").WithLocation(7, 33) ); VerifyEmptyForEachStatementInfo(comp); } private static void VerifyEmptyForEachStatementInfo(CSharpCompilation comp) { var tree = comp.SyntaxTrees.First(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Null(info.MoveNextMethod); Assert.Null(info.ElementType); } [Fact] [WorkItem(31609, "https://github.com/dotnet/roslyn/issues/31609")] public void TestWithPattern_MoveNextAsyncReturnsAwaitable_WithoutGetResult() { string source = @" using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { } } public AsyncEnumerator GetAsyncEnumerator() => throw null; public class AsyncEnumerator : System.IAsyncDisposable { public int Current => 1; public Awaitable MoveNextAsync() => throw null; public ValueTask DisposeAsync() => throw null; } public class Awaitable { public Awaiter GetAwaiter() => throw null; } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public bool IsCompleted { get { return true; } } public void OnCompleted(System.Action continuation) { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,33): error CS1061: 'C.Awaiter' does not contain a definition for 'GetResult' and no accessible extension method 'GetResult' accepting a first argument of type 'C.Awaiter' could be found (are you missing a using directive or an assembly reference?) // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C()").WithArguments("C.Awaiter", "GetResult").WithLocation(7, 33) ); VerifyEmptyForEachStatementInfo(comp); } [Fact] [WorkItem(31609, "https://github.com/dotnet/roslyn/issues/31609")] public void TestWithPattern_MoveNextAsyncReturnsAwaitable_WithoutOnCompleted() { string source = @" using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { } } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public class AsyncEnumerator : System.IAsyncDisposable { public int Current => 1; public Awaitable MoveNextAsync() => throw null; public ValueTask DisposeAsync() => throw null; } public class Awaitable { public Awaiter GetAwaiter() => throw null; } public class Awaiter { public bool IsCompleted { get { return true; } } public bool GetResult() { return true; } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,33): error CS4027: 'C.Awaiter' does not implement 'INotifyCompletion' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "new C()").WithArguments("C.Awaiter", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(7, 33) ); VerifyEmptyForEachStatementInfo(comp); } [Fact] public void TestWithPattern_MoveNextAsyncReturnsBadType() { string source = @" using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { } } public AsyncEnumerator GetAsyncEnumerator() => throw null; public class AsyncEnumerator { public int Current => throw null; public int MoveNextAsync() => throw null; public ValueTask DisposeAsync() => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics( // (7,33): error CS1061: 'int' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C()").WithArguments("int", "GetAwaiter").WithLocation(7, 33) ); var tree = comp.SyntaxTrees.First(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Null(info.MoveNextMethod); Assert.Null(info.ElementType); } [Fact] public void TestWithPattern_WithUnsealed() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } } public Enumerator GetAsyncEnumerator() { return new Enumerator(); } public class Enumerator { int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async Task<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var memberModel = model.GetMemberModel(foreachSyntax); BoundForEachStatement boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Current(3) Got(3) NextAsync(3) Dispose(4)"); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void TestWithPattern_WithUnsealed_WithIAsyncDisposable() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new DerivedEnumerator(); } public class Enumerator { protected int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async Task<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } } public class DerivedEnumerator : Enumerator, System.IAsyncDisposable { public ValueTask DisposeAsync() => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.False(internalInfo.NeedsDisposal); var verifier = CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Current(3) Got(3) NextAsync(3)"); verifier.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 262 (0x106) .maxstack 3 .locals init (int V_0, System.Threading.CancellationToken V_1, System.Runtime.CompilerServices.TaskAwaiter<bool> V_2, C.<Main>d__0 V_3, System.Exception V_4) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Main>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: <hidden> IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_0011 IL_000c: br IL_009a // sequence point: { IL_0011: nop // sequence point: await foreach IL_0012: nop // sequence point: new C() IL_0013: ldarg.0 IL_0014: newobj ""C..ctor()"" IL_0019: ldloca.s V_1 IL_001b: initobj ""System.Threading.CancellationToken"" IL_0021: ldloc.1 IL_0022: call ""C.Enumerator C.GetAsyncEnumerator(System.Threading.CancellationToken)"" IL_0027: stfld ""C.Enumerator C.<Main>d__0.<>s__1"" // sequence point: <hidden> IL_002c: br.s IL_005c // sequence point: var i IL_002e: ldarg.0 IL_002f: ldarg.0 IL_0030: ldfld ""C.Enumerator C.<Main>d__0.<>s__1"" IL_0035: callvirt ""int C.Enumerator.Current.get"" IL_003a: stfld ""int C.<Main>d__0.<i>5__2"" // sequence point: { IL_003f: nop // sequence point: Write($""Got({i}) ""); IL_0040: ldstr ""Got({0}) "" IL_0045: ldarg.0 IL_0046: ldfld ""int C.<Main>d__0.<i>5__2"" IL_004b: box ""int"" IL_0050: call ""string string.Format(string, object)"" IL_0055: call ""void System.Console.Write(string)"" IL_005a: nop // sequence point: } IL_005b: nop // sequence point: in IL_005c: ldarg.0 IL_005d: ldfld ""C.Enumerator C.<Main>d__0.<>s__1"" IL_0062: callvirt ""System.Threading.Tasks.Task<bool> C.Enumerator.MoveNextAsync()"" IL_0067: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<bool> System.Threading.Tasks.Task<bool>.GetAwaiter()"" IL_006c: stloc.2 // sequence point: <hidden> IL_006d: ldloca.s V_2 IL_006f: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.IsCompleted.get"" IL_0074: brtrue.s IL_00b6 IL_0076: ldarg.0 IL_0077: ldc.i4.0 IL_0078: dup IL_0079: stloc.0 IL_007a: stfld ""int C.<Main>d__0.<>1__state"" // async: yield IL_007f: ldarg.0 IL_0080: ldloc.2 IL_0081: stfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_0086: ldarg.0 IL_0087: stloc.3 IL_0088: ldarg.0 IL_0089: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_008e: ldloca.s V_2 IL_0090: ldloca.s V_3 IL_0092: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<bool>, C.<Main>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<bool>, ref C.<Main>d__0)"" IL_0097: nop IL_0098: leave.s IL_0105 // async: resume IL_009a: ldarg.0 IL_009b: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_00a0: stloc.2 IL_00a1: ldarg.0 IL_00a2: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_00a7: initobj ""System.Runtime.CompilerServices.TaskAwaiter<bool>"" IL_00ad: ldarg.0 IL_00ae: ldc.i4.m1 IL_00af: dup IL_00b0: stloc.0 IL_00b1: stfld ""int C.<Main>d__0.<>1__state"" IL_00b6: ldarg.0 IL_00b7: ldloca.s V_2 IL_00b9: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.GetResult()"" IL_00be: stfld ""bool C.<Main>d__0.<>s__3"" IL_00c3: ldarg.0 IL_00c4: ldfld ""bool C.<Main>d__0.<>s__3"" IL_00c9: brtrue IL_002e IL_00ce: ldarg.0 IL_00cf: ldnull IL_00d0: stfld ""C.Enumerator C.<Main>d__0.<>s__1"" IL_00d5: leave.s IL_00f1 } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_00d7: stloc.s V_4 IL_00d9: ldarg.0 IL_00da: ldc.i4.s -2 IL_00dc: stfld ""int C.<Main>d__0.<>1__state"" IL_00e1: ldarg.0 IL_00e2: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_00e7: ldloc.s V_4 IL_00e9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00ee: nop IL_00ef: leave.s IL_0105 } // sequence point: } IL_00f1: ldarg.0 IL_00f2: ldc.i4.s -2 IL_00f4: stfld ""int C.<Main>d__0.<>1__state"" // sequence point: <hidden> IL_00f9: ldarg.0 IL_00fa: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_00ff: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_0104: nop IL_0105: ret }", sequencePoints: "C+<Main>d__0.MoveNext", source: source + s_IAsyncEnumerable); } [Fact] public void TestWithPattern_WithIAsyncDisposable() { string source = @" using static System.Console; using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } } public Enumerator GetAsyncEnumerator() { return new Enumerator(); } public sealed class Enumerator : System.IAsyncDisposable { int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async Task<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var memberModel = model.GetMemberModel(foreachSyntax); BoundForEachStatement boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Current(3) Got(3) NextAsync(3) Dispose(4)"); } [Fact] public void TestWithPattern_WithIAsyncDisposableUseSiteError() { string enumerator = @" using System.Threading.Tasks; public class C { public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator : System.IAsyncDisposable { public int Current { get => throw null; } public Task<bool> MoveNextAsync() => throw null; public async ValueTask DisposeAsync() { await Task.Yield(); } } }"; string source = @" using System.Threading.Tasks; class Client { async Task M() { await foreach (var i in new C()) { } } }"; var lib = CreateCompilationWithTasksExtensions(enumerator + s_IAsyncEnumerable); lib.VerifyDiagnostics(); var comp = CreateCompilationWithTasksExtensions(source, references: new[] { lib.EmitToImageReference() }); comp.MakeTypeMissing(WellKnownType.System_IAsyncDisposable); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); } [Fact] public void TestWithMultipleInterface() { string source = @" using System.Collections.Generic; class C : IAsyncEnumerable<int>, IAsyncEnumerable<string> { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { throw null; } IAsyncEnumerator<string> IAsyncEnumerable<string>.GetAsyncEnumerator(System.Threading.CancellationToken token) { throw null; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (7,33): error CS8413: Async foreach statement cannot operate on variables of type 'C' because it implements multiple instantiations of 'IAsyncEnumerable<T>'; try casting to a specific interface instantiation // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_MultipleIAsyncEnumOfT, "new C()").WithArguments("C", "System.Collections.Generic.IAsyncEnumerable<T>").WithLocation(7, 33) ); } [Fact] public void TestWithMultipleImplementations() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class Base : IAsyncEnumerable<string> { IAsyncEnumerator<string> IAsyncEnumerable<string>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; } class C : Base, IAsyncEnumerable<int> { async Task M() { await foreach (var i in new C()) { } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (13,33): error CS8413: Async foreach statement cannot operate on variables of type 'C' because it implements multiple instantiations of 'IAsyncEnumerable<T>'; try casting to a specific interface instantiation // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_MultipleIAsyncEnumOfT, "new C()").WithArguments("C", "System.Collections.Generic.IAsyncEnumerable<T>").WithLocation(13, 33) ); } [Fact] public void TestWithInterface() { string source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; using static System.Console; class C : IAsyncEnumerable<int> { static async Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } sealed class AsyncEnumerator : IAsyncEnumerator<int> { int i = 0; int IAsyncEnumerator<int>.Current { get { Write($""Current({i}) ""); return i; } } async ValueTask<bool> IAsyncEnumerator<int>.MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } async ValueTask IAsyncDisposable.DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Current(3) Got(3) NextAsync(3) Dispose(4)"); var tree = comp.SyntaxTrees.First(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("System.Collections.Generic.IAsyncEnumerator<System.Int32> System.Collections.Generic.IAsyncEnumerable<System.Int32>.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask<System.Boolean> System.Collections.Generic.IAsyncEnumerator<System.Int32>.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 System.Collections.Generic.IAsyncEnumerator<System.Int32>.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()", info.DisposeMethod.ToTestDisplayString()); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); } [Fact] public void TestWithInterface_OnStruct_ImplicitInterfaceImplementation() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; struct C : IAsyncEnumerable<int> { static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } class AsyncEnumerator : IAsyncEnumerator<int> { public int i; public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; // Note: the enumerator type should not be a struct, otherwise you will loop forever var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Current(3) Got(3) NextAsync(3) Dispose(4)"); // The thing to notice here is that the call to GetAsyncEnumerator is a constrained call (we're not boxing to `IAsyncEnumerable<int>`) verifier.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 496 (0x1f0) .maxstack 3 .locals init (int V_0, C V_1, System.Threading.CancellationToken V_2, System.Runtime.CompilerServices.ValueTaskAwaiter<bool> V_3, System.Threading.Tasks.ValueTask<bool> V_4, C.<Main>d__0 V_5, object V_6, System.Runtime.CompilerServices.ValueTaskAwaiter V_7, System.Threading.Tasks.ValueTask V_8, System.Exception V_9) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Main>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0019 IL_0012: br.s IL_004c IL_0014: br IL_015c IL_0019: nop IL_001a: nop IL_001b: ldarg.0 IL_001c: ldloca.s V_1 IL_001e: dup IL_001f: initobj ""C"" IL_0025: ldloca.s V_2 IL_0027: initobj ""System.Threading.CancellationToken"" IL_002d: ldloc.2 IL_002e: constrained. ""C"" IL_0034: callvirt ""System.Collections.Generic.IAsyncEnumerator<int> System.Collections.Generic.IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken)"" IL_0039: stfld ""System.Collections.Generic.IAsyncEnumerator<int> C.<Main>d__0.<>s__1"" IL_003e: ldarg.0 IL_003f: ldnull IL_0040: stfld ""object C.<Main>d__0.<>s__2"" IL_0045: ldarg.0 IL_0046: ldc.i4.0 IL_0047: stfld ""int C.<Main>d__0.<>s__3"" IL_004c: nop .try { IL_004d: ldloc.0 IL_004e: brfalse.s IL_0052 IL_0050: br.s IL_0054 IL_0052: br.s IL_00ca IL_0054: br.s IL_0084 IL_0056: ldarg.0 IL_0057: ldarg.0 IL_0058: ldfld ""System.Collections.Generic.IAsyncEnumerator<int> C.<Main>d__0.<>s__1"" IL_005d: callvirt ""int System.Collections.Generic.IAsyncEnumerator<int>.Current.get"" IL_0062: stfld ""int C.<Main>d__0.<i>5__4"" IL_0067: nop IL_0068: ldstr ""Got({0}) "" IL_006d: ldarg.0 IL_006e: ldfld ""int C.<Main>d__0.<i>5__4"" IL_0073: box ""int"" IL_0078: call ""string string.Format(string, object)"" IL_007d: call ""void System.Console.Write(string)"" IL_0082: nop IL_0083: nop IL_0084: ldarg.0 IL_0085: ldfld ""System.Collections.Generic.IAsyncEnumerator<int> C.<Main>d__0.<>s__1"" IL_008a: callvirt ""System.Threading.Tasks.ValueTask<bool> System.Collections.Generic.IAsyncEnumerator<int>.MoveNextAsync()"" IL_008f: stloc.s V_4 IL_0091: ldloca.s V_4 IL_0093: call ""System.Runtime.CompilerServices.ValueTaskAwaiter<bool> System.Threading.Tasks.ValueTask<bool>.GetAwaiter()"" IL_0098: stloc.3 IL_0099: ldloca.s V_3 IL_009b: call ""bool System.Runtime.CompilerServices.ValueTaskAwaiter<bool>.IsCompleted.get"" IL_00a0: brtrue.s IL_00e6 IL_00a2: ldarg.0 IL_00a3: ldc.i4.0 IL_00a4: dup IL_00a5: stloc.0 IL_00a6: stfld ""int C.<Main>d__0.<>1__state"" IL_00ab: ldarg.0 IL_00ac: ldloc.3 IL_00ad: stfld ""System.Runtime.CompilerServices.ValueTaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_00b2: ldarg.0 IL_00b3: stloc.s V_5 IL_00b5: ldarg.0 IL_00b6: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_00bb: ldloca.s V_3 IL_00bd: ldloca.s V_5 IL_00bf: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ValueTaskAwaiter<bool>, C.<Main>d__0>(ref System.Runtime.CompilerServices.ValueTaskAwaiter<bool>, ref C.<Main>d__0)"" IL_00c4: nop IL_00c5: leave IL_01ef IL_00ca: ldarg.0 IL_00cb: ldfld ""System.Runtime.CompilerServices.ValueTaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_00d0: stloc.3 IL_00d1: ldarg.0 IL_00d2: ldflda ""System.Runtime.CompilerServices.ValueTaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_00d7: initobj ""System.Runtime.CompilerServices.ValueTaskAwaiter<bool>"" IL_00dd: ldarg.0 IL_00de: ldc.i4.m1 IL_00df: dup IL_00e0: stloc.0 IL_00e1: stfld ""int C.<Main>d__0.<>1__state"" IL_00e6: ldarg.0 IL_00e7: ldloca.s V_3 IL_00e9: call ""bool System.Runtime.CompilerServices.ValueTaskAwaiter<bool>.GetResult()"" IL_00ee: stfld ""bool C.<Main>d__0.<>s__5"" IL_00f3: ldarg.0 IL_00f4: ldfld ""bool C.<Main>d__0.<>s__5"" IL_00f9: brtrue IL_0056 IL_00fe: leave.s IL_010c } catch object { IL_0100: stloc.s V_6 IL_0102: ldarg.0 IL_0103: ldloc.s V_6 IL_0105: stfld ""object C.<Main>d__0.<>s__2"" IL_010a: leave.s IL_010c } IL_010c: ldarg.0 IL_010d: ldfld ""System.Collections.Generic.IAsyncEnumerator<int> C.<Main>d__0.<>s__1"" IL_0112: brfalse.s IL_0181 IL_0114: ldarg.0 IL_0115: ldfld ""System.Collections.Generic.IAsyncEnumerator<int> C.<Main>d__0.<>s__1"" IL_011a: callvirt ""System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()"" IL_011f: stloc.s V_8 IL_0121: ldloca.s V_8 IL_0123: call ""System.Runtime.CompilerServices.ValueTaskAwaiter System.Threading.Tasks.ValueTask.GetAwaiter()"" IL_0128: stloc.s V_7 IL_012a: ldloca.s V_7 IL_012c: call ""bool System.Runtime.CompilerServices.ValueTaskAwaiter.IsCompleted.get"" IL_0131: brtrue.s IL_0179 IL_0133: ldarg.0 IL_0134: ldc.i4.1 IL_0135: dup IL_0136: stloc.0 IL_0137: stfld ""int C.<Main>d__0.<>1__state"" IL_013c: ldarg.0 IL_013d: ldloc.s V_7 IL_013f: stfld ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__2"" IL_0144: ldarg.0 IL_0145: stloc.s V_5 IL_0147: ldarg.0 IL_0148: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_014d: ldloca.s V_7 IL_014f: ldloca.s V_5 IL_0151: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ValueTaskAwaiter, C.<Main>d__0>(ref System.Runtime.CompilerServices.ValueTaskAwaiter, ref C.<Main>d__0)"" IL_0156: nop IL_0157: leave IL_01ef IL_015c: ldarg.0 IL_015d: ldfld ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__2"" IL_0162: stloc.s V_7 IL_0164: ldarg.0 IL_0165: ldflda ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__2"" IL_016a: initobj ""System.Runtime.CompilerServices.ValueTaskAwaiter"" IL_0170: ldarg.0 IL_0171: ldc.i4.m1 IL_0172: dup IL_0173: stloc.0 IL_0174: stfld ""int C.<Main>d__0.<>1__state"" IL_0179: ldloca.s V_7 IL_017b: call ""void System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()"" IL_0180: nop IL_0181: ldarg.0 IL_0182: ldfld ""object C.<Main>d__0.<>s__2"" IL_0187: stloc.s V_6 IL_0189: ldloc.s V_6 IL_018b: brfalse.s IL_01aa IL_018d: ldloc.s V_6 IL_018f: isinst ""System.Exception"" IL_0194: stloc.s V_9 IL_0196: ldloc.s V_9 IL_0198: brtrue.s IL_019d IL_019a: ldloc.s V_6 IL_019c: throw IL_019d: ldloc.s V_9 IL_019f: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)"" IL_01a4: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()"" IL_01a9: nop IL_01aa: ldarg.0 IL_01ab: ldfld ""int C.<Main>d__0.<>s__3"" IL_01b0: pop IL_01b1: ldarg.0 IL_01b2: ldnull IL_01b3: stfld ""object C.<Main>d__0.<>s__2"" IL_01b8: ldarg.0 IL_01b9: ldnull IL_01ba: stfld ""System.Collections.Generic.IAsyncEnumerator<int> C.<Main>d__0.<>s__1"" IL_01bf: leave.s IL_01db } catch System.Exception { IL_01c1: stloc.s V_9 IL_01c3: ldarg.0 IL_01c4: ldc.i4.s -2 IL_01c6: stfld ""int C.<Main>d__0.<>1__state"" IL_01cb: ldarg.0 IL_01cc: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_01d1: ldloc.s V_9 IL_01d3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_01d8: nop IL_01d9: leave.s IL_01ef } IL_01db: ldarg.0 IL_01dc: ldc.i4.s -2 IL_01de: stfld ""int C.<Main>d__0.<>1__state"" IL_01e3: ldarg.0 IL_01e4: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_01e9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_01ee: nop IL_01ef: ret }"); } [Fact] public void TestWithInterface_WithEarlyCompletion1() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } Write($""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(2); } internal sealed class AsyncEnumerator : IAsyncEnumerator<int> { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public ValueTask DisposeAsync() { Write($""Dispose({i}) ""); return new ValueTask(Task.CompletedTask); // return a completed task } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(2) Current(3) Got(3) NextAsync(3) Dispose(4) Done"); } [Fact] public void TestWithInterface_WithBreakAndContinue() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { if (i == 2 || i == 3) { Write($""Continue({i}) ""); continue; } if (i == 4) { Write(""Break ""); break; } Write($""Got({i}) ""); } Write(""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } sealed class AsyncEnumerator : IAsyncEnumerator<int> { int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 10); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Continue(2) NextAsync(2) Current(3) Continue(3) NextAsync(3) Current(4) Break Dispose(4) Done"); } [Fact] public void TestWithInterface_WithGoto() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { if (i == 2 || i == 3) { Write($""Continue({i}) ""); continue; } if (i == 4) { Write(""Goto ""); goto done; } Write($""Got({i}) ""); } done: Write(""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } sealed class AsyncEnumerator : IAsyncEnumerator<int> { int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 10); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Continue(2) NextAsync(2) Current(3) Continue(3) NextAsync(3) Current(4) Goto Dispose(4) Done"); } [Fact] public void TestWithInterface_WithStruct() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { static async Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } Write($""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(0); } internal struct AsyncEnumerator : IAsyncEnumerator<int> { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get { Write($""Current({i}) ""); i++; return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); bool more = await Task.FromResult(i < 4); i = i + 100; // Note: side-effects of async methods in structs are lost return more; } public async ValueTask DisposeAsync() { Write($""Dispose({i}) ""); await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(0) Got(1) NextAsync(1) Current(1) Got(2) NextAsync(2) Current(2) Got(3) NextAsync(3) Current(3) Got(4) NextAsync(4) Dispose(4) Done"); } [Fact, WorkItem(27651, "https://github.com/dotnet/roslyn/issues/27651")] public void TestControlFlowAnalysis() { string source = @" class C { async System.Threading.Tasks.Task M(System.Collections.Generic.IAsyncEnumerable<int> collection) { await foreach (var item in collection) { } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var loop = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var ctrlFlowAnalysis = model.AnalyzeControlFlow(loop); Assert.Equal(0, ctrlFlowAnalysis.ExitPoints.Count()); } [Fact] public void TestWithNullLiteralCollection() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { async Task M() { await foreach (var i in null) { } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { throw null; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (8,33): error CS0186: Use of null is not valid in this context // await foreach (var i in null) Diagnostic(ErrorCode.ERR_NullNotValid, "null").WithLocation(8, 33) ); } [Fact] public void TestWithNullCollection() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task Main() { C c = null; try { await foreach (var i in c) { } } catch (System.NullReferenceException) { System.Console.Write(""Success""); } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(0); } internal struct AsyncEnumerator : IAsyncEnumerator<int> { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get => throw new System.Exception(); } public ValueTask<bool> MoveNextAsync() => throw new System.Exception(); public ValueTask DisposeAsync() => throw new System.Exception(); } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Success"); } [Fact] public void TestInCatch() { string source = @" using System.Collections.Generic; using static System.Console; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task Main() { try { Write($""Try ""); throw null; } catch (System.NullReferenceException) { await foreach (var i in new C()) { Write($""Got({i}) ""); } } Write($""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(0); } internal class AsyncEnumerator : IAsyncEnumerator<int> { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Try NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Current(3) Got(3) NextAsync(3) Dispose(4) Done"); } /// Covered in greater details by <see cref="CodeGenAsyncIteratorTests.TryFinally_AwaitForeachInFinally"/> [Fact] public void TestInFinally() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task Main() { try { } finally { await foreach (var i in new C()) { } } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { throw null; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics(); } [Fact] public void TestWithConversionToElement() { string source = @" using System.Collections.Generic; using static System.Console; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task Main() { await foreach (Element i in new C()) { Write($""Got({i}) ""); } Write($""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(0); } internal class AsyncEnumerator : IAsyncEnumerator<int> { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 3); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } } class Element { int i; public static implicit operator Element(int value) { Write($""Convert({value}) ""); return new Element(value); } private Element(int value) { i = value; } public override string ToString() => i.ToString(); }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Convert(1) Got(1) NextAsync(1) Current(2) Convert(2) Got(2) NextAsync(2) Dispose(3) Done"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("System.Collections.Generic.IAsyncEnumerator<System.Int32> System.Collections.Generic.IAsyncEnumerable<System.Int32>.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask<System.Boolean> System.Collections.Generic.IAsyncEnumerator<System.Int32>.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 System.Collections.Generic.IAsyncEnumerator<System.Int32>.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()", info.DisposeMethod.ToTestDisplayString()); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitUserDefined, info.ElementConversion.Kind); Assert.Equal("Element Element.op_Implicit(System.Int32 value)", info.ElementConversion.MethodSymbol.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); } [Fact] public void TestWithNullableCollection() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; struct C : IAsyncEnumerable<int> { static async System.Threading.Tasks.Task Main() { C? c = new C(); // non-null value await foreach (var i in c) { Write($""Got({i}) ""); } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } sealed class AsyncEnumerator : IAsyncEnumerator<int> { int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 3); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Dispose(3)"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("System.Collections.Generic.IAsyncEnumerator<System.Int32> System.Collections.Generic.IAsyncEnumerable<System.Int32>.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask<System.Boolean> System.Collections.Generic.IAsyncEnumerator<System.Int32>.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 System.Collections.Generic.IAsyncEnumerator<System.Int32>.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()", info.DisposeMethod.ToTestDisplayString()); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); } [Fact] public void TestWithNullableCollection2() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; struct C : IAsyncEnumerable<int> { static async Task Main() { C? c = null; // null value try { await foreach (var i in c) { Write($""UNREACHABLE""); } } catch (System.InvalidOperationException) { Write($""Success""); } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { throw new System.Exception(); } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Success"); } [Fact] public void TestWithInterfaceAndDeconstruction() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { static async System.Threading.Tasks.Task Main() { await foreach (var (i, j) in new C()) { Write($""Got({i},{j}) ""); } Write($""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } sealed class AsyncEnumerator : IAsyncEnumerator<int> { int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 3); } public async ValueTask DisposeAsync() { Write($""Dispose({i}) ""); await Task.Yield(); } } } public static class Extensions { public static void Deconstruct(this int i, out string x1, out int x2) { Write($""Deconstruct({i}) ""); x1 = i.ToString(); x2 = -i; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Deconstruct(1) Got(1,-1) NextAsync(1) Current(2) Deconstruct(2) Got(2,-2) NextAsync(2) Dispose(3) Done"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("System.Collections.Generic.IAsyncEnumerator<System.Int32> System.Collections.Generic.IAsyncEnumerable<System.Int32>.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask<System.Boolean> System.Collections.Generic.IAsyncEnumerator<System.Int32>.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 System.Collections.Generic.IAsyncEnumerator<System.Int32>.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()", info.DisposeMethod.ToTestDisplayString()); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); } [Fact] public void TestWithDeconstructionInNonAsyncMethod() { string source = @" using System.Collections.Generic; class C : IAsyncEnumerable<int> { static void Main() { await foreach (var (i, j) in new C()) { } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; } public static class Extensions { public static void Deconstruct(this int i, out int x1, out int x2) { x1 = i; x2 = -i; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (7,9): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // await foreach (var (i, j) in new C()) Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(7, 9) ); } [Fact] public void TestWithPatternAndDeconstructionOfTuple() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<(string, int)> { public static async System.Threading.Tasks.Task Main() { await foreach (var (i, j) in new C()) { Write($""Got({i},{j}) ""); } Write($""Done""); } IAsyncEnumerator<(string, int)> IAsyncEnumerable<(string, int)>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } sealed class AsyncEnumerator : IAsyncEnumerator<(string, int)> { int i = 0; public (string, int) Current { get { Write($""Current({i}) ""); return (i.ToString(), -i); } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 3); } public async ValueTask DisposeAsync() { Write($""Dispose({i}) ""); await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1,-1) NextAsync(1) Current(2) Got(2,-2) NextAsync(2) Dispose(3) Done"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("System.Collections.Generic.IAsyncEnumerator<(System.String, System.Int32)> System.Collections.Generic.IAsyncEnumerable<(System.String, System.Int32)>.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask<System.Boolean> System.Collections.Generic.IAsyncEnumerator<(System.String, System.Int32)>.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("(System.String, System.Int32) System.Collections.Generic.IAsyncEnumerator<(System.String, System.Int32)>.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()", info.DisposeMethod.ToTestDisplayString()); Assert.Equal("(System.String, System.Int32)", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); } [Fact] public void TestWithInterfaceAndDeconstruction_ManualIteration() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { static async Task Main() { var e = ((IAsyncEnumerable<int>)new C()).GetAsyncEnumerator(); try { while (await e.MoveNextAsync()) { (int i, int j) = e.Current; Write($""Got({i},{j}) ""); } } finally { await e.DisposeAsync(); } Write($""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(0); } internal class AsyncEnumerator : IAsyncEnumerator<int> { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 3); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } } public static class Extensions { public static void Deconstruct(this int i, out int x1, out int x2) { x1 = i; x2 = -i; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1,-1) NextAsync(1) Current(2) Got(2,-2) NextAsync(2) Dispose(3) Done"); } [Fact] public void TestWithPatternAndObsolete() { string source = @" using System.Threading.Tasks; class C { static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { } } [System.Obsolete] public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } [System.Obsolete] public sealed class AsyncEnumerator : System.IAsyncDisposable { [System.Obsolete] public int Current { get => throw null; } [System.Obsolete] public Task<bool> MoveNextAsync() => throw null; [System.Obsolete] public ValueTask DisposeAsync() => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,15): warning CS0612: 'C.GetAsyncEnumerator(CancellationToken)' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(7, 15), // (7,15): warning CS0612: 'C.AsyncEnumerator.MoveNextAsync()' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.AsyncEnumerator.MoveNextAsync()").WithLocation(7, 15), // (7,15): warning CS0612: 'C.AsyncEnumerator.Current' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.AsyncEnumerator.Current").WithLocation(7, 15) ); // Note: Obsolete on DisposeAsync is not reported since always called through IAsyncDisposable interface } [Fact] public void TestWithUnassignedCollection() { string source = @" using System.Collections.Generic; class C { async System.Threading.Tasks.Task M() { C c; await foreach (var i in c) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (8,33): error CS0165: Use of unassigned local variable 'c' // await foreach (var i in c) Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c").WithLocation(8, 33) ); } [Fact] public void TestInRegularForeach() { string source = @" using System.Collections.Generic; class C { void M() { foreach (var i in new C()) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (7,27): error CS8414: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator'. Did you mean 'await foreach'? // foreach (var i in new C()) Diagnostic(ErrorCode.ERR_ForEachMissingMemberWrongAsync, "new C()").WithArguments("C", "GetEnumerator").WithLocation(7, 27) ); } [Fact] public void TestWithGenericCollection() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class Collection<T> : IAsyncEnumerable<T> { IAsyncEnumerator<T> IAsyncEnumerable<T>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } sealed class AsyncEnumerator : IAsyncEnumerator<T> { int i = 0; public T Current { get { Write($""Current({i}) ""); return default; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public async ValueTask DisposeAsync() { Write($""Dispose({i}) ""); await Task.Yield(); } } } class C { static async System.Threading.Tasks.Task Main() { await foreach (var i in new Collection<int>()) { Write($""Got ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got NextAsync(1) Current(2) Got NextAsync(2) Current(3) Got NextAsync(3) Dispose(4)"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("System.Collections.Generic.IAsyncEnumerator<System.Int32> System.Collections.Generic.IAsyncEnumerable<System.Int32>.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask<System.Boolean> System.Collections.Generic.IAsyncEnumerator<System.Int32>.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 System.Collections.Generic.IAsyncEnumerator<System.Int32>.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()", info.DisposeMethod.ToTestDisplayString()); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void TestWithInterfaceImplementingPattern() { string source = @" using static System.Console; using System.Threading.Tasks; public interface ICollection<T> { IMyAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default); } public interface IMyAsyncEnumerator<T> { T Current { get; } Task<bool> MoveNextAsync(); } public class Collection<T> : ICollection<T> { public IMyAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new MyAsyncEnumerator<T>(); } } public sealed class MyAsyncEnumerator<T> : IMyAsyncEnumerator<T> { int i = 0; public T Current { get { Write($""Current({i}) ""); return default; } } public async Task<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } } class C { static async System.Threading.Tasks.Task Main() { ICollection<int> c = new Collection<int>(); await foreach (var i in c) { Write($""Got ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got NextAsync(1) Current(2) Got NextAsync(2) Current(3) Got NextAsync(3)"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("IMyAsyncEnumerator<System.Int32> ICollection<System.Int32>.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<System.Boolean> IMyAsyncEnumerator<System.Int32>.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 IMyAsyncEnumerator<System.Int32>.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Null(info.DisposeMethod); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.False(internalInfo.NeedsDisposal); verifier.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 272 (0x110) .maxstack 3 .locals init (int V_0, System.Threading.CancellationToken V_1, System.Runtime.CompilerServices.TaskAwaiter<bool> V_2, C.<Main>d__0 V_3, System.Exception V_4) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Main>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: <hidden> IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_0011 IL_000c: br IL_0096 // sequence point: { IL_0011: nop // sequence point: ICollection<int> c = new Collection<int>(); IL_0012: ldarg.0 IL_0013: newobj ""Collection<int>..ctor()"" IL_0018: stfld ""ICollection<int> C.<Main>d__0.<c>5__1"" // sequence point: await foreach IL_001d: nop // sequence point: c IL_001e: ldarg.0 IL_001f: ldarg.0 IL_0020: ldfld ""ICollection<int> C.<Main>d__0.<c>5__1"" IL_0025: ldloca.s V_1 IL_0027: initobj ""System.Threading.CancellationToken"" IL_002d: ldloc.1 IL_002e: callvirt ""IMyAsyncEnumerator<int> ICollection<int>.GetAsyncEnumerator(System.Threading.CancellationToken)"" IL_0033: stfld ""IMyAsyncEnumerator<int> C.<Main>d__0.<>s__2"" // sequence point: <hidden> IL_0038: br.s IL_0058 // sequence point: var i IL_003a: ldarg.0 IL_003b: ldarg.0 IL_003c: ldfld ""IMyAsyncEnumerator<int> C.<Main>d__0.<>s__2"" IL_0041: callvirt ""int IMyAsyncEnumerator<int>.Current.get"" IL_0046: stfld ""int C.<Main>d__0.<i>5__3"" // sequence point: { IL_004b: nop // sequence point: Write($""Got ""); IL_004c: ldstr ""Got "" IL_0051: call ""void System.Console.Write(string)"" IL_0056: nop // sequence point: } IL_0057: nop // sequence point: in IL_0058: ldarg.0 IL_0059: ldfld ""IMyAsyncEnumerator<int> C.<Main>d__0.<>s__2"" IL_005e: callvirt ""System.Threading.Tasks.Task<bool> IMyAsyncEnumerator<int>.MoveNextAsync()"" IL_0063: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<bool> System.Threading.Tasks.Task<bool>.GetAwaiter()"" IL_0068: stloc.2 // sequence point: <hidden> IL_0069: ldloca.s V_2 IL_006b: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.IsCompleted.get"" IL_0070: brtrue.s IL_00b2 IL_0072: ldarg.0 IL_0073: ldc.i4.0 IL_0074: dup IL_0075: stloc.0 IL_0076: stfld ""int C.<Main>d__0.<>1__state"" // async: yield IL_007b: ldarg.0 IL_007c: ldloc.2 IL_007d: stfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_0082: ldarg.0 IL_0083: stloc.3 IL_0084: ldarg.0 IL_0085: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_008a: ldloca.s V_2 IL_008c: ldloca.s V_3 IL_008e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<bool>, C.<Main>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<bool>, ref C.<Main>d__0)"" IL_0093: nop IL_0094: leave.s IL_010f // async: resume IL_0096: ldarg.0 IL_0097: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_009c: stloc.2 IL_009d: ldarg.0 IL_009e: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_00a3: initobj ""System.Runtime.CompilerServices.TaskAwaiter<bool>"" IL_00a9: ldarg.0 IL_00aa: ldc.i4.m1 IL_00ab: dup IL_00ac: stloc.0 IL_00ad: stfld ""int C.<Main>d__0.<>1__state"" IL_00b2: ldarg.0 IL_00b3: ldloca.s V_2 IL_00b5: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.GetResult()"" IL_00ba: stfld ""bool C.<Main>d__0.<>s__4"" IL_00bf: ldarg.0 IL_00c0: ldfld ""bool C.<Main>d__0.<>s__4"" IL_00c5: brtrue IL_003a IL_00ca: ldarg.0 IL_00cb: ldnull IL_00cc: stfld ""IMyAsyncEnumerator<int> C.<Main>d__0.<>s__2"" IL_00d1: leave.s IL_00f4 } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_00d3: stloc.s V_4 IL_00d5: ldarg.0 IL_00d6: ldc.i4.s -2 IL_00d8: stfld ""int C.<Main>d__0.<>1__state"" IL_00dd: ldarg.0 IL_00de: ldnull IL_00df: stfld ""ICollection<int> C.<Main>d__0.<c>5__1"" IL_00e4: ldarg.0 IL_00e5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_00ea: ldloc.s V_4 IL_00ec: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00f1: nop IL_00f2: leave.s IL_010f } // sequence point: } IL_00f4: ldarg.0 IL_00f5: ldc.i4.s -2 IL_00f7: stfld ""int C.<Main>d__0.<>1__state"" // sequence point: <hidden> IL_00fc: ldarg.0 IL_00fd: ldnull IL_00fe: stfld ""ICollection<int> C.<Main>d__0.<c>5__1"" IL_0103: ldarg.0 IL_0104: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_0109: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_010e: nop IL_010f: ret }", sequencePoints: "C+<Main>d__0.MoveNext", source: source); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void TestWithInterfaceImplementingPattern_ChildImplementsDisposeAsync() { string source = @" using static System.Console; using System.Threading.Tasks; public interface ICollection<T> { IMyAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default); } public interface IMyAsyncEnumerator<T> { T Current { get; } Task<bool> MoveNextAsync(); } public class Collection<T> : ICollection<T> { public IMyAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new MyAsyncEnumerator<T>(); } } public sealed class MyAsyncEnumerator<T> : IMyAsyncEnumerator<T> { int i = 0; public T Current { get { Write($""Current({i}) ""); return default; } } public async Task<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public System.Threading.Tasks.ValueTask DisposeAsync() => throw null; } class C { static async System.Threading.Tasks.Task Main() { ICollection<int> c = new Collection<int>(); await foreach (var i in c) { Write($""Got ""); } } }"; // DisposeAsync on implementing type is ignored, since we don't do runtime check var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got NextAsync(1) Current(2) Got NextAsync(2) Current(3) Got NextAsync(3)"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Null(info.DisposeMethod); } [Fact] public void GetAsyncEnumerator_CancellationTokenMustBeOptional() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token) { throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] [WorkItem(50182, "https://github.com/dotnet/roslyn/issues/50182")] public void GetAsyncEnumerator_CancellationTokenMustBeOptional_OnIAsyncEnumerable() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C { public static async Task M(IAsyncEnumerable<int> e) { await foreach (var i in e) { } } } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token); } public interface IAsyncEnumerator<out T> : System.IAsyncDisposable { System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); T Current { get; } } } namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } "; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyEmitDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'IAsyncEnumerable<int>' because 'IAsyncEnumerable<int>' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in e) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "e").WithArguments("System.Collections.Generic.IAsyncEnumerable<int>", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] [WorkItem(50182, "https://github.com/dotnet/roslyn/issues/50182")] public void GetAsyncEnumerator_CancellationTokenMustBeOptional_OnIAsyncEnumerable_ImplicitImplementation() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task M(C c) { await foreach (var i in c) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token); } public interface IAsyncEnumerator<out T> : System.IAsyncDisposable { System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); T Current { get; } } } namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } "; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyEmitDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in c) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "c").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] [WorkItem(50182, "https://github.com/dotnet/roslyn/issues/50182")] public void GetAsyncEnumerator_CancellationTokenMustBeOptional_OnIAsyncEnumerable_ExplicitImplementation() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task M(C c) { await foreach (var i in c) { } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token); } public interface IAsyncEnumerator<out T> : System.IAsyncDisposable { System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); T Current { get; } } } namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } "; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyEmitDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in c) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "c").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void GetAsyncEnumerator_Missing() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task M(C c) { await foreach (var i in c) { } } } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { } public interface IAsyncEnumerator<out T> : System.IAsyncDisposable { System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); T Current { get; } } } namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } "; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyEmitDiagnostics( // (8,33): error CS0656: Missing compiler required member 'System.Collections.Generic.IAsyncEnumerable`1.GetAsyncEnumerator' // await foreach (var i in c) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "c").WithArguments("System.Collections.Generic.IAsyncEnumerable`1", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void GetAsyncEnumerator_WithOptionalParameter() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(int opt = 0) { throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics(); } [Fact] public void GetAsyncEnumerator_WithParams() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(params int[] x) { 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; } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync"); } [Fact] public void GetAsyncEnumerator_WithMultipleValidCandidatesWithOptionalParameters() { string source = @" using System.Threading.Tasks; using System.Collections.Generic; class C { public static async Task Main() { await foreach (var i in new C()) { } } public IEnumerator<int> GetAsyncEnumerator(int a = 0) => throw null; public IEnumerator<int> GetAsyncEnumerator(bool a = true) => throw null; }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (8,33): warning CS0278: 'C' does not implement the 'collection' pattern. 'C.GetAsyncEnumerator(int)' is ambiguous with 'C.GetAsyncEnumerator(bool)'. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "new C()").WithArguments("C", "collection", "C.GetAsyncEnumerator(int)", "C.GetAsyncEnumerator(bool)").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void GetAsyncEnumerator_WithMultipleInvalidCandidates() { string source = @" using System.Threading.Tasks; using System.Collections.Generic; class C { public static async Task Main() { await foreach (var i in new C()) { } } public IEnumerator<int> GetAsyncEnumerator(int a) => throw null; public IEnumerator<int> GetAsyncEnumerator(bool a) => throw null; }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_TwoOverloads() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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(int i = 0) { System.Console.Write(""DisposeAsync ""); await Task.Yield(); } public Task DisposeAsync(params string[] s) => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_NoExtensions() { string source = @" using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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 static class Extension { public static ValueTask DisposeAsync(this C.Enumerator e) => throw null; }"; // extension methods do not contribute to pattern-based disposal var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync Done"); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_NoExtensions_TwoExtensions() { string source = @" using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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 static class Extension1 { public static ValueTask DisposeAsync(this C.Enumerator c) => throw null; } public static class Extension2 { public static ValueTask DisposeAsync(this C.Enumerator c) => throw null; } "; // extension methods do not contribute to pattern-based disposal var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync Done"); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_InterfacePreferredToInstanceMethod() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } public Enumerator GetAsyncEnumerator() { return new Enumerator(); } public sealed class Enumerator : System.IAsyncDisposable { public async Task<bool> MoveNextAsync() { System.Console.Write(""MoveNextAsync ""); await Task.Yield(); return false; } public int Current { get => throw null; } async ValueTask System.IAsyncDisposable.DisposeAsync() { System.Console.Write(""DisposeAsync ""); await Task.Yield(); } public ValueTask DisposeAsync() => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_ReturnsVoid() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { public Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } public void DisposeAsync() => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics( // (7,33): error CS4008: Cannot await 'void' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadAwaitArgVoidCall, "new C()").WithLocation(7, 33) ); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_ReturnsInt() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() { return new Enumerator(); } public sealed class Enumerator { public async Task<bool> MoveNextAsync() { await Task.Yield(); return false; } public int Current { get => throw null; } public int DisposeAsync() { throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics( // (7,33): error CS1061: 'int' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C()").WithArguments("int", "GetAwaiter").WithLocation(7, 33) ); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_ReturnsAwaitable() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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 Awaitable DisposeAsync() { System.Console.Write(""DisposeAsync ""); return new Awaitable(); } } } public class Awaitable { public Awaiter GetAwaiter() { return new Awaiter(); } } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public bool IsCompleted { get { return true; } } public bool GetResult() { return true; } public void OnCompleted(System.Action continuation) { } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_ReturnsTask() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_ReturnsTaskOfInt() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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<int> DisposeAsync() { System.Console.Write(""DisposeAsync ""); await Task.Yield(); return 1; } } } "; // it's okay to await `Task<int>` even if we don't care about the result var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] public void PatternBasedDisposal_WithOptionalParameter() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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<int> DisposeAsync(int i = 1) { System.Console.Write($""DisposeAsync {i} ""); await Task.Yield(); return 1; } } } "; // it's okay to await `Task<int>` even if we don't care about the result var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync 1 Done"); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterBoxingConversion() { var source = @"using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; interface I1 { } interface I2 { } struct StructAwaitable1 : I1 { } struct StructAwaitable2 : I2 { } class Enumerable { public Enumerator GetAsyncEnumerator() => new Enumerator(); internal class Enumerator { public object Current => null; public StructAwaitable1 MoveNextAsync() => new StructAwaitable1(); public StructAwaitable2 DisposeAsync() => new StructAwaitable2(); } } static class Extensions { internal static TaskAwaiter<bool> GetAwaiter(this I1 x) { if (x == null) throw new ArgumentNullException(nameof(x)); Console.Write(x); return Task.FromResult(false).GetAwaiter(); } internal static TaskAwaiter GetAwaiter(this I2 x) { if (x == null) throw new ArgumentNullException(nameof(x)); Console.Write(x); return Task.CompletedTask.GetAwaiter(); } } class Program { static async Task Main() { await foreach (var o in new Enumerable()) { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "StructAwaitable1StructAwaitable2"); } [Fact] public void TestInvalidForeachOnConstantNullObject() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in (object)null) { Console.Write(i); } } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'object' because 'object' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in (object)null) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "(object)null").WithArguments("object", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestConstantNullObjectImplementingIEnumerable() { var source = @" using System; using System.Threading.Tasks; using System.Collections.Generic; public class C { public static async Task Main() { await foreach (var i in (IAsyncEnumerable<int>)null) { Console.Write(i); } } }"; CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (9,33): error CS0186: Use of null is not valid in this context // await foreach (var i in (IAsyncEnumerable<int>)null) Diagnostic(ErrorCode.ERR_NullNotValid, "(IAsyncEnumerable<int>)null").WithLocation(9, 33) ); } [Fact] public void TestConstantNullObjectWithGetAsyncEnumeratorPattern() { var source = @" using System; using System.Threading.Tasks; using System.Collections.Generic; public class C { public static async Task Main() { await foreach (var i in (C)null) { Console.Write(i); } } public IAsyncEnumerator<int> GetAsyncEnumerator() => throw null; }"; CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (9,33): error CS0186: Use of null is not valid in this context // await foreach (var i in (C)null) Diagnostic(ErrorCode.ERR_NullNotValid, "(C)null").WithLocation(9, 33) ); } [Fact] public void TestConstantNullableImplementingIEnumerable() { var source = @" using System; using System.Threading.Tasks; using System.Collections.Generic; public struct C : IAsyncEnumerable<int> { public static async Task Main() { await foreach (var i in (C?)null) { Console.Write(i); } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) => throw null; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp); } [Fact] public void TestConstantNullableWithGetAsyncEnumeratorPattern() { var source = @" using System; using System.Threading.Tasks; using System.Collections.Generic; public struct C { public static async Task Main() { await foreach (var i in (C?)null) { Console.Write(i); } } public IAsyncEnumerator<int> GetAsyncEnumerator() => throw null; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp); } [Fact] public void TestForeachNullLiteral() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in null) { Console.Write(i); } } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS0186: Use of null is not valid in this context // await foreach (var i in null) Diagnostic(ErrorCode.ERR_NullNotValid, "null").WithLocation(8, 33) ); } [Fact] public void TestForeachDefaultLiteral() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in default) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this object self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS8716: There is no target type for the default literal. // await foreach (var i in default) Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensions() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("C.Enumerator Extensions.GetAsyncEnumerator(this C self)", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<System.Boolean> C.Enumerator.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 C.Enumerator.Current { get; private set; }", info.CurrentProperty.ToTestDisplayString()); Assert.Null(info.DisposeMethod); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithUpcast() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this object self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnDefaultObject() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in default(object)) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this object self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithStructEnumerator() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithUserDefinedImplicitConversion() { string source = @" using System; using System.Threading.Tasks; public class C { public static implicit operator int(C c) => 0; public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this int self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,33): error CS1929: 'C' does not contain a definition for 'GetAsyncEnumerator' and the best extension method overload 'Extensions.GetAsyncEnumerator(int)' requires a receiver of type 'int' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new C()").WithArguments("C", "GetAsyncEnumerator", "Extensions.GetAsyncEnumerator(int)", "int").WithLocation(10, 33), // (10,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(10, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithNullableValueTypeConversion() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in 1) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this int? self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS1929: 'int' does not contain a definition for 'GetAsyncEnumerator' and the best extension method overload 'Extensions.GetAsyncEnumerator(int?)' requires a receiver of type 'int?' // await foreach (var i in 1) Diagnostic(ErrorCode.ERR_BadInstanceArgType, "1").WithArguments("int", "GetAsyncEnumerator", "Extensions.GetAsyncEnumerator(int?)", "int?").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'int' because 'int' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in 1) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "1").WithArguments("int", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithUnboxingConversion() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new object()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this int self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS1929: 'object' does not contain a definition for 'GetAsyncEnumerator' and the best extension method overload 'Extensions.GetAsyncEnumerator(int)' requires a receiver of type 'int' // await foreach (var i in new object()) Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new object()").WithArguments("object", "GetAsyncEnumerator", "Extensions.GetAsyncEnumerator(int)", "int").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'object' because 'object' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new object()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new object()").WithArguments("object", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithNullableUnwrapping() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in (int?)1) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this int self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS1929: 'int?' does not contain a definition for 'GetAsyncEnumerator' and the best extension method overload 'Extensions.GetAsyncEnumerator(int)' requires a receiver of type 'int' // await foreach (var i in (int?)1) Diagnostic(ErrorCode.ERR_BadInstanceArgType, "(int?)1").WithArguments("int?", "GetAsyncEnumerator", "Extensions.GetAsyncEnumerator(int)", "int").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'int?' because 'int?' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in (int?)1) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "(int?)1").WithArguments("int?", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithZeroToEnumConversion() { var source = @" using System; using System.Threading.Tasks; public enum E { Default = 0 } public class C { public static async Task Main() { await foreach (var i in 0) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this E self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (9,33): error CS1929: 'int' does not contain a definition for 'GetAsyncEnumerator' and the best extension method overload 'Extensions.GetAsyncEnumerator(E)' requires a receiver of type 'E' // await foreach (var i in 0) Diagnostic(ErrorCode.ERR_BadInstanceArgType, "0").WithArguments("int", "GetAsyncEnumerator", "Extensions.GetAsyncEnumerator(E)", "E").WithLocation(9, 33), // (9,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'int' because 'int' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in 0) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "0").WithArguments("int", "GetAsyncEnumerator").WithLocation(9, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithUnconstrainedGenericConversion() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await Inner(1); async Task Inner<T>(T t) { await foreach (var i in t) { Console.Write(i); } } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this object self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithConstrainedGenericConversion() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await Inner(1); async Task Inner<T>(T t) where T : IConvertible { await foreach (var i in t) { Console.Write(i); } } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this IConvertible self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithFormattableStringConversion1() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in $"" "") { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this FormattableString self) => throw null; public static C.Enumerator GetAsyncEnumerator(this object self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithFormattableStringConversion2() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in $"" "") { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this string self) => new C.Enumerator(); public static C.Enumerator GetAsyncEnumerator(this FormattableString self) => throw null; public static C.Enumerator GetAsyncEnumerator(this object self) => throw null; }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithFormattableStringConversion3() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in $"" "") { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this FormattableString self) => throw null; }"; CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS1929: 'string' does not contain a definition for 'GetAsyncEnumerator' and the best extension method overload 'Extensions.GetAsyncEnumerator(FormattableString)' requires a receiver of type 'FormattableString' // await foreach (var i in $" ") Diagnostic(ErrorCode.ERR_BadInstanceArgType, @"$"" """).WithArguments("string", "GetAsyncEnumerator", "Extensions.GetAsyncEnumerator(System.FormattableString)", "System.FormattableString").WithLocation(8, 33), // (8,33): error CS8415: Asynchronous foreach statement cannot operate on variables of type 'string' because 'string' does not contain a public instance or extension definition for 'GetAsyncEnumerator'. Did you mean 'foreach' rather than 'await foreach'? // await foreach (var i in $" ") Diagnostic(ErrorCode.ERR_AwaitForEachMissingMemberWrongAsync, @"$"" """).WithArguments("string", "GetAsyncEnumerator").WithLocation(8, 33)); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithDelegateConversion() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in () => 42) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this Func<int> self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? // await foreach (var i in () => 42) Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "() => 42").WithArguments("lambda expression").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithBoxing() { string source = @" using System; using System.Threading.Tasks; public struct C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this object self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnInterface() { var source = @" using System; using System.Threading.Tasks; public interface I {} public class C : I { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this I self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnDelegate() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in (Func<int>)(() => 42)) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this Func<int> self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnEnum() { var source = @" using System; using System.Threading.Tasks; public enum E { Default } public class C { public static async Task Main() { await foreach (var i in E.Default) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this E self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnNullable() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in (int?)null) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this int? self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnConstantNullObject() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in (object)null) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this object self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnTypeParameter() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new object()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator<T>(this T self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternOnRange() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in 1..4) { Console.Write(i); } } } public static class Extensions { public static async IAsyncEnumerator<int> GetAsyncEnumerator(this Range range) { await Task.Yield(); for(var i = range.Start.Value; i < range.End.Value; i++) { yield return i; } } }"; var comp = CreateCompilationWithTasksExtensions( new[] { source, TestSources.Index, TestSources.Range, AsyncStreamsTypes }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnTuple() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; public struct C { public static async Task Main() { await foreach (var i in (1, 2, 3)) { Console.Write(i); } } } public static class Extensions { public static async IAsyncEnumerator<T> GetAsyncEnumerator<T>(this (T first, T second, T third) self) { await Task.Yield(); yield return self.first; yield return self.second; yield return self.third; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnTupleWithNestedConversions() { var source = @" using System; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; public struct C { public static async Task Main() { await foreach (var (a, b) in (new[] { 1, 2, 3 }, new List<decimal>{ 0.1m, 0.2m, 0.3m })) { Console.WriteLine(a + b); } } } public static class Extensions { public static async IAsyncEnumerator<(T1, T2)> GetAsyncEnumerator<T1, T2>(this (IEnumerable<T1> first, IEnumerable<T2> second) self) { await Task.Yield(); foreach(var pair in self.first.Zip(self.second, (a,b) => (a,b))) { yield return pair; } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"1.1 2.2 3.3"); } [Fact] public void TestMoveNextAsyncPatternViaExtensions1() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); public static bool MoveNext(this C.Enumerator e) => false; }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,33): error CS0117: 'C.Enumerator' does not contain a definition for 'MoveNextAsync' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator", "MoveNextAsync").WithLocation(8, 33), // (8,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'Extensions.GetAsyncEnumerator(C)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "Extensions.GetAsyncEnumerator(C)").WithLocation(8, 33) ); } [Fact] public void TestMoveNextAsyncPatternViaExtensions2() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } } public C.Enumerator GetAsyncEnumerator() => new C.Enumerator(); } public static class Extensions { public static bool MoveNext(this C.Enumerator e) => false; }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,33): error CS0117: 'C.Enumerator' does not contain a definition for 'MoveNextAsync' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator", "MoveNextAsync").WithLocation(8, 33), // (8,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator()").WithLocation(8, 33) ); } [Fact] public void TestPreferAsyncEnumeratorPatternFromInstanceThanViaExtension() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator1 { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } public sealed class Enumerator2 { public int Current { get; private set; } public Task<bool> MoveNextAsync() => throw null; } public C.Enumerator1 GetAsyncEnumerator() => new C.Enumerator1(); } public static class Extensions { public static C.Enumerator2 GetAsyncEnumerator(this C self) => throw null; }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestPreferAsyncEnumeratorPatternFromInstanceThanViaExtensionEvenWhenInvalid() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator1 { } public sealed class Enumerator2 { public int Current { get; private set; } public Task<bool> MoveNextAsync() => throw null; } public C.Enumerator1 GetAsyncEnumerator() => throw null; } public static class Extensions { public static C.Enumerator2 GetAsyncEnumerator(this C self) => throw null; }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,33): error CS0117: 'C.Enumerator1' does not contain a definition for 'Current' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator1", "Current").WithLocation(8, 33), // (8,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator1' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator1", "C.GetAsyncEnumerator()").WithLocation(8, 33)); } [Fact] public void TestPreferAsyncEnumeratorPatternFromIAsyncEnumerableInterfaceThanViaExtension() { string source = @" using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; public class C : IAsyncEnumerable<int> { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator1 : IAsyncEnumerator<int> { public int Current { get; private set; } public ValueTask<bool> MoveNextAsync() => new ValueTask<bool>(Current++ != 3); public ValueTask DisposeAsync() => new ValueTask(); } public sealed class Enumerator2 { public int Current { get; private set; } public Task<bool> MoveNextAsync() => throw null; } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(CancellationToken cancellationToken) => new C.Enumerator1(); } public static class Extensions { public static C.Enumerator2 GetAsyncEnumerator(this C self) => throw null; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestCannotUseExtensionGetAsyncEnumeratorOnDynamic() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in (dynamic)new C()) { Console.Write(i); } } public sealed class Enumerator2 { public int Current { get; private set; } public bool MoveNext() => throw null; } } public static class Extensions { public static C.Enumerator2 GetAsyncEnumerator(this C self) => throw null; }"; CreateCompilationWithCSharp(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (9,33): error CS8416: Cannot use a collection of dynamic type in an asynchronous foreach // await foreach (var i in (dynamic)new C()) Diagnostic(ErrorCode.ERR_BadDynamicAwaitForEach, "(dynamic)new C()").WithLocation(9, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensions() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,33): warning CS0278: 'C' does not implement the 'collection' pattern. 'Extensions1.GetAsyncEnumerator(C)' is ambiguous with 'Extensions2.GetAsyncEnumerator(C)'. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "new C()").WithArguments("C", "collection", "Extensions1.GetAsyncEnumerator(C)", "Extensions2.GetAsyncEnumerator(C)").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWhenOneHasCorrectPattern() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static int GetAsyncEnumerator(this C self) => 42; } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): warning CS0278: 'C' does not implement the 'collection' pattern. 'Extensions1.GetAsyncEnumerator(C)' is ambiguous with 'Extensions2.GetAsyncEnumerator(C)'. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "new C()").WithArguments("C", "collection", "Extensions1.GetAsyncEnumerator(C)", "Extensions2.GetAsyncEnumerator(C)").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWhenNeitherHasCorrectPattern() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static int GetAsyncEnumerator(this C self) => 42; } public static class Extensions2 { public static bool GetAsyncEnumerator(this C self) => true; }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): warning CS0278: 'C' does not implement the 'collection' pattern. 'Extensions1.GetAsyncEnumerator(C)' is ambiguous with 'Extensions2.GetAsyncEnumerator(C)'. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "new C()").WithArguments("C", "collection", "Extensions1.GetAsyncEnumerator(C)", "Extensions2.GetAsyncEnumerator(C)").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWhenOneHasCorrectNumberOfParameters() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this C self, int _) => throw null; } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWhenNeitherHasCorrectNumberOfParameters() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this C self, int _) => new C.Enumerator(); } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this C self, bool _) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS1501: No overload for method 'GetAsyncEnumerator' takes 0 arguments // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadArgCount, "new C()").WithArguments("GetAsyncEnumerator", "0").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsOnDifferentInterfaces() { var source = @" using System; using System.Threading.Tasks; public interface I1 {} public interface I2 {} public class C : I1, I2 { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this I1 self) => new C.Enumerator(); } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this I2 self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (12,33): warning CS0278: 'C' does not implement the 'collection' pattern. 'Extensions1.GetAsyncEnumerator(I1)' is ambiguous with 'Extensions2.GetAsyncEnumerator(I2)'. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "new C()").WithArguments("C", "collection", "Extensions1.GetAsyncEnumerator(I1)", "Extensions2.GetAsyncEnumerator(I2)").WithLocation(12, 33), // (12,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(12, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWithMostSpecificReceiver() { var source = @" using System; using System.Threading.Tasks; public interface I {} public class C : I { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this I self) => throw null; } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWithMostSpecificReceiverWhenMostSpecificReceiverDoesntImplementPattern() { var source = @" using System; using System.Threading.Tasks; public interface I {} public class C : I { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this I self) => throw null; } public static class Extensions2 { public static int GetAsyncEnumerator(this C self) => 42; }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (10,33): error CS0117: 'int' does not contain a definition for 'Current' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("int", "Current").WithLocation(10, 33), // (10,33): error CS8412: Asynchronous foreach requires that the return type 'int' of 'Extensions2.GetAsyncEnumerator(C)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("int", "Extensions2.GetAsyncEnumerator(C)").WithLocation(10, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWhenOneHasOptionalParams() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this C self, int a = 0) => throw null; }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWhenOneHasFewerOptionalParams() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this C self, int a = 0, int b = 1) => new C.Enumerator(); } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this C self, int a = 0) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): warning CS0278: 'C' does not implement the 'collection' pattern. 'Extensions1.GetAsyncEnumerator(C, int, int)' is ambiguous with 'Extensions2.GetAsyncEnumerator(C, int)'. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "new C()").WithArguments("C", "collection", "Extensions1.GetAsyncEnumerator(C, int, int)", "Extensions2.GetAsyncEnumerator(C, int)").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithOptionalParameter() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public Enumerator(int start) => Current = start; public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self, int x = 1) => new C.Enumerator(x); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "23"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithArgList() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self, __arglist) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'Extensions.GetAsyncEnumerator(C, __arglist)' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "new C()").WithArguments("__arglist", "Extensions.GetAsyncEnumerator(C, __arglist)").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithParams() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public Enumerator(int[] arr) => Current = arr.Length; public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self, params int[] x) => new C.Enumerator(x); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaRefExtensionOnNonAssignableVariable() { string source = @" using System; using System.Threading.Tasks; public struct C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this ref C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,33): error CS1510: A ref or out value must be an assignable variable // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new C()").WithLocation(8, 33)); } [Fact] public void TestGetAsyncEnumeratorPatternViaRefExtensionOnAssignableVariable() { string source = @" using System; using System.Threading.Tasks; public struct C { public static async Task Main() { var c = new C(); await foreach (var i in c) { Console.Write(i); } } public struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this ref C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,33): error CS1510: A ref or out value must be an assignable variable // await foreach (var i in c) Diagnostic(ErrorCode.ERR_RefLvalueExpected, "c").WithLocation(9, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaOutExtension() { string source = @" using System; using System.Threading.Tasks; public struct C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this out C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,33): error CS1620: Argument 1 must be passed with the 'out' keyword // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadArgRef, "new C()").WithArguments("1", "out").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33), // (21,56): error CS8328: The parameter modifier 'out' cannot be used with 'this' // public static C.Enumerator GetAsyncEnumerator(this out C self) => new C.Enumerator(); Diagnostic(ErrorCode.ERR_BadParameterModifiers, "out").WithArguments("out", "this").WithLocation(21, 56)); } [Fact] public void TestGetAsyncEnumeratorPatternViaInExtensionOnNonAssignableVariable() { string source = @" using System; using System.Threading.Tasks; public struct C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this in C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaInExtensionOnAssignableVariable() { string source = @" using System; using System.Threading.Tasks; public struct C { public static async Task Main() { var c = new C(); await foreach (var i in c) { Console.Write(i); } } public struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this in C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsCSharp8() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (8,33): error CS8400: Feature 'extension GetAsyncEnumerator' is not available in C# 8.0. Please use language version 9.0 or greater. // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "new C()").WithArguments("extension GetAsyncEnumerator", "9.0").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaInternalExtensions() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { internal static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionInInternalClass() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } internal static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithInvalidEnumerator() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } } } internal static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS0117: 'C.Enumerator' does not contain a definition for 'MoveNextAsync' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator", "MoveNextAsync").WithLocation(8, 33), // (8,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'Extensions.GetAsyncEnumerator(C)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "Extensions.GetAsyncEnumerator(C)").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithInstanceGetAsyncEnumeratorReturningTypeWhichDoesntMatchPattern() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator1 { public int Current { get; private set; } } public sealed class Enumerator2 { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } public Enumerator1 GetAsyncEnumerator() => new Enumerator1(); } internal static class Extensions { public static C.Enumerator2 GetAsyncEnumerator(this C self) => new C.Enumerator2(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS0117: 'C.Enumerator1' does not contain a definition for 'MoveNextAsync' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator1", "MoveNextAsync").WithLocation(8, 33), // (8,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator1' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator1", "C.GetAsyncEnumerator()").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithInternalInstanceGetAsyncEnumerator() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } internal Enumerator GetAsyncEnumerator() => throw null; } internal static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,33): warning CS0279: 'C' does not implement the 'async streams' pattern. 'C.GetAsyncEnumerator()' is not a public instance or extension method. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "new C()").WithArguments("C", "async streams", "C.GetAsyncEnumerator()").WithLocation(8, 33) ); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithInstanceGetAsyncEnumeratorWithTooManyParameters() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } internal Enumerator GetAsyncEnumerator(int a) => throw null; } internal static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithStaticGetAsyncEnumeratorDeclaredInType() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } public static Enumerator GetAsyncEnumerator() => throw null; } internal static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestAwaitForEachViaExtensionImplicitImplementationOfIAsyncDisposableStruct() { var source = @" using System; using System.Threading.Tasks; class C { static async Task Main() { await foreach (var x in new C()) { Console.Write(x); } } } static class Extensions { public static Enumerator GetAsyncEnumerator(this C _) => new Enumerator(); } struct Enumerator : IAsyncDisposable { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); public ValueTask DisposeAsync() { Console.Write(""Disposed""); return new ValueTask(); } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"123Disposed"); } [Fact] public void TestAwaitForEachViaExtensionExplicitlyDisposableStruct() { var source = @" using System; using System.Threading.Tasks; class C { static async Task Main() { await foreach (var x in new C()) { Console.Write(x); } } } static class Extensions { public static Enumerator GetAsyncEnumerator(this C _) => new Enumerator(); } struct Enumerator : IAsyncDisposable { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); ValueTask IAsyncDisposable.DisposeAsync() { Console.Write(""Disposed""); return new ValueTask(); } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"123Disposed"); } [Fact] public void TestAwaitForEachViaExtensionAsyncDisposeStruct() { var source = @" using System; using System.Threading.Tasks; class C { static async Task Main() { await foreach (var x in new C()) { Console.Write(x); } } } static class Extensions { public static Enumerator GetAsyncEnumerator(this C _) => new Enumerator(); } struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); public ValueTask DisposeAsync() { Console.Write(""Disposed""); return new ValueTask(); } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"123Disposed"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithTaskLikeTypeMoveNext() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public ValueTask<bool> MoveNextAsync() => new ValueTask<bool>(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestWithObsoletePatternMethodsViaExtension() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { [Obsolete] public int Current { get; private set; } [Obsolete] public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); [Obsolete] public Task DisposeAsync() { Console.Write(""Disposed""); return Task.CompletedTask; } } } [Obsolete] public static class Extensions { [Obsolete] public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,15): warning CS0612: 'Extensions.GetAsyncEnumerator(C)' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("Extensions.GetAsyncEnumerator(C)").WithLocation(8, 15), // (8,15): warning CS0612: 'C.Enumerator.MoveNextAsync()' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.Enumerator.MoveNextAsync()").WithLocation(8, 15), // (8,15): warning CS0612: 'C.Enumerator.Current' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.Enumerator.Current").WithLocation(8, 15) ); CompileAndVerify(comp, expectedOutput: "123Disposed"); } [Fact] public void TestGetAsyncEnumeratorPatternViaImportedExtensions() { string source = @" using System; using System.Threading.Tasks; using N; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } namespace N { public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaUnimportedExtensions() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } namespace N { public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } }"; CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestWithPatternGetAsyncEnumeratorViaExtensionOnUnassignedCollection() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { C c; await foreach (var i in c) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,33): error CS0165: Use of unassigned local variable 'c' // await foreach (var i in c) Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c").WithLocation(9, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaValidExtensionInClosestNamespaceInvalidInFurtherNamespace1() { var source = @" using System; using System.Threading.Tasks; using N1.N2.N3; namespace N1 { public static class Extensions { public static int GetAsyncEnumerator(this C self) => throw null; } namespace N2 { public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } namespace N3 { using N2; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } } } }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaValidExtensionInClosestNamespaceInvalidInFurtherNamespace2() { var source = @" using System; using System.Threading.Tasks; using N1; using N3; namespace N1 { using N2; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } } namespace N2 { public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } } namespace N3 { public static class Extensions { public static int GetAsyncEnumerator(this C self) => throw null; } }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,1): hidden CS8019: Unnecessary using directive. // using N3; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N3;").WithLocation(5, 1)); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaInvalidExtensionInClosestNamespaceValidInFurtherNamespace1() { var source = @" using System; using System.Threading.Tasks; using N1.N2.N3; namespace N1 { public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } namespace N2 { public static class Extensions { public static int GetAsyncEnumerator(this C self) => throw null; } namespace N3 { using N2; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } } } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (27,45): error CS0117: 'int' does not contain a definition for 'Current' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("int", "Current").WithLocation(27, 45), // (27,45): error CS8412: Asynchronous foreach requires that the return type 'int' of 'Extensions.GetAsyncEnumerator(C)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("int", "N1.N2.Extensions.GetAsyncEnumerator(N1.N2.N3.C)").WithLocation(27, 45)); } [Fact] public void TestGetAsyncEnumeratorPatternViaInvalidExtensionInClosestNamespaceValidInFurtherNamespace2() { var source = @" using System; using System.Threading.Tasks; using N1; using N2; namespace N1 { using N3; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } } namespace N2 { public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } } namespace N3 { public static class Extensions { public static int GetAsyncEnumerator(this C self) => throw null; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (5,1): hidden CS8019: Unnecessary using directive. // using N2; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N2;").WithLocation(5, 1), // (14,37): error CS0117: 'int' does not contain a definition for 'Current' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("int", "Current").WithLocation(14, 37), // (14,37): error CS8412: Asynchronous foreach requires that the return type 'int' of 'Extensions.GetAsyncEnumerator(C)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("int", "N3.Extensions.GetAsyncEnumerator(N1.C)").WithLocation(14, 37)); } [Fact] public void TestGetAsyncEnumeratorPatternViaAccessiblePrivateExtension() { var source = @" using System; using System.Threading.Tasks; public static class Program { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } private static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } public class C { public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaAccessiblePrivateExtensionInNestedClass() { var source = @" using System; using System.Threading.Tasks; public static class Program { public static class Inner { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } } private static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } public class C { public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaInaccessiblePrivateExtension() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { private static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } "; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithRefReturn() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } await foreach (var i in new C()) { Console.Write(i); } } public struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator Instance = new C.Enumerator(); public static ref C.Enumerator GetAsyncEnumerator(this C self) => ref Instance; }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123123"); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { [CompilerTrait(CompilerFeature.AsyncStreams)] public class CodeGenAwaitForeachTests : EmitMetadataTestBase { [Fact] public void TestWithCSharp7_3() { string source = @" using System.Collections.Generic; class C : IAsyncEnumerable<int> { public static async System.Threading.Tasks.Task Main() { await foreach (int i in new C()) { } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; }"; var expected = new[] { // (7,9): error CS8652: The feature 'async streams' is not available in C# 7.3. Please use language version 8.0 or greater. // await foreach (int i in new C()) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "await").WithArguments("async streams", "8.0").WithLocation(7, 9) }; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(expected); comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void TestWithMissingValueTask() { string lib_cs = @" using System.Collections.Generic; public class C : IAsyncEnumerable<int> { IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; }"; var lib = CreateCompilationWithTasksExtensions(new[] { lib_cs, s_IAsyncEnumerable }); lib.VerifyDiagnostics(); string source = @" class D { public static async System.Threading.Tasks.Task Main() { await foreach (int i in new C()) { } } } "; var comp = CreateCompilationWithTasksExtensions(source, references: new[] { lib.EmitToImageReference() }); comp.MakeTypeMissing(WellKnownType.System_Threading_Tasks_ValueTask); comp.VerifyDiagnostics( // (6,9): error CS0518: Predefined type 'System.Threading.Tasks.ValueTask' is not defined or imported // await foreach (int i in new C()) { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await foreach (int i in new C()) { }").WithArguments("System.Threading.Tasks.ValueTask").WithLocation(6, 9) ); } [Fact] public void TestWithIAsyncEnumerator() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; public class C { async Task M(IAsyncEnumerator<int> enumerator) { await foreach (int i in enumerator) { } } } "; var comp_checked = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp_checked.VerifyDiagnostics( // (8,33): error CS8411: Async foreach statement cannot operate on variables of type 'IAsyncEnumerator<int>' because 'IAsyncEnumerator<int>' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (int i in enumerator) { } Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "enumerator").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestWithUIntToIntConversion() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; public class C : IAsyncEnumerable<uint> { public static async Task Main() { try { REPLACE { await foreach (int i in new C()) { System.Console.Write($""0x{i:X8}""); } } } catch (System.OverflowException) { System.Console.Write(""overflow""); } } public IAsyncEnumerator<uint> GetAsyncEnumerator(System.Threading.CancellationToken token) => new AsyncEnumerator(); public sealed class AsyncEnumerator : IAsyncEnumerator<uint> { bool firstValue = true; public uint Current => 0xFFFFFFFF; public async ValueTask<bool> MoveNextAsync() { await Task.Yield(); bool result = firstValue; firstValue = false; return result; } public async ValueTask DisposeAsync() { await Task.Yield(); } } } "; var comp_checked = CreateCompilationWithTasksExtensions(new[] { source.Replace("REPLACE", "checked"), s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp_checked.VerifyDiagnostics(); CompileAndVerify(comp_checked, expectedOutput: "overflow"); var comp_unchecked = CreateCompilationWithTasksExtensions(new[] { source.Replace("REPLACE", "unchecked"), s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp_unchecked.VerifyDiagnostics(); CompileAndVerify(comp_unchecked, expectedOutput: "0xFFFFFFFF"); } [Fact] public void TestWithTwoIAsyncEnumerableImplementations() { string source = @" using System.Collections.Generic; class C : IAsyncEnumerable<int>, IAsyncEnumerable<string> { public static async System.Threading.Tasks.Task Main() { await foreach (int i in new C()) { } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; IAsyncEnumerator<string> IAsyncEnumerable<string>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics( // (7,33): error CS8413: Async foreach statement cannot operate on variables of type 'C' because it implements multiple instantiations of 'IAsyncEnumerable<T>'; try casting to a specific interface instantiation // await foreach (int i in new C()) Diagnostic(ErrorCode.ERR_MultipleIAsyncEnumOfT, "new C()").WithArguments("C", "System.Collections.Generic.IAsyncEnumerable<T>").WithLocation(7, 33) ); } [Fact] public void TestWithMissingPattern() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8411: Async foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(6, 33) ); } [Fact] public void TestWithStaticGetEnumerator() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public static Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token) { throw null; } public sealed class Enumerator { } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8411: Async foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(6, 33) ); } [Fact] public void TestWithInaccessibleGetEnumerator() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } internal Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } public sealed class Enumerator { } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): warning CS0279: 'C' does not implement the 'async streams' pattern. 'C.GetAsyncEnumerator(System.Threading.CancellationToken)' is not a public instance or extension method. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "new C()").WithArguments("C", "async streams", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33), // (6,33): error CS8411: Async foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(6, 33) ); } [Fact] public void TestWithObsoletePatternMethods() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } [System.Obsolete] public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } public sealed class Enumerator { [System.Obsolete] public System.Threading.Tasks.Task<bool> MoveNextAsync() { throw null; } [System.Obsolete] public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,15): warning CS0612: 'C.GetAsyncEnumerator(CancellationToken)' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 15), // (6,15): warning CS0612: 'C.Enumerator.MoveNextAsync()' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.Enumerator.MoveNextAsync()").WithLocation(6, 15), // (6,15): warning CS0612: 'C.Enumerator.Current' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.Enumerator.Current").WithLocation(6, 15) ); } [Fact] public void TestWithMoveNextAsync_ReturnsValueTaskOfObject() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<object> MoveNextAsync() => throw null; public int Current => throw null; } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator()").WithLocation(6, 33) ); } [Fact] public void TestWithMoveNextAsync_ReturnsObject() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<object> MoveNextAsync() => throw null; // returns Task<object> public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator()").WithLocation(6, 33) ); } [Fact] public void TestWithMoveNextAsync_Static() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } public sealed class Enumerator { public static System.Threading.Tasks.Task<bool> MoveNextAsync() { throw null; } public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33) ); } [Fact] public void TestWithCurrent_Static() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public static int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator()").WithLocation(6, 33) ); } [Fact] public void TestWithMoveNextAsync_NonPublic() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { internal System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current => throw null; } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator()").WithLocation(6, 33) ); } [Fact] public void TestWithCurrent_NonPublicProperty() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; private int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS0122: 'C.Enumerator.Current' is inaccessible due to its protection level // await foreach (var i in new C()) { } Diagnostic(ErrorCode.ERR_BadAccess, "new C()").WithArguments("C.Enumerator.Current").WithLocation(6, 33), // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33) ); } [Fact] public void TestWithCurrent_NonPublicGetter() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { private get => throw null; set => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator()").WithLocation(6, 33) ); } [Fact] public void TestWithCurrent_MissingGetter() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { set => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33) ); } [Fact] public void TestWithCurrent_MissingGetterOnInterface() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task M(C c) { await foreach (var i in c) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default); } public interface IAsyncEnumerator<out T> : System.IAsyncDisposable { System.Threading.Tasks.Task<bool> MoveNextAsync(); T Current { set; } } } namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } "; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyEmitDiagnostics( // (8,33): error CS8412: Asynchronous foreach requires that the return type 'IAsyncEnumerator<int>' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in c) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "c").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(8, 33), // (24,9): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'IAsyncEnumerator<T>.Current'. 'T' is covariant. // T Current { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("System.Collections.Generic.IAsyncEnumerator<T>.Current", "T", "covariant", "contravariantly").WithLocation(24, 9) ); } [Fact] public void TestWithCurrent_MissingPropertyOnInterface() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task M(C c) { await foreach (var i in c) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default); } public interface IAsyncEnumerator<out T> : System.IAsyncDisposable { System.Threading.Tasks.Task<bool> MoveNextAsync(); } } namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } "; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyEmitDiagnostics( // (8,33): error CS0117: 'IAsyncEnumerator<int>' does not contain a definition for 'Current' // await foreach (var i in c) Diagnostic(ErrorCode.ERR_NoSuchMember, "c").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "Current").WithLocation(8, 33), // (8,33): error CS8412: Asynchronous foreach requires that the return type 'IAsyncEnumerator<int>' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in c) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "c").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(8, 33) ); } [Fact] public void TestMoveNextAsync_ReturnsTask() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } public sealed class Enumerator { public System.Threading.Tasks.Task MoveNextAsync() { throw null; } public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33) ); } [Fact] public void TestMoveNextAsync_ReturnsTaskOfInt() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } public sealed class Enumerator { public System.Threading.Tasks.Task<int> MoveNextAsync() { throw null; } public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33) ); } [Fact] public void TestMoveNextAsync_WithOptionalParameter() { string source = @" public class C { public static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new Enumerator(); } public sealed class Enumerator { public async System.Threading.Tasks.Task<bool> MoveNextAsync(int ok = 1) { System.Console.Write($""MoveNextAsync {ok}""); await System.Threading.Tasks.Task.Yield(); return false; } public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync 1"); } [Fact] public void TestMoveNextAsync_WithParamsParameter() { string source = @" public class C { public static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new Enumerator(); } public sealed class Enumerator { public async System.Threading.Tasks.Task<bool> MoveNextAsync(params int[] ok) { System.Console.Write($""MoveNextAsync {ok.Length}""); await System.Threading.Tasks.Task.Yield(); return false; } public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync 0"); } [Fact] public void TestMoveNextAsync_Missing() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task M(C c) { await foreach (var i in c) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default); } public interface IAsyncEnumerator<out T> : System.IAsyncDisposable { T Current { get; } } } namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } "; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyEmitDiagnostics( // (8,33): error CS0117: 'IAsyncEnumerator<int>' does not contain a definition for 'MoveNextAsync' // await foreach (var i in c) Diagnostic(ErrorCode.ERR_NoSuchMember, "c").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "MoveNextAsync").WithLocation(8, 33), // (8,33): error CS8412: Asynchronous foreach requires that the return type 'IAsyncEnumerator<int>' of 'C.GetAsyncEnumerator(CancellationToken)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in c) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "c").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(8, 33) ); } [Fact] public void TestWithNonConvertibleElementType() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (string i in new C()) { } } public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,15): error CS0030: Cannot convert type 'int' to 'string' // await foreach (string i in new C()) Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("int", "string").WithLocation(6, 15) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.True(info.IsAsynchronous); Assert.Equal("C.Enumerator C.GetAsyncEnumerator()", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<System.Boolean> C.Enumerator.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 C.Enumerator.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Null(info.DisposeMethod); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.NoConversion, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); } [Fact] public void TestWithNonConvertibleElementType2() { string source = @" using System.Threading.Tasks; class C { async Task M() { await foreach (Element i in new C()) { } } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class AsyncEnumerator { public int Current { get => throw null; } public Task<bool> MoveNextAsync() => throw null; public ValueTask DisposeAsync() => throw null; } } class Element { }"; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyDiagnostics( // (7,15): error CS0030: Cannot convert type 'int' to 'Element' // await foreach (Element i in new C()) Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("int", "Element").WithLocation(7, 15) ); } [Fact] public void TestWithExplicitlyConvertibleElementType() { string source = @" using static System.Console; using System.Threading.Tasks; class C { public static async System.Threading.Tasks.Task Main() { await foreach (Element i in new C()) { Write($""Got({i}) ""); } } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new AsyncEnumerator(); } public sealed class AsyncEnumerator : System.IAsyncDisposable { int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async Task<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; bool more = await Task.FromResult(i < 4); return more; } public async ValueTask DisposeAsync() { Write($""Dispose({i}) ""); await Task.Yield(); } } } class Element { int i; public static explicit operator Element(int value) { Write($""Convert({value}) ""); return new Element(value); } private Element(int value) { i = value; } public override string ToString() => i.ToString(); }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Convert(1) Got(1) NextAsync(1) Current(2) Convert(2) Got(2) NextAsync(2) Current(3) Convert(3) Got(3) NextAsync(3) Dispose(4)"); } [Fact] public void TestWithCaptureOfIterationVariable() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async System.Threading.Tasks.Task Main() { System.Action f = null; await foreach (var i in new C()) { Write($""Got({i}) ""); if (f == null) f = () => Write($""Captured({i})""); } f(); } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new AsyncEnumerator(); } public sealed class AsyncEnumerator : System.IAsyncDisposable { int i = 0; public int Current => i; public async Task<bool> MoveNextAsync() { i++; return await Task.FromResult(i < 3); } public async ValueTask DisposeAsync() { await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Got(1) Got(2) Captured(1)"); } [Fact] public void TestWithGenericIterationVariable() { string source = @" using static System.Console; using System.Threading.Tasks; class IntContainer { public int Value { get; set; } } public class Program { public static async System.Threading.Tasks.Task Main() { await foreach (var i in new C<IntContainer>()) { Write($""Got({i.Value}) ""); } } } class C<T> where T : IntContainer, new() { public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new AsyncEnumerator(); } public sealed class AsyncEnumerator : System.IAsyncDisposable { int i = 0; public T Current { get { Write($""Current({i}) ""); var result = new T(); ((IntContainer)result).Value = i; return result; } } public async Task<bool> MoveNextAsync() { i++; Write($""NextAsync({i}) ""); return await Task.FromResult(i < 4); } public async ValueTask DisposeAsync() { Write($""Dispose({i}) ""); await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(1) Current(1) Got(1) NextAsync(2) Current(2) Got(2) NextAsync(3) Current(3) Got(3) NextAsync(4) Dispose(4)"); } [Fact] public void TestWithThrowingGetAsyncEnumerator() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async Task Main() { try { await foreach (var i in new C()) { throw null; } throw null; } catch (System.ArgumentException e) { Write(e.Message); } } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw new System.ArgumentException(""exception""); public sealed class AsyncEnumerator : System.IAsyncDisposable { public int Current => throw null; public Task<bool> MoveNextAsync() => throw null; public ValueTask DisposeAsync() => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "exception"); } [Fact] public void TestWithThrowingMoveNextAsync() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async Task Main() { try { await foreach (var i in new C()) { throw null; } throw null; } catch (System.ArgumentException e) { Write(e.Message); } } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => new AsyncEnumerator(); public sealed class AsyncEnumerator : System.IAsyncDisposable { public int Current => throw null; public Task<bool> MoveNextAsync() => throw new System.ArgumentException(""exception""); public async ValueTask DisposeAsync() { Write(""dispose ""); await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "dispose exception"); } [Fact] public void TestWithThrowingCurrent() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async Task Main() { try { await foreach (var i in new C()) { throw null; } throw null; } catch (System.ArgumentException e) { Write(e.Message); } } public AsyncEnumerator GetAsyncEnumerator() => new AsyncEnumerator(); public sealed class AsyncEnumerator : System.IAsyncDisposable { public int Current => throw new System.ArgumentException(""exception""); public async Task<bool> MoveNextAsync() { Write(""wait ""); await Task.Yield(); return true; } public async ValueTask DisposeAsync() { Write(""dispose ""); await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "wait dispose exception"); } [Fact] public void TestWithThrowingDisposeAsync() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async Task Main() { try { await foreach (var i in new C()) { throw null; } throw null; } catch (System.ArgumentException e) { Write(e.Message); } } public AsyncEnumerator GetAsyncEnumerator() => new AsyncEnumerator(); public sealed class AsyncEnumerator : System.IAsyncDisposable { public int Current => throw null; public async Task<bool> MoveNextAsync() { Write(""wait ""); await Task.Yield(); return false; } public ValueTask DisposeAsync() => throw new System.ArgumentException(""exception""); } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "wait exception"); } [Fact] public void TestWithDynamicCollection() { string source = @" class C { public static async System.Threading.Tasks.Task Main() { await foreach (var i in (dynamic)new C()) { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics( // (6,33): error CS8416: Cannot use a collection of dynamic type in an asynchronous foreach // await foreach (var i in (dynamic)new C()) Diagnostic(ErrorCode.ERR_BadDynamicAwaitForEach, "(dynamic)new C()").WithLocation(6, 33)); } [Fact] public void TestWithIncompleteInterface() { string source = @" namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { } } class C { async System.Threading.Tasks.Task M(System.Collections.Generic.IAsyncEnumerable<int> collection) { await foreach (var i in collection) { } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (12,33): error CS8411: Async foreach statement cannot operate on variables of type 'IAsyncEnumerable<int>' because 'IAsyncEnumerable<int>' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in collection) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "collection").WithArguments("System.Collections.Generic.IAsyncEnumerable<int>", "GetAsyncEnumerator").WithLocation(12, 33) ); } [Fact] public void TestWithIncompleteInterface2() { string source = @" namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default); } public interface IAsyncEnumerator<out T> { System.Threading.Tasks.Task<bool> MoveNextAsync(); } } class C { async System.Threading.Tasks.Task M(System.Collections.Generic.IAsyncEnumerable<int> collection) { await foreach (var i in collection) { } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (18,33): error CS0117: 'IAsyncEnumerator<int>' does not contain a definition for 'Current' // await foreach (var i in collection) Diagnostic(ErrorCode.ERR_NoSuchMember, "collection").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "Current").WithLocation(18, 33), // (18,33): error CS8412: Async foreach requires that the return type 'IAsyncEnumerator<int>' of 'IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken)' must have a suitable public MoveNextAsync method and public Current property // await foreach (var i in collection) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "collection").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "System.Collections.Generic.IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(18, 33) ); } [Fact] public void TestWithIncompleteInterface3() { string source = @" namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default); } public interface IAsyncEnumerator<out T> { T Current { get; } } } class C { async System.Threading.Tasks.Task M(System.Collections.Generic.IAsyncEnumerable<int> collection) { await foreach (var i in collection) { } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (18,33): error CS0117: 'IAsyncEnumerator<int>' does not contain a definition for 'MoveNextAsync' // await foreach (var i in collection) Diagnostic(ErrorCode.ERR_NoSuchMember, "collection").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "MoveNextAsync").WithLocation(18, 33), // (18,33): error CS8412: Async foreach requires that the return type 'IAsyncEnumerator<int>' of 'IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken)' must have a suitable public MoveNextAsync method and public Current property // await foreach (var i in collection) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "collection").WithArguments("System.Collections.Generic.IAsyncEnumerator<int>", "System.Collections.Generic.IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(18, 33) ); } [Fact] public void TestWithSyncPattern() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetEnumerator() { throw null; } public sealed class Enumerator { bool MoveNext() => throw null; int Current => throw null; } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,33): error CS8411: Async foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(6, 33) ); } [Fact] public void TestRegularForeachWithAsyncPattern() { string source = @" class C { void M() { foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (6,27): error CS8414: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator'. Did you mean 'await foreach' rather than 'foreach'? // foreach (var i in new C()) Diagnostic(ErrorCode.ERR_ForEachMissingMemberWrongAsync, "new C()").WithArguments("C", "GetEnumerator").WithLocation(6, 27) ); } [Fact] public void TestRegularForeachWithAsyncInterface() { string source = @" using System.Collections.Generic; class C { void M(IAsyncEnumerable<int> collection) { foreach (var i in collection) { } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (7,27): error CS8414: foreach statement cannot operate on variables of type 'IAsyncEnumerable<int>' because 'IAsyncEnumerable<int>' does not contain a public instance or extension definition for 'GetEnumerator'. Did you mean 'await foreach'? // foreach (var i in collection) Diagnostic(ErrorCode.ERR_ForEachMissingMemberWrongAsync, "collection").WithArguments("System.Collections.Generic.IAsyncEnumerable<int>", "GetEnumerator").WithLocation(7, 27) ); } [Fact] public void TestWithSyncInterfaceInRegularMethod() { string source = @" using System.Collections.Generic; class C { void M(IEnumerable<int> collection) { await foreach (var i in collection) { } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (7,9): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // await foreach (var i in collection) Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(7, 9), // (7,33): error CS8415: Asynchronous foreach statement cannot operate on variables of type 'IEnumerable<int>' because 'IEnumerable<int>' does not contain a public instance or extension definition for 'GetAsyncEnumerator'. Did you mean 'foreach' rather than 'await foreach'? // await foreach (var i in collection) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMemberWrongAsync, "collection").WithArguments("System.Collections.Generic.IEnumerable<int>", "GetAsyncEnumerator").WithLocation(7, 33) ); } [Fact] public void TestPatternBasedAsyncEnumerableWithRegularForeach() { string source = @" class C { void M() { foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,27): error CS8414: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator'. Did you mean 'await foreach'? // foreach (var i in new C()) Diagnostic(ErrorCode.ERR_ForEachMissingMemberWrongAsync, "new C()").WithArguments("C", "GetEnumerator").WithLocation(6, 27) ); } [Fact] public void TestPatternBased_GetEnumeratorWithoutCancellationToken() { string source = @" public class C { public static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() // no parameter => new Enumerator(); public sealed class Enumerator { public async System.Threading.Tasks.Task<bool> MoveNextAsync() { System.Console.Write(""MoveNextAsync""); await System.Threading.Tasks.Task.Yield(); return false; } public int Current => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync"); } [Fact] public void TestPatternBasedEnumerableWithAwaitForeach() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator<int> GetEnumerator() => throw null; public class Enumerator<T> { public T Current { get; } public bool MoveNext() => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,33): error CS8415: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetAsyncEnumerator'. Did you mean 'foreach' rather than 'await foreach'? // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMemberWrongAsync, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(6, 33) ); } [Fact] public void TestWithPattern() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() { throw null; } public int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("C.Enumerator C.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<System.Boolean> C.Enumerator.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 C.Enumerator.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Null(info.DisposeMethod); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); var memberModel = model.GetMemberModel(foreachSyntax); BoundForEachStatement boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.False(internalInfo.NeedsDisposal); } [Fact] public void TestWithPattern_Ref() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (ref var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,32): error CS8177: Async methods cannot have by-reference locals // await foreach (ref var i in new C()) Diagnostic(ErrorCode.ERR_BadAsyncLocalType, "i").WithLocation(6, 32)); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); Assert.Equal(default, model.GetForEachStatementInfo(foreachSyntax)); } [Fact] public void TestWithPattern_PointerType() { string source = @" unsafe class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int* Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (6,9): error CS4004: Cannot await in an unsafe context // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await").WithLocation(6, 9)); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); Assert.Equal(default, model.GetForEachStatementInfo(foreachSyntax)); } [Fact] public void TestWithPattern_InaccessibleGetAsyncEnumerator() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new D()) { } } } class D { private Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,33): error CS8411: Async foreach statement cannot operate on variables of type 'D' because 'D' does not contain a public definition for 'GetAsyncEnumerator' // await foreach (var i in new D()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new D()").WithArguments("D", "GetAsyncEnumerator").WithLocation(6, 33) ); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); Assert.Equal(default, model.GetForEachStatementInfo(foreachSyntax)); } [Fact] public void TestWithPattern_InaccessibleMoveNextAsync() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new D()) { } } } class D { public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { private System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,33): error CS0122: 'D.Enumerator.MoveNextAsync()' is inaccessible due to its protection level // await foreach (var i in new D()) Diagnostic(ErrorCode.ERR_BadAccess, "new D()").WithArguments("D.Enumerator.MoveNextAsync()").WithLocation(6, 33), // (6,33): error CS8412: Async foreach requires that the return type 'D.Enumerator' of 'D.GetAsyncEnumerator(System.Threading.CancellationToken)' must have a suitable public MoveNextAsync method and public Current property // await foreach (var i in new D()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new D()").WithArguments("D.Enumerator", "D.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33) ); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); Assert.Equal(default, model.GetForEachStatementInfo(foreachSyntax)); } [Fact] public void TestWithPattern_InaccessibleCurrent() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new D()) { } } } class D { public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; private int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,33): error CS0122: 'D.Enumerator.Current' is inaccessible due to its protection level // await foreach (var i in new D()) { } Diagnostic(ErrorCode.ERR_BadAccess, "new D()").WithArguments("D.Enumerator.Current").WithLocation(6, 33), // (6,33): error CS8412: Async foreach requires that the return type 'D.Enumerator' of 'D.GetAsyncEnumerator(System.Threading.CancellationToken)' must have a suitable public MoveNextAsync method and public Current property // await foreach (var i in new D()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new D()").WithArguments("D.Enumerator", "D.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(6, 33) ); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); Assert.Equal(default, model.GetForEachStatementInfo(foreachSyntax)); } [Fact] public void TestWithPattern_InaccessibleCurrentGetter() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new D()) { } } } class D { public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { private get => throw null; set => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (6,33): error CS8412: Async foreach requires that the return type 'D.Enumerator' of 'D.GetAsyncEnumerator()' must have a suitable public MoveNextAsync method and public Current property // await foreach (var i in new D()) { } Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new D()").WithArguments("D.Enumerator", "D.GetAsyncEnumerator()").WithLocation(6, 33) ); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); Assert.Equal(default, model.GetForEachStatementInfo(foreachSyntax)); } [Fact] public void TestWithPattern_RefStruct() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async System.Threading.Tasks.Task Main() { await foreach (var s in new C()) { Write($""{s.ToString()} ""); } Write(""Done""); } public Enumerator GetAsyncEnumerator() => new Enumerator(); public sealed class Enumerator : System.IAsyncDisposable { int i = 0; public int Current => i; public async Task<bool> MoveNextAsync() { i++; return await Task.FromResult(i < 3); } public async ValueTask DisposeAsync() { await Task.Yield(); } } } public ref struct S { int i; public S(int i) { this.i = i; } public override string ToString() => i.ToString(); } "; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2 Done"); } [Fact] public void TestWithPattern_RefReturningCurrent() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async System.Threading.Tasks.Task Main() { await foreach (var s in new C()) { Write($""{s.ToString()} ""); } Write(""Done""); } public Enumerator GetAsyncEnumerator() => new Enumerator(); public sealed class Enumerator { int i = 0; S current; public ref S Current { get { current = new S(i); return ref current; } } public async Task<bool> MoveNextAsync() { i++; return await Task.FromResult(i < 4); } } } public struct S { int i; public S(int i) { this.i = i; } public override string ToString() => i.ToString(); } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1 2 3 Done", verify: Verification.Fails); } [Fact] public void TestWithPattern_IterationVariableIsReadOnly() { string source = @" class C { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { i = 1; } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public sealed class Enumerator { public System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics( // (8,13): error CS1656: Cannot assign to 'i' because it is a 'foreach iteration variable' // i = 1; Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "i").WithArguments("i", "foreach iteration variable").WithLocation(8, 13) ); } [Fact] public void TestWithPattern_WithStruct_MoveNextAsyncReturnsTask() { string source = @" using static System.Console; using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } Write($""Done""); } public AsyncEnumerator GetAsyncEnumerator() { return new AsyncEnumerator(0); } public struct AsyncEnumerator { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get { Write($""Current({i}) ""); i++; return i; } } public async Task<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); bool more = await Task.FromResult(i < 4); i = i + 100; // Note: side-effects of async methods in structs are lost return more; } public async ValueTask DisposeAsync() { Write($""DisposeAsync ""); await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(0) Got(1) NextAsync(1) Current(1) Got(2) NextAsync(2) Current(2) Got(3) NextAsync(3) Current(3) Got(4) NextAsync(4) DisposeAsync Done"); } [Fact] public void TestWithPattern_MoveNextAsyncReturnsValueTask() { string source = @" using static System.Console; using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } Write($""Done""); } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new AsyncEnumerator(0); } public class AsyncEnumerator : System.IAsyncDisposable { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public async ValueTask DisposeAsync() { Write($""Dispose({i}) ""); await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Current(3) Got(3) NextAsync(3) Dispose(4) Done"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("System.Threading.Tasks.ValueTask<System.Boolean> C.AsyncEnumerator.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); } [Fact] [WorkItem(31609, "https://github.com/dotnet/roslyn/issues/31609")] public void TestWithPattern_MoveNextAsyncReturnsAwaitable() { string source = @" using static System.Console; using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { Write($""Item({i}) ""); break; } Write($""Done""); } public AsyncEnumerator GetAsyncEnumerator() { return new AsyncEnumerator(); } public class AsyncEnumerator : System.IAsyncDisposable { public int Current => 1; public Awaitable MoveNextAsync() { return new Awaitable(); } public async ValueTask DisposeAsync() { Write(""Dispose ""); await Task.Yield(); } } public class Awaitable { public Awaiter GetAwaiter() { return new Awaiter(); } } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public bool IsCompleted { get { return true; } } public bool GetResult() { return true; } public void OnCompleted(System.Action continuation) { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Item(1) Dispose Done"); var tree = comp.SyntaxTrees.First(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("C.Awaitable C.AsyncEnumerator.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); } [Fact] [WorkItem(31609, "https://github.com/dotnet/roslyn/issues/31609")] public void TestWithPattern_MoveNextAsyncReturnsAwaitable_WithoutGetAwaiter() { string source = @" using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { } } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public class AsyncEnumerator : System.IAsyncDisposable { public int Current => 1; public Awaitable MoveNextAsync() => throw null; public ValueTask DisposeAsync() => throw null; } public class Awaitable { } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,33): error CS1061: 'C.Awaitable' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'C.Awaitable' could be found (are you missing a using directive or an assembly reference?) // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C()").WithArguments("C.Awaitable", "GetAwaiter").WithLocation(7, 33) ); VerifyEmptyForEachStatementInfo(comp); } [Fact] [WorkItem(31609, "https://github.com/dotnet/roslyn/issues/31609")] public void TestWithPattern_MoveNextAsyncReturnsAwaitable_WithoutIsCompleted() { string source = @" using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { } } public AsyncEnumerator GetAsyncEnumerator() => throw null; public class AsyncEnumerator : System.IAsyncDisposable { public int Current => 1; public Awaitable MoveNextAsync() => throw null; public ValueTask DisposeAsync() => throw null; } public class Awaitable { public Awaiter GetAwaiter() => throw null; } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public bool GetResult() { return true; } public void OnCompleted(System.Action continuation) { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,33): error CS0117: 'C.Awaiter' does not contain a definition for 'IsCompleted' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Awaiter", "IsCompleted").WithLocation(7, 33) ); VerifyEmptyForEachStatementInfo(comp); } private static void VerifyEmptyForEachStatementInfo(CSharpCompilation comp) { var tree = comp.SyntaxTrees.First(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Null(info.MoveNextMethod); Assert.Null(info.ElementType); } [Fact] [WorkItem(31609, "https://github.com/dotnet/roslyn/issues/31609")] public void TestWithPattern_MoveNextAsyncReturnsAwaitable_WithoutGetResult() { string source = @" using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { } } public AsyncEnumerator GetAsyncEnumerator() => throw null; public class AsyncEnumerator : System.IAsyncDisposable { public int Current => 1; public Awaitable MoveNextAsync() => throw null; public ValueTask DisposeAsync() => throw null; } public class Awaitable { public Awaiter GetAwaiter() => throw null; } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public bool IsCompleted { get { return true; } } public void OnCompleted(System.Action continuation) { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,33): error CS1061: 'C.Awaiter' does not contain a definition for 'GetResult' and no accessible extension method 'GetResult' accepting a first argument of type 'C.Awaiter' could be found (are you missing a using directive or an assembly reference?) // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C()").WithArguments("C.Awaiter", "GetResult").WithLocation(7, 33) ); VerifyEmptyForEachStatementInfo(comp); } [Fact] [WorkItem(31609, "https://github.com/dotnet/roslyn/issues/31609")] public void TestWithPattern_MoveNextAsyncReturnsAwaitable_WithoutOnCompleted() { string source = @" using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { } } public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; public class AsyncEnumerator : System.IAsyncDisposable { public int Current => 1; public Awaitable MoveNextAsync() => throw null; public ValueTask DisposeAsync() => throw null; } public class Awaitable { public Awaiter GetAwaiter() => throw null; } public class Awaiter { public bool IsCompleted { get { return true; } } public bool GetResult() { return true; } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,33): error CS4027: 'C.Awaiter' does not implement 'INotifyCompletion' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "new C()").WithArguments("C.Awaiter", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(7, 33) ); VerifyEmptyForEachStatementInfo(comp); } [Fact] public void TestWithPattern_MoveNextAsyncReturnsBadType() { string source = @" using System.Threading.Tasks; class C { static async Task Main() { await foreach (var i in new C()) { } } public AsyncEnumerator GetAsyncEnumerator() => throw null; public class AsyncEnumerator { public int Current => throw null; public int MoveNextAsync() => throw null; public ValueTask DisposeAsync() => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics( // (7,33): error CS1061: 'int' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C()").WithArguments("int", "GetAwaiter").WithLocation(7, 33) ); var tree = comp.SyntaxTrees.First(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Null(info.MoveNextMethod); Assert.Null(info.ElementType); } [Fact] public void TestWithPattern_WithUnsealed() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } } public Enumerator GetAsyncEnumerator() { return new Enumerator(); } public class Enumerator { int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async Task<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var memberModel = model.GetMemberModel(foreachSyntax); BoundForEachStatement boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Current(3) Got(3) NextAsync(3) Dispose(4)"); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void TestWithPattern_WithUnsealed_WithIAsyncDisposable() { string source = @" using static System.Console; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } } public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new DerivedEnumerator(); } public class Enumerator { protected int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async Task<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } } public class DerivedEnumerator : Enumerator, System.IAsyncDisposable { public ValueTask DisposeAsync() => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.False(internalInfo.NeedsDisposal); var verifier = CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Current(3) Got(3) NextAsync(3)"); verifier.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 262 (0x106) .maxstack 3 .locals init (int V_0, System.Threading.CancellationToken V_1, System.Runtime.CompilerServices.TaskAwaiter<bool> V_2, C.<Main>d__0 V_3, System.Exception V_4) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Main>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: <hidden> IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_0011 IL_000c: br IL_009a // sequence point: { IL_0011: nop // sequence point: await foreach IL_0012: nop // sequence point: new C() IL_0013: ldarg.0 IL_0014: newobj ""C..ctor()"" IL_0019: ldloca.s V_1 IL_001b: initobj ""System.Threading.CancellationToken"" IL_0021: ldloc.1 IL_0022: call ""C.Enumerator C.GetAsyncEnumerator(System.Threading.CancellationToken)"" IL_0027: stfld ""C.Enumerator C.<Main>d__0.<>s__1"" // sequence point: <hidden> IL_002c: br.s IL_005c // sequence point: var i IL_002e: ldarg.0 IL_002f: ldarg.0 IL_0030: ldfld ""C.Enumerator C.<Main>d__0.<>s__1"" IL_0035: callvirt ""int C.Enumerator.Current.get"" IL_003a: stfld ""int C.<Main>d__0.<i>5__2"" // sequence point: { IL_003f: nop // sequence point: Write($""Got({i}) ""); IL_0040: ldstr ""Got({0}) "" IL_0045: ldarg.0 IL_0046: ldfld ""int C.<Main>d__0.<i>5__2"" IL_004b: box ""int"" IL_0050: call ""string string.Format(string, object)"" IL_0055: call ""void System.Console.Write(string)"" IL_005a: nop // sequence point: } IL_005b: nop // sequence point: in IL_005c: ldarg.0 IL_005d: ldfld ""C.Enumerator C.<Main>d__0.<>s__1"" IL_0062: callvirt ""System.Threading.Tasks.Task<bool> C.Enumerator.MoveNextAsync()"" IL_0067: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<bool> System.Threading.Tasks.Task<bool>.GetAwaiter()"" IL_006c: stloc.2 // sequence point: <hidden> IL_006d: ldloca.s V_2 IL_006f: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.IsCompleted.get"" IL_0074: brtrue.s IL_00b6 IL_0076: ldarg.0 IL_0077: ldc.i4.0 IL_0078: dup IL_0079: stloc.0 IL_007a: stfld ""int C.<Main>d__0.<>1__state"" // async: yield IL_007f: ldarg.0 IL_0080: ldloc.2 IL_0081: stfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_0086: ldarg.0 IL_0087: stloc.3 IL_0088: ldarg.0 IL_0089: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_008e: ldloca.s V_2 IL_0090: ldloca.s V_3 IL_0092: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<bool>, C.<Main>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<bool>, ref C.<Main>d__0)"" IL_0097: nop IL_0098: leave.s IL_0105 // async: resume IL_009a: ldarg.0 IL_009b: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_00a0: stloc.2 IL_00a1: ldarg.0 IL_00a2: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_00a7: initobj ""System.Runtime.CompilerServices.TaskAwaiter<bool>"" IL_00ad: ldarg.0 IL_00ae: ldc.i4.m1 IL_00af: dup IL_00b0: stloc.0 IL_00b1: stfld ""int C.<Main>d__0.<>1__state"" IL_00b6: ldarg.0 IL_00b7: ldloca.s V_2 IL_00b9: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.GetResult()"" IL_00be: stfld ""bool C.<Main>d__0.<>s__3"" IL_00c3: ldarg.0 IL_00c4: ldfld ""bool C.<Main>d__0.<>s__3"" IL_00c9: brtrue IL_002e IL_00ce: ldarg.0 IL_00cf: ldnull IL_00d0: stfld ""C.Enumerator C.<Main>d__0.<>s__1"" IL_00d5: leave.s IL_00f1 } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_00d7: stloc.s V_4 IL_00d9: ldarg.0 IL_00da: ldc.i4.s -2 IL_00dc: stfld ""int C.<Main>d__0.<>1__state"" IL_00e1: ldarg.0 IL_00e2: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_00e7: ldloc.s V_4 IL_00e9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00ee: nop IL_00ef: leave.s IL_0105 } // sequence point: } IL_00f1: ldarg.0 IL_00f2: ldc.i4.s -2 IL_00f4: stfld ""int C.<Main>d__0.<>1__state"" // sequence point: <hidden> IL_00f9: ldarg.0 IL_00fa: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_00ff: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_0104: nop IL_0105: ret }", sequencePoints: "C+<Main>d__0.MoveNext", source: source + s_IAsyncEnumerable); } [Fact] public void TestWithPattern_WithIAsyncDisposable() { string source = @" using static System.Console; using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } } public Enumerator GetAsyncEnumerator() { return new Enumerator(); } public sealed class Enumerator : System.IAsyncDisposable { int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async Task<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var memberModel = model.GetMemberModel(foreachSyntax); BoundForEachStatement boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Current(3) Got(3) NextAsync(3) Dispose(4)"); } [Fact] public void TestWithPattern_WithIAsyncDisposableUseSiteError() { string enumerator = @" using System.Threading.Tasks; public class C { public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator : System.IAsyncDisposable { public int Current { get => throw null; } public Task<bool> MoveNextAsync() => throw null; public async ValueTask DisposeAsync() { await Task.Yield(); } } }"; string source = @" using System.Threading.Tasks; class Client { async Task M() { await foreach (var i in new C()) { } } }"; var lib = CreateCompilationWithTasksExtensions(enumerator + s_IAsyncEnumerable); lib.VerifyDiagnostics(); var comp = CreateCompilationWithTasksExtensions(source, references: new[] { lib.EmitToImageReference() }); comp.MakeTypeMissing(WellKnownType.System_IAsyncDisposable); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); } [Fact] public void TestWithMultipleInterface() { string source = @" using System.Collections.Generic; class C : IAsyncEnumerable<int>, IAsyncEnumerable<string> { async System.Threading.Tasks.Task M() { await foreach (var i in new C()) { } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { throw null; } IAsyncEnumerator<string> IAsyncEnumerable<string>.GetAsyncEnumerator(System.Threading.CancellationToken token) { throw null; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (7,33): error CS8413: Async foreach statement cannot operate on variables of type 'C' because it implements multiple instantiations of 'IAsyncEnumerable<T>'; try casting to a specific interface instantiation // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_MultipleIAsyncEnumOfT, "new C()").WithArguments("C", "System.Collections.Generic.IAsyncEnumerable<T>").WithLocation(7, 33) ); } [Fact] public void TestWithMultipleImplementations() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class Base : IAsyncEnumerable<string> { IAsyncEnumerator<string> IAsyncEnumerable<string>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; } class C : Base, IAsyncEnumerable<int> { async Task M() { await foreach (var i in new C()) { } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (13,33): error CS8413: Async foreach statement cannot operate on variables of type 'C' because it implements multiple instantiations of 'IAsyncEnumerable<T>'; try casting to a specific interface instantiation // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_MultipleIAsyncEnumOfT, "new C()").WithArguments("C", "System.Collections.Generic.IAsyncEnumerable<T>").WithLocation(13, 33) ); } [Fact] public void TestWithInterface() { string source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; using static System.Console; class C : IAsyncEnumerable<int> { static async Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } sealed class AsyncEnumerator : IAsyncEnumerator<int> { int i = 0; int IAsyncEnumerator<int>.Current { get { Write($""Current({i}) ""); return i; } } async ValueTask<bool> IAsyncEnumerator<int>.MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } async ValueTask IAsyncDisposable.DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Current(3) Got(3) NextAsync(3) Dispose(4)"); var tree = comp.SyntaxTrees.First(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("System.Collections.Generic.IAsyncEnumerator<System.Int32> System.Collections.Generic.IAsyncEnumerable<System.Int32>.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask<System.Boolean> System.Collections.Generic.IAsyncEnumerator<System.Int32>.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 System.Collections.Generic.IAsyncEnumerator<System.Int32>.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()", info.DisposeMethod.ToTestDisplayString()); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); } [Fact] public void TestWithInterface_OnStruct_ImplicitInterfaceImplementation() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; struct C : IAsyncEnumerable<int> { static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } class AsyncEnumerator : IAsyncEnumerator<int> { public int i; public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; // Note: the enumerator type should not be a struct, otherwise you will loop forever var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Current(3) Got(3) NextAsync(3) Dispose(4)"); // The thing to notice here is that the call to GetAsyncEnumerator is a constrained call (we're not boxing to `IAsyncEnumerable<int>`) verifier.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 496 (0x1f0) .maxstack 3 .locals init (int V_0, C V_1, System.Threading.CancellationToken V_2, System.Runtime.CompilerServices.ValueTaskAwaiter<bool> V_3, System.Threading.Tasks.ValueTask<bool> V_4, C.<Main>d__0 V_5, object V_6, System.Runtime.CompilerServices.ValueTaskAwaiter V_7, System.Threading.Tasks.ValueTask V_8, System.Exception V_9) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Main>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0019 IL_0012: br.s IL_004c IL_0014: br IL_015c IL_0019: nop IL_001a: nop IL_001b: ldarg.0 IL_001c: ldloca.s V_1 IL_001e: dup IL_001f: initobj ""C"" IL_0025: ldloca.s V_2 IL_0027: initobj ""System.Threading.CancellationToken"" IL_002d: ldloc.2 IL_002e: constrained. ""C"" IL_0034: callvirt ""System.Collections.Generic.IAsyncEnumerator<int> System.Collections.Generic.IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken)"" IL_0039: stfld ""System.Collections.Generic.IAsyncEnumerator<int> C.<Main>d__0.<>s__1"" IL_003e: ldarg.0 IL_003f: ldnull IL_0040: stfld ""object C.<Main>d__0.<>s__2"" IL_0045: ldarg.0 IL_0046: ldc.i4.0 IL_0047: stfld ""int C.<Main>d__0.<>s__3"" IL_004c: nop .try { IL_004d: ldloc.0 IL_004e: brfalse.s IL_0052 IL_0050: br.s IL_0054 IL_0052: br.s IL_00ca IL_0054: br.s IL_0084 IL_0056: ldarg.0 IL_0057: ldarg.0 IL_0058: ldfld ""System.Collections.Generic.IAsyncEnumerator<int> C.<Main>d__0.<>s__1"" IL_005d: callvirt ""int System.Collections.Generic.IAsyncEnumerator<int>.Current.get"" IL_0062: stfld ""int C.<Main>d__0.<i>5__4"" IL_0067: nop IL_0068: ldstr ""Got({0}) "" IL_006d: ldarg.0 IL_006e: ldfld ""int C.<Main>d__0.<i>5__4"" IL_0073: box ""int"" IL_0078: call ""string string.Format(string, object)"" IL_007d: call ""void System.Console.Write(string)"" IL_0082: nop IL_0083: nop IL_0084: ldarg.0 IL_0085: ldfld ""System.Collections.Generic.IAsyncEnumerator<int> C.<Main>d__0.<>s__1"" IL_008a: callvirt ""System.Threading.Tasks.ValueTask<bool> System.Collections.Generic.IAsyncEnumerator<int>.MoveNextAsync()"" IL_008f: stloc.s V_4 IL_0091: ldloca.s V_4 IL_0093: call ""System.Runtime.CompilerServices.ValueTaskAwaiter<bool> System.Threading.Tasks.ValueTask<bool>.GetAwaiter()"" IL_0098: stloc.3 IL_0099: ldloca.s V_3 IL_009b: call ""bool System.Runtime.CompilerServices.ValueTaskAwaiter<bool>.IsCompleted.get"" IL_00a0: brtrue.s IL_00e6 IL_00a2: ldarg.0 IL_00a3: ldc.i4.0 IL_00a4: dup IL_00a5: stloc.0 IL_00a6: stfld ""int C.<Main>d__0.<>1__state"" IL_00ab: ldarg.0 IL_00ac: ldloc.3 IL_00ad: stfld ""System.Runtime.CompilerServices.ValueTaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_00b2: ldarg.0 IL_00b3: stloc.s V_5 IL_00b5: ldarg.0 IL_00b6: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_00bb: ldloca.s V_3 IL_00bd: ldloca.s V_5 IL_00bf: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ValueTaskAwaiter<bool>, C.<Main>d__0>(ref System.Runtime.CompilerServices.ValueTaskAwaiter<bool>, ref C.<Main>d__0)"" IL_00c4: nop IL_00c5: leave IL_01ef IL_00ca: ldarg.0 IL_00cb: ldfld ""System.Runtime.CompilerServices.ValueTaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_00d0: stloc.3 IL_00d1: ldarg.0 IL_00d2: ldflda ""System.Runtime.CompilerServices.ValueTaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_00d7: initobj ""System.Runtime.CompilerServices.ValueTaskAwaiter<bool>"" IL_00dd: ldarg.0 IL_00de: ldc.i4.m1 IL_00df: dup IL_00e0: stloc.0 IL_00e1: stfld ""int C.<Main>d__0.<>1__state"" IL_00e6: ldarg.0 IL_00e7: ldloca.s V_3 IL_00e9: call ""bool System.Runtime.CompilerServices.ValueTaskAwaiter<bool>.GetResult()"" IL_00ee: stfld ""bool C.<Main>d__0.<>s__5"" IL_00f3: ldarg.0 IL_00f4: ldfld ""bool C.<Main>d__0.<>s__5"" IL_00f9: brtrue IL_0056 IL_00fe: leave.s IL_010c } catch object { IL_0100: stloc.s V_6 IL_0102: ldarg.0 IL_0103: ldloc.s V_6 IL_0105: stfld ""object C.<Main>d__0.<>s__2"" IL_010a: leave.s IL_010c } IL_010c: ldarg.0 IL_010d: ldfld ""System.Collections.Generic.IAsyncEnumerator<int> C.<Main>d__0.<>s__1"" IL_0112: brfalse.s IL_0181 IL_0114: ldarg.0 IL_0115: ldfld ""System.Collections.Generic.IAsyncEnumerator<int> C.<Main>d__0.<>s__1"" IL_011a: callvirt ""System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()"" IL_011f: stloc.s V_8 IL_0121: ldloca.s V_8 IL_0123: call ""System.Runtime.CompilerServices.ValueTaskAwaiter System.Threading.Tasks.ValueTask.GetAwaiter()"" IL_0128: stloc.s V_7 IL_012a: ldloca.s V_7 IL_012c: call ""bool System.Runtime.CompilerServices.ValueTaskAwaiter.IsCompleted.get"" IL_0131: brtrue.s IL_0179 IL_0133: ldarg.0 IL_0134: ldc.i4.1 IL_0135: dup IL_0136: stloc.0 IL_0137: stfld ""int C.<Main>d__0.<>1__state"" IL_013c: ldarg.0 IL_013d: ldloc.s V_7 IL_013f: stfld ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__2"" IL_0144: ldarg.0 IL_0145: stloc.s V_5 IL_0147: ldarg.0 IL_0148: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_014d: ldloca.s V_7 IL_014f: ldloca.s V_5 IL_0151: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ValueTaskAwaiter, C.<Main>d__0>(ref System.Runtime.CompilerServices.ValueTaskAwaiter, ref C.<Main>d__0)"" IL_0156: nop IL_0157: leave IL_01ef IL_015c: ldarg.0 IL_015d: ldfld ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__2"" IL_0162: stloc.s V_7 IL_0164: ldarg.0 IL_0165: ldflda ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__2"" IL_016a: initobj ""System.Runtime.CompilerServices.ValueTaskAwaiter"" IL_0170: ldarg.0 IL_0171: ldc.i4.m1 IL_0172: dup IL_0173: stloc.0 IL_0174: stfld ""int C.<Main>d__0.<>1__state"" IL_0179: ldloca.s V_7 IL_017b: call ""void System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()"" IL_0180: nop IL_0181: ldarg.0 IL_0182: ldfld ""object C.<Main>d__0.<>s__2"" IL_0187: stloc.s V_6 IL_0189: ldloc.s V_6 IL_018b: brfalse.s IL_01aa IL_018d: ldloc.s V_6 IL_018f: isinst ""System.Exception"" IL_0194: stloc.s V_9 IL_0196: ldloc.s V_9 IL_0198: brtrue.s IL_019d IL_019a: ldloc.s V_6 IL_019c: throw IL_019d: ldloc.s V_9 IL_019f: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)"" IL_01a4: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()"" IL_01a9: nop IL_01aa: ldarg.0 IL_01ab: ldfld ""int C.<Main>d__0.<>s__3"" IL_01b0: pop IL_01b1: ldarg.0 IL_01b2: ldnull IL_01b3: stfld ""object C.<Main>d__0.<>s__2"" IL_01b8: ldarg.0 IL_01b9: ldnull IL_01ba: stfld ""System.Collections.Generic.IAsyncEnumerator<int> C.<Main>d__0.<>s__1"" IL_01bf: leave.s IL_01db } catch System.Exception { IL_01c1: stloc.s V_9 IL_01c3: ldarg.0 IL_01c4: ldc.i4.s -2 IL_01c6: stfld ""int C.<Main>d__0.<>1__state"" IL_01cb: ldarg.0 IL_01cc: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_01d1: ldloc.s V_9 IL_01d3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_01d8: nop IL_01d9: leave.s IL_01ef } IL_01db: ldarg.0 IL_01dc: ldc.i4.s -2 IL_01de: stfld ""int C.<Main>d__0.<>1__state"" IL_01e3: ldarg.0 IL_01e4: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_01e9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_01ee: nop IL_01ef: ret }"); } [Fact] public void TestWithInterface_WithEarlyCompletion1() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } Write($""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(2); } internal sealed class AsyncEnumerator : IAsyncEnumerator<int> { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public ValueTask DisposeAsync() { Write($""Dispose({i}) ""); return new ValueTask(Task.CompletedTask); // return a completed task } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(2) Current(3) Got(3) NextAsync(3) Dispose(4) Done"); } [Fact] public void TestWithInterface_WithBreakAndContinue() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { if (i == 2 || i == 3) { Write($""Continue({i}) ""); continue; } if (i == 4) { Write(""Break ""); break; } Write($""Got({i}) ""); } Write(""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } sealed class AsyncEnumerator : IAsyncEnumerator<int> { int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 10); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Continue(2) NextAsync(2) Current(3) Continue(3) NextAsync(3) Current(4) Break Dispose(4) Done"); } [Fact] public void TestWithInterface_WithGoto() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { if (i == 2 || i == 3) { Write($""Continue({i}) ""); continue; } if (i == 4) { Write(""Goto ""); goto done; } Write($""Got({i}) ""); } done: Write(""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } sealed class AsyncEnumerator : IAsyncEnumerator<int> { int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 10); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Continue(2) NextAsync(2) Current(3) Continue(3) NextAsync(3) Current(4) Goto Dispose(4) Done"); } [Fact] public void TestWithInterface_WithStruct() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { static async Task Main() { await foreach (var i in new C()) { Write($""Got({i}) ""); } Write($""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(0); } internal struct AsyncEnumerator : IAsyncEnumerator<int> { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get { Write($""Current({i}) ""); i++; return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); bool more = await Task.FromResult(i < 4); i = i + 100; // Note: side-effects of async methods in structs are lost return more; } public async ValueTask DisposeAsync() { Write($""Dispose({i}) ""); await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(0) Got(1) NextAsync(1) Current(1) Got(2) NextAsync(2) Current(2) Got(3) NextAsync(3) Current(3) Got(4) NextAsync(4) Dispose(4) Done"); } [Fact, WorkItem(27651, "https://github.com/dotnet/roslyn/issues/27651")] public void TestControlFlowAnalysis() { string source = @" class C { async System.Threading.Tasks.Task M(System.Collections.Generic.IAsyncEnumerable<int> collection) { await foreach (var item in collection) { } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var loop = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var ctrlFlowAnalysis = model.AnalyzeControlFlow(loop); Assert.Equal(0, ctrlFlowAnalysis.ExitPoints.Count()); } [Fact] public void TestWithNullLiteralCollection() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { async Task M() { await foreach (var i in null) { } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { throw null; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (8,33): error CS0186: Use of null is not valid in this context // await foreach (var i in null) Diagnostic(ErrorCode.ERR_NullNotValid, "null").WithLocation(8, 33) ); } [Fact] public void TestWithNullCollection() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task Main() { C c = null; try { await foreach (var i in c) { } } catch (System.NullReferenceException) { System.Console.Write(""Success""); } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(0); } internal struct AsyncEnumerator : IAsyncEnumerator<int> { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get => throw new System.Exception(); } public ValueTask<bool> MoveNextAsync() => throw new System.Exception(); public ValueTask DisposeAsync() => throw new System.Exception(); } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Success"); } [Fact] public void TestInCatch() { string source = @" using System.Collections.Generic; using static System.Console; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task Main() { try { Write($""Try ""); throw null; } catch (System.NullReferenceException) { await foreach (var i in new C()) { Write($""Got({i}) ""); } } Write($""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(0); } internal class AsyncEnumerator : IAsyncEnumerator<int> { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Try NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Current(3) Got(3) NextAsync(3) Dispose(4) Done"); } /// Covered in greater details by <see cref="CodeGenAsyncIteratorTests.TryFinally_AwaitForeachInFinally"/> [Fact] public void TestInFinally() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task Main() { try { } finally { await foreach (var i in new C()) { } } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { throw null; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics(); } [Fact] public void TestWithConversionToElement() { string source = @" using System.Collections.Generic; using static System.Console; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task Main() { await foreach (Element i in new C()) { Write($""Got({i}) ""); } Write($""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(0); } internal class AsyncEnumerator : IAsyncEnumerator<int> { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 3); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } } class Element { int i; public static implicit operator Element(int value) { Write($""Convert({value}) ""); return new Element(value); } private Element(int value) { i = value; } public override string ToString() => i.ToString(); }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Convert(1) Got(1) NextAsync(1) Current(2) Convert(2) Got(2) NextAsync(2) Dispose(3) Done"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("System.Collections.Generic.IAsyncEnumerator<System.Int32> System.Collections.Generic.IAsyncEnumerable<System.Int32>.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask<System.Boolean> System.Collections.Generic.IAsyncEnumerator<System.Int32>.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 System.Collections.Generic.IAsyncEnumerator<System.Int32>.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()", info.DisposeMethod.ToTestDisplayString()); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitUserDefined, info.ElementConversion.Kind); Assert.Equal("Element Element.op_Implicit(System.Int32 value)", info.ElementConversion.MethodSymbol.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); } [Fact] public void TestWithNullableCollection() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; struct C : IAsyncEnumerable<int> { static async System.Threading.Tasks.Task Main() { C? c = new C(); // non-null value await foreach (var i in c) { Write($""Got({i}) ""); } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } sealed class AsyncEnumerator : IAsyncEnumerator<int> { int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 3); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1) NextAsync(1) Current(2) Got(2) NextAsync(2) Dispose(3)"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("System.Collections.Generic.IAsyncEnumerator<System.Int32> System.Collections.Generic.IAsyncEnumerable<System.Int32>.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask<System.Boolean> System.Collections.Generic.IAsyncEnumerator<System.Int32>.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 System.Collections.Generic.IAsyncEnumerator<System.Int32>.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()", info.DisposeMethod.ToTestDisplayString()); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); } [Fact] public void TestWithNullableCollection2() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; struct C : IAsyncEnumerable<int> { static async Task Main() { C? c = null; // null value try { await foreach (var i in c) { Write($""UNREACHABLE""); } } catch (System.InvalidOperationException) { Write($""Success""); } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { throw new System.Exception(); } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Success"); } [Fact] public void TestWithInterfaceAndDeconstruction() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { static async System.Threading.Tasks.Task Main() { await foreach (var (i, j) in new C()) { Write($""Got({i},{j}) ""); } Write($""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } sealed class AsyncEnumerator : IAsyncEnumerator<int> { int i = 0; public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 3); } public async ValueTask DisposeAsync() { Write($""Dispose({i}) ""); await Task.Yield(); } } } public static class Extensions { public static void Deconstruct(this int i, out string x1, out int x2) { Write($""Deconstruct({i}) ""); x1 = i.ToString(); x2 = -i; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Deconstruct(1) Got(1,-1) NextAsync(1) Current(2) Deconstruct(2) Got(2,-2) NextAsync(2) Dispose(3) Done"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("System.Collections.Generic.IAsyncEnumerator<System.Int32> System.Collections.Generic.IAsyncEnumerable<System.Int32>.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask<System.Boolean> System.Collections.Generic.IAsyncEnumerator<System.Int32>.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 System.Collections.Generic.IAsyncEnumerator<System.Int32>.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()", info.DisposeMethod.ToTestDisplayString()); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); } [Fact] public void TestWithDeconstructionInNonAsyncMethod() { string source = @" using System.Collections.Generic; class C : IAsyncEnumerable<int> { static void Main() { await foreach (var (i, j) in new C()) { } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; } public static class Extensions { public static void Deconstruct(this int i, out int x1, out int x2) { x1 = i; x2 = -i; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (7,9): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // await foreach (var (i, j) in new C()) Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(7, 9) ); } [Fact] public void TestWithPatternAndDeconstructionOfTuple() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<(string, int)> { public static async System.Threading.Tasks.Task Main() { await foreach (var (i, j) in new C()) { Write($""Got({i},{j}) ""); } Write($""Done""); } IAsyncEnumerator<(string, int)> IAsyncEnumerable<(string, int)>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } sealed class AsyncEnumerator : IAsyncEnumerator<(string, int)> { int i = 0; public (string, int) Current { get { Write($""Current({i}) ""); return (i.ToString(), -i); } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 3); } public async ValueTask DisposeAsync() { Write($""Dispose({i}) ""); await Task.Yield(); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1,-1) NextAsync(1) Current(2) Got(2,-2) NextAsync(2) Dispose(3) Done"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("System.Collections.Generic.IAsyncEnumerator<(System.String, System.Int32)> System.Collections.Generic.IAsyncEnumerable<(System.String, System.Int32)>.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask<System.Boolean> System.Collections.Generic.IAsyncEnumerator<(System.String, System.Int32)>.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("(System.String, System.Int32) System.Collections.Generic.IAsyncEnumerator<(System.String, System.Int32)>.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()", info.DisposeMethod.ToTestDisplayString()); Assert.Equal("(System.String, System.Int32)", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); } [Fact] public void TestWithInterfaceAndDeconstruction_ManualIteration() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { static async Task Main() { var e = ((IAsyncEnumerable<int>)new C()).GetAsyncEnumerator(); try { while (await e.MoveNextAsync()) { (int i, int j) = e.Current; Write($""Got({i},{j}) ""); } } finally { await e.DisposeAsync(); } Write($""Done""); } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(0); } internal class AsyncEnumerator : IAsyncEnumerator<int> { int i; internal AsyncEnumerator(int start) { i = start; } public int Current { get { Write($""Current({i}) ""); return i; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 3); } public async ValueTask DisposeAsync() { Write($""Disp""); await Task.Yield(); Write($""ose({i}) ""); } } } public static class Extensions { public static void Deconstruct(this int i, out int x1, out int x2) { x1 = i; x2 = -i; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got(1,-1) NextAsync(1) Current(2) Got(2,-2) NextAsync(2) Dispose(3) Done"); } [Fact] public void TestWithPatternAndObsolete() { string source = @" using System.Threading.Tasks; class C { static async System.Threading.Tasks.Task Main() { await foreach (var i in new C()) { } } [System.Obsolete] public AsyncEnumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } [System.Obsolete] public sealed class AsyncEnumerator : System.IAsyncDisposable { [System.Obsolete] public int Current { get => throw null; } [System.Obsolete] public Task<bool> MoveNextAsync() => throw null; [System.Obsolete] public ValueTask DisposeAsync() => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,15): warning CS0612: 'C.GetAsyncEnumerator(CancellationToken)' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.GetAsyncEnumerator(System.Threading.CancellationToken)").WithLocation(7, 15), // (7,15): warning CS0612: 'C.AsyncEnumerator.MoveNextAsync()' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.AsyncEnumerator.MoveNextAsync()").WithLocation(7, 15), // (7,15): warning CS0612: 'C.AsyncEnumerator.Current' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.AsyncEnumerator.Current").WithLocation(7, 15) ); // Note: Obsolete on DisposeAsync is not reported since always called through IAsyncDisposable interface } [Fact] public void TestWithUnassignedCollection() { string source = @" using System.Collections.Generic; class C { async System.Threading.Tasks.Task M() { C c; await foreach (var i in c) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token = default) => throw null; }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (8,33): error CS0165: Use of unassigned local variable 'c' // await foreach (var i in c) Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c").WithLocation(8, 33) ); } [Fact] public void TestInRegularForeach() { string source = @" using System.Collections.Generic; class C { void M() { foreach (var i in new C()) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token = default) { throw null; } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable); comp.VerifyDiagnostics( // (7,27): error CS8414: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator'. Did you mean 'await foreach'? // foreach (var i in new C()) Diagnostic(ErrorCode.ERR_ForEachMissingMemberWrongAsync, "new C()").WithArguments("C", "GetEnumerator").WithLocation(7, 27) ); } [Fact] public void TestWithGenericCollection() { string source = @" using static System.Console; using System.Collections.Generic; using System.Threading.Tasks; class Collection<T> : IAsyncEnumerable<T> { IAsyncEnumerator<T> IAsyncEnumerable<T>.GetAsyncEnumerator(System.Threading.CancellationToken token) { return new AsyncEnumerator(); } sealed class AsyncEnumerator : IAsyncEnumerator<T> { int i = 0; public T Current { get { Write($""Current({i}) ""); return default; } } public async ValueTask<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public async ValueTask DisposeAsync() { Write($""Dispose({i}) ""); await Task.Yield(); } } } class C { static async System.Threading.Tasks.Task Main() { await foreach (var i in new Collection<int>()) { Write($""Got ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got NextAsync(1) Current(2) Got NextAsync(2) Current(3) Got NextAsync(3) Dispose(4)"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("System.Collections.Generic.IAsyncEnumerator<System.Int32> System.Collections.Generic.IAsyncEnumerable<System.Int32>.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask<System.Boolean> System.Collections.Generic.IAsyncEnumerator<System.Int32>.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 System.Collections.Generic.IAsyncEnumerator<System.Int32>.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()", info.DisposeMethod.ToTestDisplayString()); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.True(internalInfo.NeedsDisposal); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void TestWithInterfaceImplementingPattern() { string source = @" using static System.Console; using System.Threading.Tasks; public interface ICollection<T> { IMyAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default); } public interface IMyAsyncEnumerator<T> { T Current { get; } Task<bool> MoveNextAsync(); } public class Collection<T> : ICollection<T> { public IMyAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new MyAsyncEnumerator<T>(); } } public sealed class MyAsyncEnumerator<T> : IMyAsyncEnumerator<T> { int i = 0; public T Current { get { Write($""Current({i}) ""); return default; } } public async Task<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } } class C { static async System.Threading.Tasks.Task Main() { ICollection<int> c = new Collection<int>(); await foreach (var i in c) { Write($""Got ""); } } }"; var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got NextAsync(1) Current(2) Got NextAsync(2) Current(3) Got NextAsync(3)"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("IMyAsyncEnumerator<System.Int32> ICollection<System.Int32>.GetAsyncEnumerator([System.Threading.CancellationToken token = default(System.Threading.CancellationToken)])", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<System.Boolean> IMyAsyncEnumerator<System.Int32>.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 IMyAsyncEnumerator<System.Int32>.Current { get; }", info.CurrentProperty.ToTestDisplayString()); Assert.Null(info.DisposeMethod); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); var memberModel = model.GetMemberModel(foreachSyntax); var boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(foreachSyntax); ForEachEnumeratorInfo internalInfo = boundNode.EnumeratorInfoOpt; Assert.False(internalInfo.NeedsDisposal); verifier.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 272 (0x110) .maxstack 3 .locals init (int V_0, System.Threading.CancellationToken V_1, System.Runtime.CompilerServices.TaskAwaiter<bool> V_2, C.<Main>d__0 V_3, System.Exception V_4) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Main>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: <hidden> IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_0011 IL_000c: br IL_0096 // sequence point: { IL_0011: nop // sequence point: ICollection<int> c = new Collection<int>(); IL_0012: ldarg.0 IL_0013: newobj ""Collection<int>..ctor()"" IL_0018: stfld ""ICollection<int> C.<Main>d__0.<c>5__1"" // sequence point: await foreach IL_001d: nop // sequence point: c IL_001e: ldarg.0 IL_001f: ldarg.0 IL_0020: ldfld ""ICollection<int> C.<Main>d__0.<c>5__1"" IL_0025: ldloca.s V_1 IL_0027: initobj ""System.Threading.CancellationToken"" IL_002d: ldloc.1 IL_002e: callvirt ""IMyAsyncEnumerator<int> ICollection<int>.GetAsyncEnumerator(System.Threading.CancellationToken)"" IL_0033: stfld ""IMyAsyncEnumerator<int> C.<Main>d__0.<>s__2"" // sequence point: <hidden> IL_0038: br.s IL_0058 // sequence point: var i IL_003a: ldarg.0 IL_003b: ldarg.0 IL_003c: ldfld ""IMyAsyncEnumerator<int> C.<Main>d__0.<>s__2"" IL_0041: callvirt ""int IMyAsyncEnumerator<int>.Current.get"" IL_0046: stfld ""int C.<Main>d__0.<i>5__3"" // sequence point: { IL_004b: nop // sequence point: Write($""Got ""); IL_004c: ldstr ""Got "" IL_0051: call ""void System.Console.Write(string)"" IL_0056: nop // sequence point: } IL_0057: nop // sequence point: in IL_0058: ldarg.0 IL_0059: ldfld ""IMyAsyncEnumerator<int> C.<Main>d__0.<>s__2"" IL_005e: callvirt ""System.Threading.Tasks.Task<bool> IMyAsyncEnumerator<int>.MoveNextAsync()"" IL_0063: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<bool> System.Threading.Tasks.Task<bool>.GetAwaiter()"" IL_0068: stloc.2 // sequence point: <hidden> IL_0069: ldloca.s V_2 IL_006b: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.IsCompleted.get"" IL_0070: brtrue.s IL_00b2 IL_0072: ldarg.0 IL_0073: ldc.i4.0 IL_0074: dup IL_0075: stloc.0 IL_0076: stfld ""int C.<Main>d__0.<>1__state"" // async: yield IL_007b: ldarg.0 IL_007c: ldloc.2 IL_007d: stfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_0082: ldarg.0 IL_0083: stloc.3 IL_0084: ldarg.0 IL_0085: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_008a: ldloca.s V_2 IL_008c: ldloca.s V_3 IL_008e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<bool>, C.<Main>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<bool>, ref C.<Main>d__0)"" IL_0093: nop IL_0094: leave.s IL_010f // async: resume IL_0096: ldarg.0 IL_0097: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_009c: stloc.2 IL_009d: ldarg.0 IL_009e: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<Main>d__0.<>u__1"" IL_00a3: initobj ""System.Runtime.CompilerServices.TaskAwaiter<bool>"" IL_00a9: ldarg.0 IL_00aa: ldc.i4.m1 IL_00ab: dup IL_00ac: stloc.0 IL_00ad: stfld ""int C.<Main>d__0.<>1__state"" IL_00b2: ldarg.0 IL_00b3: ldloca.s V_2 IL_00b5: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.GetResult()"" IL_00ba: stfld ""bool C.<Main>d__0.<>s__4"" IL_00bf: ldarg.0 IL_00c0: ldfld ""bool C.<Main>d__0.<>s__4"" IL_00c5: brtrue IL_003a IL_00ca: ldarg.0 IL_00cb: ldnull IL_00cc: stfld ""IMyAsyncEnumerator<int> C.<Main>d__0.<>s__2"" IL_00d1: leave.s IL_00f4 } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_00d3: stloc.s V_4 IL_00d5: ldarg.0 IL_00d6: ldc.i4.s -2 IL_00d8: stfld ""int C.<Main>d__0.<>1__state"" IL_00dd: ldarg.0 IL_00de: ldnull IL_00df: stfld ""ICollection<int> C.<Main>d__0.<c>5__1"" IL_00e4: ldarg.0 IL_00e5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_00ea: ldloc.s V_4 IL_00ec: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00f1: nop IL_00f2: leave.s IL_010f } // sequence point: } IL_00f4: ldarg.0 IL_00f5: ldc.i4.s -2 IL_00f7: stfld ""int C.<Main>d__0.<>1__state"" // sequence point: <hidden> IL_00fc: ldarg.0 IL_00fd: ldnull IL_00fe: stfld ""ICollection<int> C.<Main>d__0.<c>5__1"" IL_0103: ldarg.0 IL_0104: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_0109: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_010e: nop IL_010f: ret }", sequencePoints: "C+<Main>d__0.MoveNext", source: source); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void TestWithInterfaceImplementingPattern_ChildImplementsDisposeAsync() { string source = @" using static System.Console; using System.Threading.Tasks; public interface ICollection<T> { IMyAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default); } public interface IMyAsyncEnumerator<T> { T Current { get; } Task<bool> MoveNextAsync(); } public class Collection<T> : ICollection<T> { public IMyAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token = default) { return new MyAsyncEnumerator<T>(); } } public sealed class MyAsyncEnumerator<T> : IMyAsyncEnumerator<T> { int i = 0; public T Current { get { Write($""Current({i}) ""); return default; } } public async Task<bool> MoveNextAsync() { Write($""NextAsync({i}) ""); i++; return await Task.FromResult(i < 4); } public System.Threading.Tasks.ValueTask DisposeAsync() => throw null; } class C { static async System.Threading.Tasks.Task Main() { ICollection<int> c = new Collection<int>(); await foreach (var i in c) { Write($""Got ""); } } }"; // DisposeAsync on implementing type is ignored, since we don't do runtime check var comp = CreateCompilationWithTasksExtensions(source + s_IAsyncEnumerable, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "NextAsync(0) Current(1) Got NextAsync(1) Current(2) Got NextAsync(2) Current(3) Got NextAsync(3)"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Null(info.DisposeMethod); } [Fact] public void GetAsyncEnumerator_CancellationTokenMustBeOptional() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token) { throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] [WorkItem(50182, "https://github.com/dotnet/roslyn/issues/50182")] public void GetAsyncEnumerator_CancellationTokenMustBeOptional_OnIAsyncEnumerable() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C { public static async Task M(IAsyncEnumerable<int> e) { await foreach (var i in e) { } } } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token); } public interface IAsyncEnumerator<out T> : System.IAsyncDisposable { System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); T Current { get; } } } namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } "; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyEmitDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'IAsyncEnumerable<int>' because 'IAsyncEnumerable<int>' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in e) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "e").WithArguments("System.Collections.Generic.IAsyncEnumerable<int>", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] [WorkItem(50182, "https://github.com/dotnet/roslyn/issues/50182")] public void GetAsyncEnumerator_CancellationTokenMustBeOptional_OnIAsyncEnumerable_ImplicitImplementation() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task M(C c) { await foreach (var i in c) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token); } public interface IAsyncEnumerator<out T> : System.IAsyncDisposable { System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); T Current { get; } } } namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } "; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyEmitDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in c) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "c").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] [WorkItem(50182, "https://github.com/dotnet/roslyn/issues/50182")] public void GetAsyncEnumerator_CancellationTokenMustBeOptional_OnIAsyncEnumerable_ExplicitImplementation() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task M(C c) { await foreach (var i in c) { } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken token) => throw null; } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken token); } public interface IAsyncEnumerator<out T> : System.IAsyncDisposable { System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); T Current { get; } } } namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } "; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyEmitDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in c) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "c").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void GetAsyncEnumerator_Missing() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C : IAsyncEnumerable<int> { public static async Task M(C c) { await foreach (var i in c) { } } } namespace System.Collections.Generic { public interface IAsyncEnumerable<out T> { } public interface IAsyncEnumerator<out T> : System.IAsyncDisposable { System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); T Current { get; } } } namespace System { public interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } "; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyEmitDiagnostics( // (8,33): error CS0656: Missing compiler required member 'System.Collections.Generic.IAsyncEnumerable`1.GetAsyncEnumerator' // await foreach (var i in c) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "c").WithArguments("System.Collections.Generic.IAsyncEnumerable`1", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void GetAsyncEnumerator_WithOptionalParameter() { string source = @" using System.Collections.Generic; using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } } public IAsyncEnumerator<int> GetAsyncEnumerator(int opt = 0) { throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics(); } [Fact] public void GetAsyncEnumerator_WithParams() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator(params int[] x) { 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; } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync"); } [Fact] public void GetAsyncEnumerator_WithMultipleValidCandidatesWithOptionalParameters() { string source = @" using System.Threading.Tasks; using System.Collections.Generic; class C { public static async Task Main() { await foreach (var i in new C()) { } } public IEnumerator<int> GetAsyncEnumerator(int a = 0) => throw null; public IEnumerator<int> GetAsyncEnumerator(bool a = true) => throw null; }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (8,33): warning CS0278: 'C' does not implement the 'collection' pattern. 'C.GetAsyncEnumerator(int)' is ambiguous with 'C.GetAsyncEnumerator(bool)'. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "new C()").WithArguments("C", "collection", "C.GetAsyncEnumerator(int)", "C.GetAsyncEnumerator(bool)").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void GetAsyncEnumerator_WithMultipleInvalidCandidates() { string source = @" using System.Threading.Tasks; using System.Collections.Generic; class C { public static async Task Main() { await foreach (var i in new C()) { } } public IEnumerator<int> GetAsyncEnumerator(int a) => throw null; public IEnumerator<int> GetAsyncEnumerator(bool a) => throw null; }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_TwoOverloads() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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(int i = 0) { System.Console.Write(""DisposeAsync ""); await Task.Yield(); } public Task DisposeAsync(params string[] s) => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_NoExtensions() { string source = @" using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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 static class Extension { public static ValueTask DisposeAsync(this C.Enumerator e) => throw null; }"; // extension methods do not contribute to pattern-based disposal var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync Done"); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_NoExtensions_TwoExtensions() { string source = @" using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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 static class Extension1 { public static ValueTask DisposeAsync(this C.Enumerator c) => throw null; } public static class Extension2 { public static ValueTask DisposeAsync(this C.Enumerator c) => throw null; } "; // extension methods do not contribute to pattern-based disposal var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync Done"); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_InterfacePreferredToInstanceMethod() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } public Enumerator GetAsyncEnumerator() { return new Enumerator(); } public sealed class Enumerator : System.IAsyncDisposable { public async Task<bool> MoveNextAsync() { System.Console.Write(""MoveNextAsync ""); await Task.Yield(); return false; } public int Current { get => throw null; } async ValueTask System.IAsyncDisposable.DisposeAsync() { System.Console.Write(""DisposeAsync ""); await Task.Yield(); } public ValueTask DisposeAsync() => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_ReturnsVoid() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() => throw null; public sealed class Enumerator { public Task<bool> MoveNextAsync() => throw null; public int Current { get => throw null; } public void DisposeAsync() => throw null; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics( // (7,33): error CS4008: Cannot await 'void' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadAwaitArgVoidCall, "new C()").WithLocation(7, 33) ); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_ReturnsInt() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } } public Enumerator GetAsyncEnumerator() { return new Enumerator(); } public sealed class Enumerator { public async Task<bool> MoveNextAsync() { await Task.Yield(); return false; } public int Current { get => throw null; } public int DisposeAsync() { throw null; } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }); comp.VerifyDiagnostics( // (7,33): error CS1061: 'int' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C()").WithArguments("int", "GetAwaiter").WithLocation(7, 33) ); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_ReturnsAwaitable() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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 Awaitable DisposeAsync() { System.Console.Write(""DisposeAsync ""); return new Awaitable(); } } } public class Awaitable { public Awaiter GetAwaiter() { return new Awaiter(); } } public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public bool IsCompleted { get { return true; } } public bool GetResult() { return true; } public void OnCompleted(System.Action continuation) { } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_ReturnsTask() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] [WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")] public void PatternBasedDisposal_ReturnsTaskOfInt() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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<int> DisposeAsync() { System.Console.Write(""DisposeAsync ""); await Task.Yield(); return 1; } } } "; // it's okay to await `Task<int>` even if we don't care about the result var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] public void PatternBasedDisposal_WithOptionalParameter() { string source = @" using System.Threading.Tasks; class C { public static async Task Main() { await foreach (var i in new C()) { } System.Console.Write(""Done""); } 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<int> DisposeAsync(int i = 1) { System.Console.Write($""DisposeAsync {i} ""); await Task.Yield(); return 1; } } } "; // it's okay to await `Task<int>` even if we don't care about the result var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync 1 Done"); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterBoxingConversion() { var source = @"using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; interface I1 { } interface I2 { } struct StructAwaitable1 : I1 { } struct StructAwaitable2 : I2 { } class Enumerable { public Enumerator GetAsyncEnumerator() => new Enumerator(); internal class Enumerator { public object Current => null; public StructAwaitable1 MoveNextAsync() => new StructAwaitable1(); public StructAwaitable2 DisposeAsync() => new StructAwaitable2(); } } static class Extensions { internal static TaskAwaiter<bool> GetAwaiter(this I1 x) { if (x == null) throw new ArgumentNullException(nameof(x)); Console.Write(x); return Task.FromResult(false).GetAwaiter(); } internal static TaskAwaiter GetAwaiter(this I2 x) { if (x == null) throw new ArgumentNullException(nameof(x)); Console.Write(x); return Task.CompletedTask.GetAwaiter(); } } class Program { static async Task Main() { await foreach (var o in new Enumerable()) { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "StructAwaitable1StructAwaitable2"); } [Fact] public void TestInvalidForeachOnConstantNullObject() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in (object)null) { Console.Write(i); } } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'object' because 'object' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in (object)null) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "(object)null").WithArguments("object", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestConstantNullObjectImplementingIEnumerable() { var source = @" using System; using System.Threading.Tasks; using System.Collections.Generic; public class C { public static async Task Main() { await foreach (var i in (IAsyncEnumerable<int>)null) { Console.Write(i); } } }"; CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (9,33): error CS0186: Use of null is not valid in this context // await foreach (var i in (IAsyncEnumerable<int>)null) Diagnostic(ErrorCode.ERR_NullNotValid, "(IAsyncEnumerable<int>)null").WithLocation(9, 33) ); } [Fact] public void TestConstantNullObjectWithGetAsyncEnumeratorPattern() { var source = @" using System; using System.Threading.Tasks; using System.Collections.Generic; public class C { public static async Task Main() { await foreach (var i in (C)null) { Console.Write(i); } } public IAsyncEnumerator<int> GetAsyncEnumerator() => throw null; }"; CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (9,33): error CS0186: Use of null is not valid in this context // await foreach (var i in (C)null) Diagnostic(ErrorCode.ERR_NullNotValid, "(C)null").WithLocation(9, 33) ); } [Fact] public void TestConstantNullableImplementingIEnumerable() { var source = @" using System; using System.Threading.Tasks; using System.Collections.Generic; public struct C : IAsyncEnumerable<int> { public static async Task Main() { await foreach (var i in (C?)null) { Console.Write(i); } } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) => throw null; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp); } [Fact] public void TestConstantNullableWithGetAsyncEnumeratorPattern() { var source = @" using System; using System.Threading.Tasks; using System.Collections.Generic; public struct C { public static async Task Main() { await foreach (var i in (C?)null) { Console.Write(i); } } public IAsyncEnumerator<int> GetAsyncEnumerator() => throw null; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp); } [Fact] public void TestForeachNullLiteral() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in null) { Console.Write(i); } } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS0186: Use of null is not valid in this context // await foreach (var i in null) Diagnostic(ErrorCode.ERR_NullNotValid, "null").WithLocation(8, 33) ); } [Fact] public void TestForeachDefaultLiteral() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in default) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this object self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS8716: There is no target type for the default literal. // await foreach (var i in default) Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensions() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); var tree = comp.SyntaxTrees.Single(); var model = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree, ignoreAccessibility: false); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal("C.Enumerator Extensions.GetAsyncEnumerator(this C self)", info.GetEnumeratorMethod.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<System.Boolean> C.Enumerator.MoveNextAsync()", info.MoveNextMethod.ToTestDisplayString()); Assert.Equal("System.Int32 C.Enumerator.Current { get; private set; }", info.CurrentProperty.ToTestDisplayString()); Assert.Null(info.DisposeMethod); Assert.Equal("System.Int32", info.ElementType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, info.ElementConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithUpcast() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this object self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnDefaultObject() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in default(object)) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this object self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithStructEnumerator() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithUserDefinedImplicitConversion() { string source = @" using System; using System.Threading.Tasks; public class C { public static implicit operator int(C c) => 0; public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this int self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,33): error CS1929: 'C' does not contain a definition for 'GetAsyncEnumerator' and the best extension method overload 'Extensions.GetAsyncEnumerator(int)' requires a receiver of type 'int' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new C()").WithArguments("C", "GetAsyncEnumerator", "Extensions.GetAsyncEnumerator(int)", "int").WithLocation(10, 33), // (10,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(10, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithNullableValueTypeConversion() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in 1) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this int? self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS1929: 'int' does not contain a definition for 'GetAsyncEnumerator' and the best extension method overload 'Extensions.GetAsyncEnumerator(int?)' requires a receiver of type 'int?' // await foreach (var i in 1) Diagnostic(ErrorCode.ERR_BadInstanceArgType, "1").WithArguments("int", "GetAsyncEnumerator", "Extensions.GetAsyncEnumerator(int?)", "int?").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'int' because 'int' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in 1) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "1").WithArguments("int", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithUnboxingConversion() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new object()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this int self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS1929: 'object' does not contain a definition for 'GetAsyncEnumerator' and the best extension method overload 'Extensions.GetAsyncEnumerator(int)' requires a receiver of type 'int' // await foreach (var i in new object()) Diagnostic(ErrorCode.ERR_BadInstanceArgType, "new object()").WithArguments("object", "GetAsyncEnumerator", "Extensions.GetAsyncEnumerator(int)", "int").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'object' because 'object' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new object()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new object()").WithArguments("object", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithNullableUnwrapping() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in (int?)1) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this int self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS1929: 'int?' does not contain a definition for 'GetAsyncEnumerator' and the best extension method overload 'Extensions.GetAsyncEnumerator(int)' requires a receiver of type 'int' // await foreach (var i in (int?)1) Diagnostic(ErrorCode.ERR_BadInstanceArgType, "(int?)1").WithArguments("int?", "GetAsyncEnumerator", "Extensions.GetAsyncEnumerator(int)", "int").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'int?' because 'int?' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in (int?)1) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "(int?)1").WithArguments("int?", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithZeroToEnumConversion() { var source = @" using System; using System.Threading.Tasks; public enum E { Default = 0 } public class C { public static async Task Main() { await foreach (var i in 0) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this E self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (9,33): error CS1929: 'int' does not contain a definition for 'GetAsyncEnumerator' and the best extension method overload 'Extensions.GetAsyncEnumerator(E)' requires a receiver of type 'E' // await foreach (var i in 0) Diagnostic(ErrorCode.ERR_BadInstanceArgType, "0").WithArguments("int", "GetAsyncEnumerator", "Extensions.GetAsyncEnumerator(E)", "E").WithLocation(9, 33), // (9,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'int' because 'int' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in 0) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "0").WithArguments("int", "GetAsyncEnumerator").WithLocation(9, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithUnconstrainedGenericConversion() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await Inner(1); async Task Inner<T>(T t) { await foreach (var i in t) { Console.Write(i); } } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this object self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithConstrainedGenericConversion() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await Inner(1); async Task Inner<T>(T t) where T : IConvertible { await foreach (var i in t) { Console.Write(i); } } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this IConvertible self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithFormattableStringConversion1() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in $"" "") { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this FormattableString self) => throw null; public static C.Enumerator GetAsyncEnumerator(this object self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithFormattableStringConversion2() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in $"" "") { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this string self) => new C.Enumerator(); public static C.Enumerator GetAsyncEnumerator(this FormattableString self) => throw null; public static C.Enumerator GetAsyncEnumerator(this object self) => throw null; }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithFormattableStringConversion3() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in $"" "") { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this FormattableString self) => throw null; }"; CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS1929: 'string' does not contain a definition for 'GetAsyncEnumerator' and the best extension method overload 'Extensions.GetAsyncEnumerator(FormattableString)' requires a receiver of type 'FormattableString' // await foreach (var i in $" ") Diagnostic(ErrorCode.ERR_BadInstanceArgType, @"$"" """).WithArguments("string", "GetAsyncEnumerator", "Extensions.GetAsyncEnumerator(System.FormattableString)", "System.FormattableString").WithLocation(8, 33), // (8,33): error CS8415: Asynchronous foreach statement cannot operate on variables of type 'string' because 'string' does not contain a public instance or extension definition for 'GetAsyncEnumerator'. Did you mean 'foreach' rather than 'await foreach'? // await foreach (var i in $" ") Diagnostic(ErrorCode.ERR_AwaitForEachMissingMemberWrongAsync, @"$"" """).WithArguments("string", "GetAsyncEnumerator").WithLocation(8, 33)); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithDelegateConversion() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in () => 42) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this Func<int> self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? // await foreach (var i in () => 42) Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "() => 42").WithArguments("lambda expression").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithBoxing() { string source = @" using System; using System.Threading.Tasks; public struct C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this object self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnInterface() { var source = @" using System; using System.Threading.Tasks; public interface I {} public class C : I { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this I self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnDelegate() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in (Func<int>)(() => 42)) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this Func<int> self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnEnum() { var source = @" using System; using System.Threading.Tasks; public enum E { Default } public class C { public static async Task Main() { await foreach (var i in E.Default) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this E self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnNullable() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in (int?)null) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this int? self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnConstantNullObject() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in (object)null) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this object self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnTypeParameter() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new object()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator<T>(this T self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternOnRange() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in 1..4) { Console.Write(i); } } } public static class Extensions { public static async IAsyncEnumerator<int> GetAsyncEnumerator(this Range range) { await Task.Yield(); for(var i = range.Start.Value; i < range.End.Value; i++) { yield return i; } } }"; var comp = CreateCompilationWithTasksExtensions( new[] { source, TestSources.Index, TestSources.Range, AsyncStreamsTypes }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnTuple() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; public struct C { public static async Task Main() { await foreach (var i in (1, 2, 3)) { Console.Write(i); } } } public static class Extensions { public static async IAsyncEnumerator<T> GetAsyncEnumerator<T>(this (T first, T second, T third) self) { await Task.Yield(); yield return self.first; yield return self.second; yield return self.third; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsOnTupleWithNestedConversions() { var source = @" using System; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; public struct C { public static async Task Main() { await foreach (var (a, b) in (new[] { 1, 2, 3 }, new List<decimal>{ 0.1m, 0.2m, 0.3m })) { Console.WriteLine(a + b); } } } public static class Extensions { public static async IAsyncEnumerator<(T1, T2)> GetAsyncEnumerator<T1, T2>(this (IEnumerable<T1> first, IEnumerable<T2> second) self) { await Task.Yield(); foreach(var pair in self.first.Zip(self.second, (a,b) => (a,b))) { yield return pair; } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"1.1 2.2 3.3"); } [Fact] public void TestMoveNextAsyncPatternViaExtensions1() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); public static bool MoveNext(this C.Enumerator e) => false; }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,33): error CS0117: 'C.Enumerator' does not contain a definition for 'MoveNextAsync' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator", "MoveNextAsync").WithLocation(8, 33), // (8,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'Extensions.GetAsyncEnumerator(C)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "Extensions.GetAsyncEnumerator(C)").WithLocation(8, 33) ); } [Fact] public void TestMoveNextAsyncPatternViaExtensions2() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } } public C.Enumerator GetAsyncEnumerator() => new C.Enumerator(); } public static class Extensions { public static bool MoveNext(this C.Enumerator e) => false; }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,33): error CS0117: 'C.Enumerator' does not contain a definition for 'MoveNextAsync' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator", "MoveNextAsync").WithLocation(8, 33), // (8,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "C.GetAsyncEnumerator()").WithLocation(8, 33) ); } [Fact] public void TestPreferAsyncEnumeratorPatternFromInstanceThanViaExtension() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator1 { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } public sealed class Enumerator2 { public int Current { get; private set; } public Task<bool> MoveNextAsync() => throw null; } public C.Enumerator1 GetAsyncEnumerator() => new C.Enumerator1(); } public static class Extensions { public static C.Enumerator2 GetAsyncEnumerator(this C self) => throw null; }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestPreferAsyncEnumeratorPatternFromInstanceThanViaExtensionEvenWhenInvalid() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator1 { } public sealed class Enumerator2 { public int Current { get; private set; } public Task<bool> MoveNextAsync() => throw null; } public C.Enumerator1 GetAsyncEnumerator() => throw null; } public static class Extensions { public static C.Enumerator2 GetAsyncEnumerator(this C self) => throw null; }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,33): error CS0117: 'C.Enumerator1' does not contain a definition for 'Current' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator1", "Current").WithLocation(8, 33), // (8,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator1' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator1", "C.GetAsyncEnumerator()").WithLocation(8, 33)); } [Fact] public void TestPreferAsyncEnumeratorPatternFromIAsyncEnumerableInterfaceThanViaExtension() { string source = @" using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; public class C : IAsyncEnumerable<int> { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator1 : IAsyncEnumerator<int> { public int Current { get; private set; } public ValueTask<bool> MoveNextAsync() => new ValueTask<bool>(Current++ != 3); public ValueTask DisposeAsync() => new ValueTask(); } public sealed class Enumerator2 { public int Current { get; private set; } public Task<bool> MoveNextAsync() => throw null; } IAsyncEnumerator<int> IAsyncEnumerable<int>.GetAsyncEnumerator(CancellationToken cancellationToken) => new C.Enumerator1(); } public static class Extensions { public static C.Enumerator2 GetAsyncEnumerator(this C self) => throw null; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestCannotUseExtensionGetAsyncEnumeratorOnDynamic() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in (dynamic)new C()) { Console.Write(i); } } public sealed class Enumerator2 { public int Current { get; private set; } public bool MoveNext() => throw null; } } public static class Extensions { public static C.Enumerator2 GetAsyncEnumerator(this C self) => throw null; }"; CreateCompilationWithCSharp(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (9,33): error CS8416: Cannot use a collection of dynamic type in an asynchronous foreach // await foreach (var i in (dynamic)new C()) Diagnostic(ErrorCode.ERR_BadDynamicAwaitForEach, "(dynamic)new C()").WithLocation(9, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensions() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,33): warning CS0278: 'C' does not implement the 'collection' pattern. 'Extensions1.GetAsyncEnumerator(C)' is ambiguous with 'Extensions2.GetAsyncEnumerator(C)'. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "new C()").WithArguments("C", "collection", "Extensions1.GetAsyncEnumerator(C)", "Extensions2.GetAsyncEnumerator(C)").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWhenOneHasCorrectPattern() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static int GetAsyncEnumerator(this C self) => 42; } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): warning CS0278: 'C' does not implement the 'collection' pattern. 'Extensions1.GetAsyncEnumerator(C)' is ambiguous with 'Extensions2.GetAsyncEnumerator(C)'. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "new C()").WithArguments("C", "collection", "Extensions1.GetAsyncEnumerator(C)", "Extensions2.GetAsyncEnumerator(C)").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWhenNeitherHasCorrectPattern() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static int GetAsyncEnumerator(this C self) => 42; } public static class Extensions2 { public static bool GetAsyncEnumerator(this C self) => true; }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): warning CS0278: 'C' does not implement the 'collection' pattern. 'Extensions1.GetAsyncEnumerator(C)' is ambiguous with 'Extensions2.GetAsyncEnumerator(C)'. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "new C()").WithArguments("C", "collection", "Extensions1.GetAsyncEnumerator(C)", "Extensions2.GetAsyncEnumerator(C)").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWhenOneHasCorrectNumberOfParameters() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this C self, int _) => throw null; } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWhenNeitherHasCorrectNumberOfParameters() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this C self, int _) => new C.Enumerator(); } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this C self, bool _) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS1501: No overload for method 'GetAsyncEnumerator' takes 0 arguments // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadArgCount, "new C()").WithArguments("GetAsyncEnumerator", "0").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsOnDifferentInterfaces() { var source = @" using System; using System.Threading.Tasks; public interface I1 {} public interface I2 {} public class C : I1, I2 { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this I1 self) => new C.Enumerator(); } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this I2 self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (12,33): warning CS0278: 'C' does not implement the 'collection' pattern. 'Extensions1.GetAsyncEnumerator(I1)' is ambiguous with 'Extensions2.GetAsyncEnumerator(I2)'. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "new C()").WithArguments("C", "collection", "Extensions1.GetAsyncEnumerator(I1)", "Extensions2.GetAsyncEnumerator(I2)").WithLocation(12, 33), // (12,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(12, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWithMostSpecificReceiver() { var source = @" using System; using System.Threading.Tasks; public interface I {} public class C : I { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this I self) => throw null; } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWithMostSpecificReceiverWhenMostSpecificReceiverDoesntImplementPattern() { var source = @" using System; using System.Threading.Tasks; public interface I {} public class C : I { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this I self) => throw null; } public static class Extensions2 { public static int GetAsyncEnumerator(this C self) => 42; }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (10,33): error CS0117: 'int' does not contain a definition for 'Current' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("int", "Current").WithLocation(10, 33), // (10,33): error CS8412: Asynchronous foreach requires that the return type 'int' of 'Extensions2.GetAsyncEnumerator(C)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("int", "Extensions2.GetAsyncEnumerator(C)").WithLocation(10, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWhenOneHasOptionalParams() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this C self, int a = 0) => throw null; }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaAmbiguousExtensionsWhenOneHasFewerOptionalParams() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions1 { public static C.Enumerator GetAsyncEnumerator(this C self, int a = 0, int b = 1) => new C.Enumerator(); } public static class Extensions2 { public static C.Enumerator GetAsyncEnumerator(this C self, int a = 0) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): warning CS0278: 'C' does not implement the 'collection' pattern. 'Extensions1.GetAsyncEnumerator(C, int, int)' is ambiguous with 'Extensions2.GetAsyncEnumerator(C, int)'. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "new C()").WithArguments("C", "collection", "Extensions1.GetAsyncEnumerator(C, int, int)", "Extensions2.GetAsyncEnumerator(C, int)").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithOptionalParameter() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public Enumerator(int start) => Current = start; public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self, int x = 1) => new C.Enumerator(x); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "23"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithArgList() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self, __arglist) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'Extensions.GetAsyncEnumerator(C, __arglist)' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "new C()").WithArguments("__arglist", "Extensions.GetAsyncEnumerator(C, __arglist)").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithParams() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public Enumerator(int[] arr) => Current = arr.Length; public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self, params int[] x) => new C.Enumerator(x); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaRefExtensionOnNonAssignableVariable() { string source = @" using System; using System.Threading.Tasks; public struct C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this ref C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,33): error CS1510: A ref or out value must be an assignable variable // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new C()").WithLocation(8, 33)); } [Fact] public void TestGetAsyncEnumeratorPatternViaRefExtensionOnAssignableVariable() { string source = @" using System; using System.Threading.Tasks; public struct C { public static async Task Main() { var c = new C(); await foreach (var i in c) { Console.Write(i); } } public struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this ref C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,33): error CS1510: A ref or out value must be an assignable variable // await foreach (var i in c) Diagnostic(ErrorCode.ERR_RefLvalueExpected, "c").WithLocation(9, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaOutExtension() { string source = @" using System; using System.Threading.Tasks; public struct C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this out C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,33): error CS1620: Argument 1 must be passed with the 'out' keyword // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadArgRef, "new C()").WithArguments("1", "out").WithLocation(8, 33), // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33), // (21,56): error CS8328: The parameter modifier 'out' cannot be used with 'this' // public static C.Enumerator GetAsyncEnumerator(this out C self) => new C.Enumerator(); Diagnostic(ErrorCode.ERR_BadParameterModifiers, "out").WithArguments("out", "this").WithLocation(21, 56)); } [Fact] public void TestGetAsyncEnumeratorPatternViaInExtensionOnNonAssignableVariable() { string source = @" using System; using System.Threading.Tasks; public struct C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this in C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaInExtensionOnAssignableVariable() { string source = @" using System; using System.Threading.Tasks; public struct C { public static async Task Main() { var c = new C(); await foreach (var i in c) { Console.Write(i); } } public struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this in C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsCSharp8() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (8,33): error CS8400: Feature 'extension GetAsyncEnumerator' is not available in C# 8.0. Please use language version 9.0 or greater. // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "new C()").WithArguments("extension GetAsyncEnumerator", "9.0").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaInternalExtensions() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { internal static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionInInternalClass() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } internal static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithInvalidEnumerator() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } } } internal static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS0117: 'C.Enumerator' does not contain a definition for 'MoveNextAsync' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator", "MoveNextAsync").WithLocation(8, 33), // (8,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator' of 'Extensions.GetAsyncEnumerator(C)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator", "Extensions.GetAsyncEnumerator(C)").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithInstanceGetAsyncEnumeratorReturningTypeWhichDoesntMatchPattern() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator1 { public int Current { get; private set; } } public sealed class Enumerator2 { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } public Enumerator1 GetAsyncEnumerator() => new Enumerator1(); } internal static class Extensions { public static C.Enumerator2 GetAsyncEnumerator(this C self) => new C.Enumerator2(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS0117: 'C.Enumerator1' does not contain a definition for 'MoveNextAsync' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("C.Enumerator1", "MoveNextAsync").WithLocation(8, 33), // (8,33): error CS8412: Asynchronous foreach requires that the return type 'C.Enumerator1' of 'C.GetAsyncEnumerator()' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("C.Enumerator1", "C.GetAsyncEnumerator()").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithInternalInstanceGetAsyncEnumerator() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } internal Enumerator GetAsyncEnumerator() => throw null; } internal static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,33): warning CS0279: 'C' does not implement the 'async streams' pattern. 'C.GetAsyncEnumerator()' is not a public instance or extension method. // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "new C()").WithArguments("C", "async streams", "C.GetAsyncEnumerator()").WithLocation(8, 33) ); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithInstanceGetAsyncEnumeratorWithTooManyParameters() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } internal Enumerator GetAsyncEnumerator(int a) => throw null; } internal static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithStaticGetAsyncEnumeratorDeclaredInType() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } public static Enumerator GetAsyncEnumerator() => throw null; } internal static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestAwaitForEachViaExtensionImplicitImplementationOfIAsyncDisposableStruct() { var source = @" using System; using System.Threading.Tasks; class C { static async Task Main() { await foreach (var x in new C()) { Console.Write(x); } } } static class Extensions { public static Enumerator GetAsyncEnumerator(this C _) => new Enumerator(); } struct Enumerator : IAsyncDisposable { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); public ValueTask DisposeAsync() { Console.Write(""Disposed""); return new ValueTask(); } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"123Disposed"); } [Fact] public void TestAwaitForEachViaExtensionExplicitlyDisposableStruct() { var source = @" using System; using System.Threading.Tasks; class C { static async Task Main() { await foreach (var x in new C()) { Console.Write(x); } } } static class Extensions { public static Enumerator GetAsyncEnumerator(this C _) => new Enumerator(); } struct Enumerator : IAsyncDisposable { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); ValueTask IAsyncDisposable.DisposeAsync() { Console.Write(""Disposed""); return new ValueTask(); } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"123Disposed"); } [Fact] public void TestAwaitForEachViaExtensionAsyncDisposeStruct() { var source = @" using System; using System.Threading.Tasks; class C { static async Task Main() { await foreach (var x in new C()) { Console.Write(x); } } } static class Extensions { public static Enumerator GetAsyncEnumerator(this C _) => new Enumerator(); } struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); public ValueTask DisposeAsync() { Console.Write(""Disposed""); return new ValueTask(); } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"123Disposed"); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionsWithTaskLikeTypeMoveNext() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public ValueTask<bool> MoveNextAsync() => new ValueTask<bool>(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestWithObsoletePatternMethodsViaExtension() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { [Obsolete] public int Current { get; private set; } [Obsolete] public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); [Obsolete] public Task DisposeAsync() { Console.Write(""Disposed""); return Task.CompletedTask; } } } [Obsolete] public static class Extensions { [Obsolete] public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,15): warning CS0612: 'Extensions.GetAsyncEnumerator(C)' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("Extensions.GetAsyncEnumerator(C)").WithLocation(8, 15), // (8,15): warning CS0612: 'C.Enumerator.MoveNextAsync()' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.Enumerator.MoveNextAsync()").WithLocation(8, 15), // (8,15): warning CS0612: 'C.Enumerator.Current' is obsolete // await foreach (var i in new C()) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "foreach").WithArguments("C.Enumerator.Current").WithLocation(8, 15) ); CompileAndVerify(comp, expectedOutput: "123Disposed"); } [Fact] public void TestGetAsyncEnumeratorPatternViaImportedExtensions() { string source = @" using System; using System.Threading.Tasks; using N; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } namespace N { public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaUnimportedExtensions() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } namespace N { public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } }"; CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestWithPatternGetAsyncEnumeratorViaExtensionOnUnassignedCollection() { string source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { C c; await foreach (var i in c) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,33): error CS0165: Use of unassigned local variable 'c' // await foreach (var i in c) Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c").WithLocation(9, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaValidExtensionInClosestNamespaceInvalidInFurtherNamespace1() { var source = @" using System; using System.Threading.Tasks; using N1.N2.N3; namespace N1 { public static class Extensions { public static int GetAsyncEnumerator(this C self) => throw null; } namespace N2 { public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } namespace N3 { using N2; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } } } }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaValidExtensionInClosestNamespaceInvalidInFurtherNamespace2() { var source = @" using System; using System.Threading.Tasks; using N1; using N3; namespace N1 { using N2; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } } namespace N2 { public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } } namespace N3 { public static class Extensions { public static int GetAsyncEnumerator(this C self) => throw null; } }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,1): hidden CS8019: Unnecessary using directive. // using N3; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N3;").WithLocation(5, 1)); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaInvalidExtensionInClosestNamespaceValidInFurtherNamespace1() { var source = @" using System; using System.Threading.Tasks; using N1.N2.N3; namespace N1 { public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } namespace N2 { public static class Extensions { public static int GetAsyncEnumerator(this C self) => throw null; } namespace N3 { using N2; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } } } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (27,45): error CS0117: 'int' does not contain a definition for 'Current' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("int", "Current").WithLocation(27, 45), // (27,45): error CS8412: Asynchronous foreach requires that the return type 'int' of 'Extensions.GetAsyncEnumerator(C)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("int", "N1.N2.Extensions.GetAsyncEnumerator(N1.N2.N3.C)").WithLocation(27, 45)); } [Fact] public void TestGetAsyncEnumeratorPatternViaInvalidExtensionInClosestNamespaceValidInFurtherNamespace2() { var source = @" using System; using System.Threading.Tasks; using N1; using N2; namespace N1 { using N3; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } } namespace N2 { public static class Extensions { public static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } } namespace N3 { public static class Extensions { public static int GetAsyncEnumerator(this C self) => throw null; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (5,1): hidden CS8019: Unnecessary using directive. // using N2; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N2;").WithLocation(5, 1), // (14,37): error CS0117: 'int' does not contain a definition for 'Current' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_NoSuchMember, "new C()").WithArguments("int", "Current").WithLocation(14, 37), // (14,37): error CS8412: Asynchronous foreach requires that the return type 'int' of 'Extensions.GetAsyncEnumerator(C)' must have a suitable public 'MoveNextAsync' method and public 'Current' property // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_BadGetAsyncEnumerator, "new C()").WithArguments("int", "N3.Extensions.GetAsyncEnumerator(N1.C)").WithLocation(14, 37)); } [Fact] public void TestGetAsyncEnumeratorPatternViaAccessiblePrivateExtension() { var source = @" using System; using System.Threading.Tasks; public static class Program { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } private static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } public class C { public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaAccessiblePrivateExtensionInNestedClass() { var source = @" using System; using System.Threading.Tasks; public static class Program { public static class Inner { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } } private static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } public class C { public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestGetAsyncEnumeratorPatternViaInaccessiblePrivateExtension() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { private static C.Enumerator GetAsyncEnumerator(this C self) => new C.Enumerator(); } "; CreateCompilation(source, parseOptions: TestOptions.Regular9) .VerifyDiagnostics( // (8,33): error CS8411: Asynchronous foreach statement cannot operate on variables of type 'C' because 'C' does not contain a suitable public instance or extension definition for 'GetAsyncEnumerator' // await foreach (var i in new C()) Diagnostic(ErrorCode.ERR_AwaitForEachMissingMember, "new C()").WithArguments("C", "GetAsyncEnumerator").WithLocation(8, 33) ); } [Fact] public void TestGetAsyncEnumeratorPatternViaExtensionWithRefReturn() { var source = @" using System; using System.Threading.Tasks; public class C { public static async Task Main() { await foreach (var i in new C()) { Console.Write(i); } await foreach (var i in new C()) { Console.Write(i); } } public struct Enumerator { public int Current { get; private set; } public Task<bool> MoveNextAsync() => Task.FromResult(Current++ != 3); } } public static class Extensions { public static C.Enumerator Instance = new C.Enumerator(); public static ref C.Enumerator GetAsyncEnumerator(this C self) => ref Instance; }"; var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "123123"); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Test/Emit/CodeGen/ForeachTest.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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class ForeachTest : EmitMetadataTestBase { // The loop object must be an array or an object collection [Fact] public void SimpleLoop() { var text = @" using System; public class Test { static void Main(string[] args) { string[] arr = new string[4]; // Initialize arr[0] = ""one""; // Element 1 arr[1] = ""two""; // Element 2 arr[2] = ""three""; // Element 3 arr[3] = ""four""; // Element 4 foreach (string s in arr) { System.Console.WriteLine(s); } } } "; string expectedOutput = @"one two three four"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestIteration() { CompileAndVerify(@" using System; public class Test { public static void Main(string[] args) { unsafe { int* y = null; foreach (var x in new int*[] { y }) { } } } }", options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 33 (0x21) .maxstack 4 .locals init (int* V_0, //y int*[] V_1, int V_2) IL_0000: ldc.i4.0 IL_0001: conv.u IL_0002: stloc.0 IL_0003: ldc.i4.1 IL_0004: newarr ""int*"" IL_0009: dup IL_000a: ldc.i4.0 IL_000b: ldloc.0 IL_000c: stelem.i IL_000d: stloc.1 IL_000e: ldc.i4.0 IL_000f: stloc.2 IL_0010: br.s IL_001a IL_0012: ldloc.1 IL_0013: ldloc.2 IL_0014: ldelem.i IL_0015: pop IL_0016: ldloc.2 IL_0017: ldc.i4.1 IL_0018: add IL_0019: stloc.2 IL_001a: ldloc.2 IL_001b: ldloc.1 IL_001c: ldlen IL_001d: conv.i4 IL_001e: blt.s IL_0012 IL_0020: ret }"); } // Using the Linq as iteration variable [Fact] public void TestLinqInForeach() { var text = @"using System; using System.Linq; public class Test { public static void Main(string[] args) { foreach (int x in from char c in ""abc"" select c) { Console.WriteLine(x); } } }"; string expectedOutput = @"97 98 99"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Empty foreach statement [Fact] public void TestEmptyStatementForeach() { var text = @"class C { static void Main() { foreach (char C in ""abc""); } }"; string expectedIL = @"{ // Code size 32 (0x20) .maxstack 2 .locals init (string V_0, int V_1) IL_0000: ldstr ""abc"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 IL_0008: br.s IL_0016 IL_000a: ldloc.0 IL_000b: ldloc.1 IL_000c: callvirt ""char string.this[int].get"" IL_0011: pop IL_0012: ldloc.1 IL_0013: ldc.i4.1 IL_0014: add IL_0015: stloc.1 IL_0016: ldloc.1 IL_0017: ldloc.0 IL_0018: callvirt ""int string.Length.get"" IL_001d: blt.s IL_000a IL_001f: ret }"; CompileAndVerify(text).VerifyIL("C.Main", expectedIL); } // Foreach value can't be deleted in a loop [Fact] public void TestRemoveValueInForeach() { var text = @"using System.Collections; using System.Collections.Generic; class C { static public void Main() { List<int> arrInt = new List<int>(); arrInt.Add(1); foreach (int i in arrInt) { arrInt.Remove(i);//It will generate error in run-time } } } "; string expectedIL = @"{ // Code size 64 (0x40) .maxstack 2 .locals init (System.Collections.Generic.List<int> V_0, //arrInt System.Collections.Generic.List<int>.Enumerator V_1, int V_2) //i IL_0000: newobj ""System.Collections.Generic.List<int>..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_000d: ldloc.0 IL_000e: callvirt ""System.Collections.Generic.List<int>.Enumerator System.Collections.Generic.List<int>.GetEnumerator()"" IL_0013: stloc.1 .try { IL_0014: br.s IL_0026 IL_0016: ldloca.s V_1 IL_0018: call ""int System.Collections.Generic.List<int>.Enumerator.Current.get"" IL_001d: stloc.2 IL_001e: ldloc.0 IL_001f: ldloc.2 IL_0020: callvirt ""bool System.Collections.Generic.List<int>.Remove(int)"" IL_0025: pop IL_0026: ldloca.s V_1 IL_0028: call ""bool System.Collections.Generic.List<int>.Enumerator.MoveNext()"" IL_002d: brtrue.s IL_0016 IL_002f: leave.s IL_003f } finally { IL_0031: ldloca.s V_1 IL_0033: constrained. ""System.Collections.Generic.List<int>.Enumerator"" IL_0039: callvirt ""void System.IDisposable.Dispose()"" IL_003e: endfinally } IL_003f: ret }"; CompileAndVerify(text).VerifyIL("C.Main", expectedIL); } // With multidimensional arrays, you can use one loop to iterate through the elements [Fact] public void TestMultiDimensionalArray() { var text = @"class T { static public void Main() { int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } }; foreach (int i in numbers2D) { System.Console.WriteLine(i); } } } "; string expectedOutput = @"9 99 3 33 5 55"; CompileAndVerify(text, expectedOutput: expectedOutput); } [WorkItem(540917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540917")] [Fact] public void TestArray() { var text = @"using System; public class Test { static void Main(string[] args) { string[] arr = new string[4]; // Initialize arr[0] = ""one""; // Element 1 arr[1] = ""two""; // Element 2 foreach (string s in arr) { System.Console.WriteLine(s); } } } "; string expectedIL = @" { // Code size 46 (0x2e) .maxstack 4 .locals init (string[] V_0, int V_1) IL_0000: ldc.i4.4 IL_0001: newarr ""string"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldstr ""one"" IL_000d: stelem.ref IL_000e: dup IL_000f: ldc.i4.1 IL_0010: ldstr ""two"" IL_0015: stelem.ref IL_0016: stloc.0 IL_0017: ldc.i4.0 IL_0018: stloc.1 IL_0019: br.s IL_0027 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldelem.ref IL_001e: call ""void System.Console.WriteLine(string)"" IL_0023: ldloc.1 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.1 IL_0027: ldloc.1 IL_0028: ldloc.0 IL_0029: ldlen IL_002a: conv.i4 IL_002b: blt.s IL_001b IL_002d: ret }"; CompileAndVerify(text).VerifyIL("Test.Main", expectedIL); } [Fact] public void TestSpan() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { var sp = new Span<int>(new[] {1, 2, 3}); foreach(var i in sp) { Console.Write(i); } } } ", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "123").VerifyIL("Test.Main", @" { // Code size 56 (0x38) .maxstack 3 .locals init (System.Span<int> V_0, int V_1) IL_0000: ldc.i4.3 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000c: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0011: newobj ""System.Span<int>..ctor(int[])"" IL_0016: stloc.0 IL_0017: ldc.i4.0 IL_0018: stloc.1 IL_0019: br.s IL_002d IL_001b: ldloca.s V_0 IL_001d: ldloc.1 IL_001e: call ""ref int System.Span<int>.this[int].get"" IL_0023: ldind.i4 IL_0024: call ""void System.Console.Write(int)"" IL_0029: ldloc.1 IL_002a: ldc.i4.1 IL_002b: add IL_002c: stloc.1 IL_002d: ldloc.1 IL_002e: ldloca.s V_0 IL_0030: call ""int System.Span<int>.Length.get"" IL_0035: blt.s IL_001b IL_0037: ret }"); } [Fact] public void TestSpanSideeffectingLoopBody() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { var sp = new Span<int>(new[] {1, 2, 3}); foreach(var i in sp) { Console.Write(i); sp = default; } Console.Write(sp.Length); } } ", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "1230").VerifyIL("Test.Main", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (System.Span<int> V_0, //sp System.Span<int> V_1, int V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.3 IL_0003: newarr ""int"" IL_0008: dup IL_0009: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000e: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0013: call ""System.Span<int>..ctor(int[])"" IL_0018: ldloc.0 IL_0019: stloc.1 IL_001a: ldc.i4.0 IL_001b: stloc.2 IL_001c: br.s IL_0038 IL_001e: ldloca.s V_1 IL_0020: ldloc.2 IL_0021: call ""ref int System.Span<int>.this[int].get"" IL_0026: ldind.i4 IL_0027: call ""void System.Console.Write(int)"" IL_002c: ldloca.s V_0 IL_002e: initobj ""System.Span<int>"" IL_0034: ldloc.2 IL_0035: ldc.i4.1 IL_0036: add IL_0037: stloc.2 IL_0038: ldloc.2 IL_0039: ldloca.s V_1 IL_003b: call ""int System.Span<int>.Length.get"" IL_0040: blt.s IL_001e IL_0042: ldloca.s V_0 IL_0044: call ""int System.Span<int>.Length.get"" IL_0049: call ""void System.Console.Write(int)"" IL_004e: ret }"); } [Fact] public void TestReadOnlySpan() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { var sp = new ReadOnlySpan<Color>(new [] {Color.Red, Color.Green, Color.Blue}); foreach(var i in sp) { Console.Write(i); } } } ", TestOptions.ReleaseExe); //NOTE: the verification error is expected. Wrapping of literals into readonly spans uses unsafe Span.ctor. CompileAndVerify(comp, expectedOutput: "RedGreenBlue", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 50 (0x32) .maxstack 2 .locals init (System.ReadOnlySpan<System.Color> V_0, int V_1) IL_0000: ldsflda ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=3 <PrivateImplementationDetails>.AE4B3280E56E2FAF83F414A6E3DABE9D5FBE18976544C05FED121ACCB85B53FC"" IL_0005: ldc.i4.3 IL_0006: newobj ""System.ReadOnlySpan<System.Color>..ctor(void*, int)"" IL_000b: stloc.0 IL_000c: ldc.i4.0 IL_000d: stloc.1 IL_000e: br.s IL_0027 IL_0010: ldloca.s V_0 IL_0012: ldloc.1 IL_0013: call ""ref readonly System.Color System.ReadOnlySpan<System.Color>.this[int].get"" IL_0018: ldind.i1 IL_0019: box ""System.Color"" IL_001e: call ""void System.Console.Write(object)"" IL_0023: ldloc.1 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.1 IL_0027: ldloc.1 IL_0028: ldloca.s V_0 IL_002a: call ""int System.ReadOnlySpan<System.Color>.Length.get"" IL_002f: blt.s IL_0010 IL_0031: ret }"); } [Fact] public void TestReadOnlySpanString() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { var sp = (ReadOnlySpan<char>)""hello""; foreach(var i in sp) { Console.Write(i); } } } ", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "hello", verify: Verification.Passes).VerifyIL("Test.Main", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (System.ReadOnlySpan<char> V_0, int V_1) IL_0000: ldstr ""hello"" IL_0005: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.0 IL_000c: stloc.1 IL_000d: br.s IL_0021 IL_000f: ldloca.s V_0 IL_0011: ldloc.1 IL_0012: call ""ref readonly char System.ReadOnlySpan<char>.this[int].get"" IL_0017: ldind.u2 IL_0018: call ""void System.Console.Write(char)"" IL_001d: ldloc.1 IL_001e: ldc.i4.1 IL_001f: add IL_0020: stloc.1 IL_0021: ldloc.1 IL_0022: ldloca.s V_0 IL_0024: call ""int System.ReadOnlySpan<char>.Length.get"" IL_0029: blt.s IL_000f IL_002b: ret }"); } [Fact] public void TestReadOnlySpan2() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { foreach(var i in (ReadOnlySpan<byte>)new byte[] {1, 2, 3}) { Console.Write(i); } } } ", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "123", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 45 (0x2d) .maxstack 2 .locals init (System.ReadOnlySpan<byte> V_0, int V_1) IL_0000: ldsflda ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=3 <PrivateImplementationDetails>.039058C6F2C0CB492C533B0A4D14EF77CC0F78ABCCCED5287D84A1A2011CFB81"" IL_0005: ldc.i4.3 IL_0006: newobj ""System.ReadOnlySpan<byte>..ctor(void*, int)"" IL_000b: stloc.0 IL_000c: ldc.i4.0 IL_000d: stloc.1 IL_000e: br.s IL_0022 IL_0010: ldloca.s V_0 IL_0012: ldloc.1 IL_0013: call ""ref readonly byte System.ReadOnlySpan<byte>.this[int].get"" IL_0018: ldind.u1 IL_0019: call ""void System.Console.Write(int)"" IL_001e: ldloc.1 IL_001f: ldc.i4.1 IL_0020: add IL_0021: stloc.1 IL_0022: ldloc.1 IL_0023: ldloca.s V_0 IL_0025: call ""int System.ReadOnlySpan<byte>.Length.get"" IL_002a: blt.s IL_0010 IL_002c: ret }"); } [Fact] public void TestSpanNoIndexer() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { var sp = new Span<int>(new[] {1, 2, 3}); foreach(var i in sp) { Console.Write(i); } } } ", TestOptions.ReleaseExe); comp.MakeMemberMissing(WellKnownMember.System_Span_T__get_Item); CompileAndVerify(comp, expectedOutput: "123").VerifyIL("Test.Main", @" { // Code size 57 (0x39) .maxstack 4 .locals init (System.Span<int> V_0, //sp System.Span<int>.Enumerator V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.3 IL_0003: newarr ""int"" IL_0008: dup IL_0009: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000e: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0013: call ""System.Span<int>..ctor(int[])"" IL_0018: ldloca.s V_0 IL_001a: call ""System.Span<int>.Enumerator System.Span<int>.GetEnumerator()"" IL_001f: stloc.1 IL_0020: br.s IL_002f IL_0022: ldloca.s V_1 IL_0024: call ""ref int System.Span<int>.Enumerator.Current.get"" IL_0029: ldind.i4 IL_002a: call ""void System.Console.Write(int)"" IL_002f: ldloca.s V_1 IL_0031: call ""bool System.Span<int>.Enumerator.MoveNext()"" IL_0036: brtrue.s IL_0022 IL_0038: ret }"); } [Fact] public void TestSpanValIndexer() { var comp = CreateEmptyCompilation(@" using System; class Test { public static void Main() { var sp = new ReadOnlySpan<int>(new[] {1, 2, 3}); foreach(var i in sp) { Console.Write(i); } } } namespace System { public readonly ref struct ReadOnlySpan<T> { private readonly T[] arr; public T this[int i] => arr[i]; public int Length { get; } public ReadOnlySpan(T[] arr) { this.arr = arr; this.Length = arr.Length; } public Enumerator GetEnumerator() => new Enumerator(this); public ref struct Enumerator { private readonly ReadOnlySpan<T> _span; private int _index; internal Enumerator(ReadOnlySpan<T> span) { _span = span; _index = -1; } public bool MoveNext() { int index = _index + 1; if (index < _span.Length) { _index = index; return true; } return false; } public T Current { get => _span[_index]; } } } } ", references: new[] { MscorlibRef_v4_0_30316_17626 }, TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "123", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 56 (0x38) .maxstack 4 .locals init (System.ReadOnlySpan<int> V_0, //sp System.ReadOnlySpan<int>.Enumerator V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.3 IL_0003: newarr ""int"" IL_0008: dup IL_0009: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000e: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0013: call ""System.ReadOnlySpan<int>..ctor(int[])"" IL_0018: ldloca.s V_0 IL_001a: call ""System.ReadOnlySpan<int>.Enumerator System.ReadOnlySpan<int>.GetEnumerator()"" IL_001f: stloc.1 IL_0020: br.s IL_002e IL_0022: ldloca.s V_1 IL_0024: call ""int System.ReadOnlySpan<int>.Enumerator.Current.get"" IL_0029: call ""void System.Console.Write(int)"" IL_002e: ldloca.s V_1 IL_0030: call ""bool System.ReadOnlySpan<int>.Enumerator.MoveNext()"" IL_0035: brtrue.s IL_0022 IL_0037: ret }"); } [Fact] public void TestSpanConvert() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { var sp = new Span<int>(new[] {1, 2, 3}); foreach(byte i in sp) { Console.Write(i); } } } ", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "123").VerifyIL("Test.Main", @" { // Code size 57 (0x39) .maxstack 3 .locals init (System.Span<int> V_0, int V_1) IL_0000: ldc.i4.3 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000c: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0011: newobj ""System.Span<int>..ctor(int[])"" IL_0016: stloc.0 IL_0017: ldc.i4.0 IL_0018: stloc.1 IL_0019: br.s IL_002e IL_001b: ldloca.s V_0 IL_001d: ldloc.1 IL_001e: call ""ref int System.Span<int>.this[int].get"" IL_0023: ldind.i4 IL_0024: conv.u1 IL_0025: call ""void System.Console.Write(int)"" IL_002a: ldloc.1 IL_002b: ldc.i4.1 IL_002c: add IL_002d: stloc.1 IL_002e: ldloc.1 IL_002f: ldloca.s V_0 IL_0031: call ""int System.Span<int>.Length.get"" IL_0036: blt.s IL_001b IL_0038: ret }"); } [Fact] public void TestSpanDeconstruct() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { static void Main(string[] args) { var sp = new Span<(int, int)>(new[] {(1, 2), (3, 4)}); foreach(var (i, j) in sp) { Console.Write(i); Console.Write(j); } } } ", TestOptions.ReleaseExe); comp = comp.WithReferences(comp.References.Concat(new[] { SystemRuntimeFacadeRef, ValueTupleRef })); CompileAndVerify(comp, expectedOutput: "1234").VerifyIL("Test.Main", @" { // Code size 95 (0x5f) .maxstack 5 .locals init (System.Span<System.ValueTuple<int, int>> V_0, int V_1, int V_2) //i IL_0000: ldc.i4.2 IL_0001: newarr ""System.ValueTuple<int, int>"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.1 IL_0009: ldc.i4.2 IL_000a: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000f: stelem ""System.ValueTuple<int, int>"" IL_0014: dup IL_0015: ldc.i4.1 IL_0016: ldc.i4.3 IL_0017: ldc.i4.4 IL_0018: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_001d: stelem ""System.ValueTuple<int, int>"" IL_0022: newobj ""System.Span<System.ValueTuple<int, int>>..ctor(System.ValueTuple<int, int>[])"" IL_0027: stloc.0 IL_0028: ldc.i4.0 IL_0029: stloc.1 IL_002a: br.s IL_0054 IL_002c: ldloca.s V_0 IL_002e: ldloc.1 IL_002f: call ""ref System.ValueTuple<int, int> System.Span<System.ValueTuple<int, int>>.this[int].get"" IL_0034: ldobj ""System.ValueTuple<int, int>"" IL_0039: dup IL_003a: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003f: stloc.2 IL_0040: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0045: ldloc.2 IL_0046: call ""void System.Console.Write(int)"" IL_004b: call ""void System.Console.Write(int)"" IL_0050: ldloc.1 IL_0051: ldc.i4.1 IL_0052: add IL_0053: stloc.1 IL_0054: ldloc.1 IL_0055: ldloca.s V_0 IL_0057: call ""int System.Span<System.ValueTuple<int, int>>.Length.get"" IL_005c: blt.s IL_002c IL_005e: ret }"); } [Fact] public void TestSpanConvertDebug() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { var sp = new Span<int>(new[] {1, 2, 3}); foreach(byte i in sp) { Console.Write(i); } } } ", TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "123").VerifyIL("Test.Main", @" { // Code size 67 (0x43) .maxstack 4 .locals init (System.Span<int> V_0, //sp System.Span<int> V_1, int V_2, byte V_3) //i IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.3 IL_0004: newarr ""int"" IL_0009: dup IL_000a: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000f: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0014: call ""System.Span<int>..ctor(int[])"" IL_0019: nop IL_001a: ldloc.0 IL_001b: stloc.1 IL_001c: ldc.i4.0 IL_001d: stloc.2 IL_001e: br.s IL_0038 IL_0020: ldloca.s V_1 IL_0022: ldloc.2 IL_0023: call ""ref int System.Span<int>.this[int].get"" IL_0028: ldind.i4 IL_0029: conv.u1 IL_002a: stloc.3 IL_002b: nop IL_002c: ldloc.3 IL_002d: call ""void System.Console.Write(int)"" IL_0032: nop IL_0033: nop IL_0034: ldloc.2 IL_0035: ldc.i4.1 IL_0036: add IL_0037: stloc.2 IL_0038: ldloc.2 IL_0039: ldloca.s V_1 IL_003b: call ""int System.Span<int>.Length.get"" IL_0040: blt.s IL_0020 IL_0042: ret }"); } // Traveled Multi-dimensional jagged arrays [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void TestJaggedArray() { var text = @"using System; public class Test { static void Main(string[] args) { int[][] arr = new int[][] { new int[] { 1, 2 }, new int[] { 4, 5, 6 } }; foreach (int[] outer in arr) { foreach (int i in outer) { Console.WriteLine(i); } } } } "; string expectedOutput = @"1 2 4 5 6"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Optimization to foreach (char c in String) by treating String as a char array [Fact] public void TestString01() { var text = @"using System; public class Test { static void Main(string[] args) { System.String Str = new System.String('\0', 1024); foreach (char C in Str) { } } } "; string expectedOutput = @""; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestString02() { var text = @"using System; public class Test { static public int Main(string[] args) { foreach (var var in ""goo"") { if (!var.GetType().Equals(typeof(char))) { System.Console.WriteLine(-1); return -1; } } return 0; } } "; string expectedOutput = @""; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestString03() { var text = @"using System; public class Test { static public void Main(string[] args) { String Str = null; foreach (char C in Str) { } } } "; string expectedIL = @"{ // Code size 28 (0x1c) .maxstack 2 .locals init (string V_0, int V_1) IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: br.s IL_0012 IL_0006: ldloc.0 IL_0007: ldloc.1 IL_0008: callvirt ""char string.this[int].get"" IL_000d: pop IL_000e: ldloc.1 IL_000f: ldc.i4.1 IL_0010: add IL_0011: stloc.1 IL_0012: ldloc.1 IL_0013: ldloc.0 IL_0014: callvirt ""int string.Length.get"" IL_0019: blt.s IL_0006 IL_001b: ret }"; CompileAndVerify(text).VerifyIL("Test.Main", expectedIL); } // Traversing items in 'Dictionary' [Fact] public void TestDictionary() { var text = @"using System; using System.Collections.Generic; public class Test { static public void Main(string[] args) { Dictionary<int, int> s = new Dictionary<int, int>(); s.Add(1, 2); s.Add(2, 3); s.Add(3, 4); foreach (var pair in s) { Console.WriteLine( pair.Key );} foreach (KeyValuePair<int, int> pair in s) {Console.WriteLine( pair.Value ); } } } "; string expectedOutput = @"1 2 3 2 3 4"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Inner foreach loop referencing the outer foreach loop iteration variable [Fact] public void TestNestedLoop() { var text = @"public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { System.Console.WriteLine(y); } } } } "; string expectedOutput = @"A B C X Y Z"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Breaking from nested Loops [Fact] public void TestBreakInNestedLoop() { var text = @"public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { if (y == 'A') break; else System.Console.WriteLine(y); } System.Console.WriteLine(x); } } } "; string expectedOutput = @"ABC X Y Z XYZ"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Continuing from nested Loops [Fact] public void TestContinueInNestedLoop() { var text = @"public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { if (y == 'C') continue; System.Console.WriteLine(y); } } } } "; string expectedOutput = @"A B X Y Z"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Goto in foreach loops [Fact] public void TestGoto01() { var text = @"public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { System.Console.WriteLine(y); goto stop; } } stop: return; } } "; string expectedOutput = @"A"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestGoto02() { var text = @"public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { System.Console.WriteLine(y); goto outerLoop; } outerLoop: return; } } } "; string expectedOutput = @"A"; CompileAndVerify(text, expectedOutput: expectedOutput); } // 'Return' in foreach [Fact] public void TestReturn() { var text = @"public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { return; } } } "; string expectedIL = @"{ // Code size 39 (0x27) .maxstack 4 .locals init (string[] V_0, int V_1) IL_0000: ldc.i4.2 IL_0001: newarr ""string"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldstr ""ABC"" IL_000d: stelem.ref IL_000e: dup IL_000f: ldc.i4.1 IL_0010: ldstr ""XYZ"" IL_0015: stelem.ref IL_0016: stloc.0 IL_0017: ldc.i4.0 IL_0018: stloc.1 IL_0019: br.s IL_0020 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldelem.ref IL_001e: pop IL_001f: ret IL_0020: ldloc.1 IL_0021: ldloc.0 IL_0022: ldlen IL_0023: conv.i4 IL_0024: blt.s IL_001b IL_0026: ret } "; CompileAndVerify(text).VerifyIL("Test.Main", expectedIL); } // Dynamic works in foreach [Fact] public void TestDynamic() { var text = @"public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (dynamic x in S) { System.Console.WriteLine(x.ToLower()); } } } "; string expectedOutput = @"abc xyz"; CompileAndVerify(text, new[] { CSharpRef }, expectedOutput: expectedOutput); } [Fact] public void TestVar01() { var text = @"using System.Collections.Generic; public class Test { static public void Main(string[] args) { foreach (var var in new List<double> { 1.0, 2.0, 3.0 }) { if (var.GetType().Equals(typeof(double))) { System.Console.WriteLine(true); } } } } "; string expectedOutput = @"True True True"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestVar02() { var text = @" public class Test { static public void Main(string[] args) { foreach (var var in new string[] { ""one"", ""two"", ""three"" }) { if (!var.GetType().Equals(typeof(double))) { System.Console.WriteLine(false); } } } } "; string expectedOutput = @"False False False"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestVar03() { var text = @" public class Test { static public void Main(string[] args) { foreach (var var in new MyClass()) { if (var.GetType().Equals(typeof(int))) { System.Console.WriteLine(true); } } } } class MyClass { public MyEnumerator GetEnumerator() { return new MyEnumerator(); } } class MyEnumerator { int count = 4; public int Current { get { return count; } } public bool MoveNext() { count--; return count != 0; } } "; string expectedOutput = @"True True True"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestQuery() { var text = @" using System.Linq; public class Test { static public void Main(string[] args) { foreach (var x in from x in new[] { 'A', 'B', 'C' } let z = x.ToString() select z into w select w) { System.Console.WriteLine(x.ToLower()); } } } "; string expectedOutput = @"a b c "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: expectedOutput); } [Fact] public void TestYield01() { var text = @" using System.Collections; public class Test { public static void Main(string[] args) { foreach (int i in myClass.Power(2, 8)) { System.Console.WriteLine(""{0}"", i); } } } public class myClass { public static IEnumerable Power(int number, int exponent) { int counter = 0; int result = 1; while (counter++ < exponent) { result = result * number; yield return result; } } } "; string expectedOutput = @"2 4 8 16 32 64 128 256 "; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestYield02() { var text = @" using System.Collections.Generic; public class Test { public static void Main(string[] args) { foreach (int i in FromTo(2,4)) { System.Console.WriteLine(""{0}"", i); } } public static IEnumerable<int> FromTo(int from, int to) { for (int i = from; i <= to; i++) yield return i; } } "; string expectedOutput = @"2 3 4 "; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestYield03() { var text = @" using System.Collections.Generic; public class Test { public static void Main(string[] args) { foreach (var i in EnumerateIt<string>(new List<string>() { ""abc"" })) { System.Console.WriteLine(i); } } public static IEnumerable<T> EnumerateIt<T>(IEnumerable<T> xs) { foreach (T x in xs) yield return x; } } "; string expectedOutput = @"abc"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestYield04() { var text = @" using System.Collections.Generic; public class Test { public static void Main(string[] args) { foreach (int p in EnumerateIt(FromTo(3, 5))) { System.Console.WriteLine(""{0}"", p); } } public static IEnumerable<int> FromTo(int from, int to) { for (int i = from; i <= to; i++) yield return i; } public static IEnumerable<T> EnumerateIt<T>(IEnumerable<T> xs) { foreach (T x in xs) yield return x; } } "; string expectedOutput = @"3 4 5"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestYield05() { var text = @" using System.Collections.Generic; public class Test { public static void Main(string[] args) { foreach (var j in new Gen<double>()) { System.Console.WriteLine(j); } } } public class Gen<T> where T : new() { public IEnumerator<T> GetEnumerator() { yield return new T(); yield return new T(); yield return new T(); } } "; string expectedOutput = @"0 0 0"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestValueTypeIterationVariableCanBeMutatedByInstanceMethods() { const string source = @" struct A { int field; void Set(A a) { this = a; } static void Main() { foreach (var a in new A[1]) { a.Set(new A { field = 5 }); System.Console.Write(a.field); } } }"; CompileAndVerify(source, expectedOutput: "5"); } [Fact, WorkItem(1077204, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077204")] public void TestValueTypeIterationVariableFieldsAreReadonly() { const string source = @" using System; struct A { public B B; static void Main() { A[] array = { default(A) }; foreach (A a in array) { a.B.SetField(5); Console.Write(a.B.Field); } } } struct B { public int Field; public void SetField(int value) { this.Field = value; } }"; CompileAndVerify(source, expectedOutput: "0"); } [Fact] public void TestValueTypeIterationVariableFieldsAreReadonly2() { const string source = @" struct C { public int field; public void SetField(int value) { field = value; } } struct B { public C c; } struct A { B b; static void Main() { foreach (var a in new A[1]) { a.b.c.SetField(5); System.Console.Write(a.b.c.field); } } }"; CompileAndVerify(source, expectedOutput: "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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class ForeachTest : EmitMetadataTestBase { // The loop object must be an array or an object collection [Fact] public void SimpleLoop() { var text = @" using System; public class Test { static void Main(string[] args) { string[] arr = new string[4]; // Initialize arr[0] = ""one""; // Element 1 arr[1] = ""two""; // Element 2 arr[2] = ""three""; // Element 3 arr[3] = ""four""; // Element 4 foreach (string s in arr) { System.Console.WriteLine(s); } } } "; string expectedOutput = @"one two three four"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestIteration() { CompileAndVerify(@" using System; public class Test { public static void Main(string[] args) { unsafe { int* y = null; foreach (var x in new int*[] { y }) { } } } }", options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 33 (0x21) .maxstack 4 .locals init (int* V_0, //y int*[] V_1, int V_2) IL_0000: ldc.i4.0 IL_0001: conv.u IL_0002: stloc.0 IL_0003: ldc.i4.1 IL_0004: newarr ""int*"" IL_0009: dup IL_000a: ldc.i4.0 IL_000b: ldloc.0 IL_000c: stelem.i IL_000d: stloc.1 IL_000e: ldc.i4.0 IL_000f: stloc.2 IL_0010: br.s IL_001a IL_0012: ldloc.1 IL_0013: ldloc.2 IL_0014: ldelem.i IL_0015: pop IL_0016: ldloc.2 IL_0017: ldc.i4.1 IL_0018: add IL_0019: stloc.2 IL_001a: ldloc.2 IL_001b: ldloc.1 IL_001c: ldlen IL_001d: conv.i4 IL_001e: blt.s IL_0012 IL_0020: ret }"); } // Using the Linq as iteration variable [Fact] public void TestLinqInForeach() { var text = @"using System; using System.Linq; public class Test { public static void Main(string[] args) { foreach (int x in from char c in ""abc"" select c) { Console.WriteLine(x); } } }"; string expectedOutput = @"97 98 99"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Empty foreach statement [Fact] public void TestEmptyStatementForeach() { var text = @"class C { static void Main() { foreach (char C in ""abc""); } }"; string expectedIL = @"{ // Code size 32 (0x20) .maxstack 2 .locals init (string V_0, int V_1) IL_0000: ldstr ""abc"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 IL_0008: br.s IL_0016 IL_000a: ldloc.0 IL_000b: ldloc.1 IL_000c: callvirt ""char string.this[int].get"" IL_0011: pop IL_0012: ldloc.1 IL_0013: ldc.i4.1 IL_0014: add IL_0015: stloc.1 IL_0016: ldloc.1 IL_0017: ldloc.0 IL_0018: callvirt ""int string.Length.get"" IL_001d: blt.s IL_000a IL_001f: ret }"; CompileAndVerify(text).VerifyIL("C.Main", expectedIL); } // Foreach value can't be deleted in a loop [Fact] public void TestRemoveValueInForeach() { var text = @"using System.Collections; using System.Collections.Generic; class C { static public void Main() { List<int> arrInt = new List<int>(); arrInt.Add(1); foreach (int i in arrInt) { arrInt.Remove(i);//It will generate error in run-time } } } "; string expectedIL = @"{ // Code size 64 (0x40) .maxstack 2 .locals init (System.Collections.Generic.List<int> V_0, //arrInt System.Collections.Generic.List<int>.Enumerator V_1, int V_2) //i IL_0000: newobj ""System.Collections.Generic.List<int>..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_000d: ldloc.0 IL_000e: callvirt ""System.Collections.Generic.List<int>.Enumerator System.Collections.Generic.List<int>.GetEnumerator()"" IL_0013: stloc.1 .try { IL_0014: br.s IL_0026 IL_0016: ldloca.s V_1 IL_0018: call ""int System.Collections.Generic.List<int>.Enumerator.Current.get"" IL_001d: stloc.2 IL_001e: ldloc.0 IL_001f: ldloc.2 IL_0020: callvirt ""bool System.Collections.Generic.List<int>.Remove(int)"" IL_0025: pop IL_0026: ldloca.s V_1 IL_0028: call ""bool System.Collections.Generic.List<int>.Enumerator.MoveNext()"" IL_002d: brtrue.s IL_0016 IL_002f: leave.s IL_003f } finally { IL_0031: ldloca.s V_1 IL_0033: constrained. ""System.Collections.Generic.List<int>.Enumerator"" IL_0039: callvirt ""void System.IDisposable.Dispose()"" IL_003e: endfinally } IL_003f: ret }"; CompileAndVerify(text).VerifyIL("C.Main", expectedIL); } // With multidimensional arrays, you can use one loop to iterate through the elements [Fact] public void TestMultiDimensionalArray() { var text = @"class T { static public void Main() { int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } }; foreach (int i in numbers2D) { System.Console.WriteLine(i); } } } "; string expectedOutput = @"9 99 3 33 5 55"; CompileAndVerify(text, expectedOutput: expectedOutput); } [WorkItem(540917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540917")] [Fact] public void TestArray() { var text = @"using System; public class Test { static void Main(string[] args) { string[] arr = new string[4]; // Initialize arr[0] = ""one""; // Element 1 arr[1] = ""two""; // Element 2 foreach (string s in arr) { System.Console.WriteLine(s); } } } "; string expectedIL = @" { // Code size 46 (0x2e) .maxstack 4 .locals init (string[] V_0, int V_1) IL_0000: ldc.i4.4 IL_0001: newarr ""string"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldstr ""one"" IL_000d: stelem.ref IL_000e: dup IL_000f: ldc.i4.1 IL_0010: ldstr ""two"" IL_0015: stelem.ref IL_0016: stloc.0 IL_0017: ldc.i4.0 IL_0018: stloc.1 IL_0019: br.s IL_0027 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldelem.ref IL_001e: call ""void System.Console.WriteLine(string)"" IL_0023: ldloc.1 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.1 IL_0027: ldloc.1 IL_0028: ldloc.0 IL_0029: ldlen IL_002a: conv.i4 IL_002b: blt.s IL_001b IL_002d: ret }"; CompileAndVerify(text).VerifyIL("Test.Main", expectedIL); } [Fact] public void TestSpan() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { var sp = new Span<int>(new[] {1, 2, 3}); foreach(var i in sp) { Console.Write(i); } } } ", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "123").VerifyIL("Test.Main", @" { // Code size 56 (0x38) .maxstack 3 .locals init (System.Span<int> V_0, int V_1) IL_0000: ldc.i4.3 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000c: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0011: newobj ""System.Span<int>..ctor(int[])"" IL_0016: stloc.0 IL_0017: ldc.i4.0 IL_0018: stloc.1 IL_0019: br.s IL_002d IL_001b: ldloca.s V_0 IL_001d: ldloc.1 IL_001e: call ""ref int System.Span<int>.this[int].get"" IL_0023: ldind.i4 IL_0024: call ""void System.Console.Write(int)"" IL_0029: ldloc.1 IL_002a: ldc.i4.1 IL_002b: add IL_002c: stloc.1 IL_002d: ldloc.1 IL_002e: ldloca.s V_0 IL_0030: call ""int System.Span<int>.Length.get"" IL_0035: blt.s IL_001b IL_0037: ret }"); } [Fact] public void TestSpanSideeffectingLoopBody() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { var sp = new Span<int>(new[] {1, 2, 3}); foreach(var i in sp) { Console.Write(i); sp = default; } Console.Write(sp.Length); } } ", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "1230").VerifyIL("Test.Main", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (System.Span<int> V_0, //sp System.Span<int> V_1, int V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.3 IL_0003: newarr ""int"" IL_0008: dup IL_0009: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000e: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0013: call ""System.Span<int>..ctor(int[])"" IL_0018: ldloc.0 IL_0019: stloc.1 IL_001a: ldc.i4.0 IL_001b: stloc.2 IL_001c: br.s IL_0038 IL_001e: ldloca.s V_1 IL_0020: ldloc.2 IL_0021: call ""ref int System.Span<int>.this[int].get"" IL_0026: ldind.i4 IL_0027: call ""void System.Console.Write(int)"" IL_002c: ldloca.s V_0 IL_002e: initobj ""System.Span<int>"" IL_0034: ldloc.2 IL_0035: ldc.i4.1 IL_0036: add IL_0037: stloc.2 IL_0038: ldloc.2 IL_0039: ldloca.s V_1 IL_003b: call ""int System.Span<int>.Length.get"" IL_0040: blt.s IL_001e IL_0042: ldloca.s V_0 IL_0044: call ""int System.Span<int>.Length.get"" IL_0049: call ""void System.Console.Write(int)"" IL_004e: ret }"); } [Fact] public void TestReadOnlySpan() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { var sp = new ReadOnlySpan<Color>(new [] {Color.Red, Color.Green, Color.Blue}); foreach(var i in sp) { Console.Write(i); } } } ", TestOptions.ReleaseExe); //NOTE: the verification error is expected. Wrapping of literals into readonly spans uses unsafe Span.ctor. CompileAndVerify(comp, expectedOutput: "RedGreenBlue", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 50 (0x32) .maxstack 2 .locals init (System.ReadOnlySpan<System.Color> V_0, int V_1) IL_0000: ldsflda ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=3 <PrivateImplementationDetails>.AE4B3280E56E2FAF83F414A6E3DABE9D5FBE18976544C05FED121ACCB85B53FC"" IL_0005: ldc.i4.3 IL_0006: newobj ""System.ReadOnlySpan<System.Color>..ctor(void*, int)"" IL_000b: stloc.0 IL_000c: ldc.i4.0 IL_000d: stloc.1 IL_000e: br.s IL_0027 IL_0010: ldloca.s V_0 IL_0012: ldloc.1 IL_0013: call ""ref readonly System.Color System.ReadOnlySpan<System.Color>.this[int].get"" IL_0018: ldind.i1 IL_0019: box ""System.Color"" IL_001e: call ""void System.Console.Write(object)"" IL_0023: ldloc.1 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.1 IL_0027: ldloc.1 IL_0028: ldloca.s V_0 IL_002a: call ""int System.ReadOnlySpan<System.Color>.Length.get"" IL_002f: blt.s IL_0010 IL_0031: ret }"); } [Fact] public void TestReadOnlySpanString() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { var sp = (ReadOnlySpan<char>)""hello""; foreach(var i in sp) { Console.Write(i); } } } ", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "hello", verify: Verification.Passes).VerifyIL("Test.Main", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (System.ReadOnlySpan<char> V_0, int V_1) IL_0000: ldstr ""hello"" IL_0005: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.0 IL_000c: stloc.1 IL_000d: br.s IL_0021 IL_000f: ldloca.s V_0 IL_0011: ldloc.1 IL_0012: call ""ref readonly char System.ReadOnlySpan<char>.this[int].get"" IL_0017: ldind.u2 IL_0018: call ""void System.Console.Write(char)"" IL_001d: ldloc.1 IL_001e: ldc.i4.1 IL_001f: add IL_0020: stloc.1 IL_0021: ldloc.1 IL_0022: ldloca.s V_0 IL_0024: call ""int System.ReadOnlySpan<char>.Length.get"" IL_0029: blt.s IL_000f IL_002b: ret }"); } [Fact] public void TestReadOnlySpan2() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { foreach(var i in (ReadOnlySpan<byte>)new byte[] {1, 2, 3}) { Console.Write(i); } } } ", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "123", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 45 (0x2d) .maxstack 2 .locals init (System.ReadOnlySpan<byte> V_0, int V_1) IL_0000: ldsflda ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=3 <PrivateImplementationDetails>.039058C6F2C0CB492C533B0A4D14EF77CC0F78ABCCCED5287D84A1A2011CFB81"" IL_0005: ldc.i4.3 IL_0006: newobj ""System.ReadOnlySpan<byte>..ctor(void*, int)"" IL_000b: stloc.0 IL_000c: ldc.i4.0 IL_000d: stloc.1 IL_000e: br.s IL_0022 IL_0010: ldloca.s V_0 IL_0012: ldloc.1 IL_0013: call ""ref readonly byte System.ReadOnlySpan<byte>.this[int].get"" IL_0018: ldind.u1 IL_0019: call ""void System.Console.Write(int)"" IL_001e: ldloc.1 IL_001f: ldc.i4.1 IL_0020: add IL_0021: stloc.1 IL_0022: ldloc.1 IL_0023: ldloca.s V_0 IL_0025: call ""int System.ReadOnlySpan<byte>.Length.get"" IL_002a: blt.s IL_0010 IL_002c: ret }"); } [Fact] public void TestSpanNoIndexer() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { var sp = new Span<int>(new[] {1, 2, 3}); foreach(var i in sp) { Console.Write(i); } } } ", TestOptions.ReleaseExe); comp.MakeMemberMissing(WellKnownMember.System_Span_T__get_Item); CompileAndVerify(comp, expectedOutput: "123").VerifyIL("Test.Main", @" { // Code size 57 (0x39) .maxstack 4 .locals init (System.Span<int> V_0, //sp System.Span<int>.Enumerator V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.3 IL_0003: newarr ""int"" IL_0008: dup IL_0009: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000e: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0013: call ""System.Span<int>..ctor(int[])"" IL_0018: ldloca.s V_0 IL_001a: call ""System.Span<int>.Enumerator System.Span<int>.GetEnumerator()"" IL_001f: stloc.1 IL_0020: br.s IL_002f IL_0022: ldloca.s V_1 IL_0024: call ""ref int System.Span<int>.Enumerator.Current.get"" IL_0029: ldind.i4 IL_002a: call ""void System.Console.Write(int)"" IL_002f: ldloca.s V_1 IL_0031: call ""bool System.Span<int>.Enumerator.MoveNext()"" IL_0036: brtrue.s IL_0022 IL_0038: ret }"); } [Fact] public void TestSpanValIndexer() { var comp = CreateEmptyCompilation(@" using System; class Test { public static void Main() { var sp = new ReadOnlySpan<int>(new[] {1, 2, 3}); foreach(var i in sp) { Console.Write(i); } } } namespace System { public readonly ref struct ReadOnlySpan<T> { private readonly T[] arr; public T this[int i] => arr[i]; public int Length { get; } public ReadOnlySpan(T[] arr) { this.arr = arr; this.Length = arr.Length; } public Enumerator GetEnumerator() => new Enumerator(this); public ref struct Enumerator { private readonly ReadOnlySpan<T> _span; private int _index; internal Enumerator(ReadOnlySpan<T> span) { _span = span; _index = -1; } public bool MoveNext() { int index = _index + 1; if (index < _span.Length) { _index = index; return true; } return false; } public T Current { get => _span[_index]; } } } } ", references: new[] { MscorlibRef_v4_0_30316_17626 }, TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "123", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 56 (0x38) .maxstack 4 .locals init (System.ReadOnlySpan<int> V_0, //sp System.ReadOnlySpan<int>.Enumerator V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.3 IL_0003: newarr ""int"" IL_0008: dup IL_0009: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000e: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0013: call ""System.ReadOnlySpan<int>..ctor(int[])"" IL_0018: ldloca.s V_0 IL_001a: call ""System.ReadOnlySpan<int>.Enumerator System.ReadOnlySpan<int>.GetEnumerator()"" IL_001f: stloc.1 IL_0020: br.s IL_002e IL_0022: ldloca.s V_1 IL_0024: call ""int System.ReadOnlySpan<int>.Enumerator.Current.get"" IL_0029: call ""void System.Console.Write(int)"" IL_002e: ldloca.s V_1 IL_0030: call ""bool System.ReadOnlySpan<int>.Enumerator.MoveNext()"" IL_0035: brtrue.s IL_0022 IL_0037: ret }"); } [Fact] public void TestSpanConvert() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { var sp = new Span<int>(new[] {1, 2, 3}); foreach(byte i in sp) { Console.Write(i); } } } ", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "123").VerifyIL("Test.Main", @" { // Code size 57 (0x39) .maxstack 3 .locals init (System.Span<int> V_0, int V_1) IL_0000: ldc.i4.3 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000c: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0011: newobj ""System.Span<int>..ctor(int[])"" IL_0016: stloc.0 IL_0017: ldc.i4.0 IL_0018: stloc.1 IL_0019: br.s IL_002e IL_001b: ldloca.s V_0 IL_001d: ldloc.1 IL_001e: call ""ref int System.Span<int>.this[int].get"" IL_0023: ldind.i4 IL_0024: conv.u1 IL_0025: call ""void System.Console.Write(int)"" IL_002a: ldloc.1 IL_002b: ldc.i4.1 IL_002c: add IL_002d: stloc.1 IL_002e: ldloc.1 IL_002f: ldloca.s V_0 IL_0031: call ""int System.Span<int>.Length.get"" IL_0036: blt.s IL_001b IL_0038: ret }"); } [Fact] public void TestSpanDeconstruct() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { static void Main(string[] args) { var sp = new Span<(int, int)>(new[] {(1, 2), (3, 4)}); foreach(var (i, j) in sp) { Console.Write(i); Console.Write(j); } } } ", TestOptions.ReleaseExe); comp = comp.WithReferences(comp.References.Concat(new[] { SystemRuntimeFacadeRef, ValueTupleRef })); CompileAndVerify(comp, expectedOutput: "1234").VerifyIL("Test.Main", @" { // Code size 95 (0x5f) .maxstack 5 .locals init (System.Span<System.ValueTuple<int, int>> V_0, int V_1, int V_2) //i IL_0000: ldc.i4.2 IL_0001: newarr ""System.ValueTuple<int, int>"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.1 IL_0009: ldc.i4.2 IL_000a: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000f: stelem ""System.ValueTuple<int, int>"" IL_0014: dup IL_0015: ldc.i4.1 IL_0016: ldc.i4.3 IL_0017: ldc.i4.4 IL_0018: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_001d: stelem ""System.ValueTuple<int, int>"" IL_0022: newobj ""System.Span<System.ValueTuple<int, int>>..ctor(System.ValueTuple<int, int>[])"" IL_0027: stloc.0 IL_0028: ldc.i4.0 IL_0029: stloc.1 IL_002a: br.s IL_0054 IL_002c: ldloca.s V_0 IL_002e: ldloc.1 IL_002f: call ""ref System.ValueTuple<int, int> System.Span<System.ValueTuple<int, int>>.this[int].get"" IL_0034: ldobj ""System.ValueTuple<int, int>"" IL_0039: dup IL_003a: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003f: stloc.2 IL_0040: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0045: ldloc.2 IL_0046: call ""void System.Console.Write(int)"" IL_004b: call ""void System.Console.Write(int)"" IL_0050: ldloc.1 IL_0051: ldc.i4.1 IL_0052: add IL_0053: stloc.1 IL_0054: ldloc.1 IL_0055: ldloca.s V_0 IL_0057: call ""int System.Span<System.ValueTuple<int, int>>.Length.get"" IL_005c: blt.s IL_002c IL_005e: ret }"); } [Fact] public void TestSpanConvertDebug() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { var sp = new Span<int>(new[] {1, 2, 3}); foreach(byte i in sp) { Console.Write(i); } } } ", TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "123").VerifyIL("Test.Main", @" { // Code size 67 (0x43) .maxstack 4 .locals init (System.Span<int> V_0, //sp System.Span<int> V_1, int V_2, byte V_3) //i IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.3 IL_0004: newarr ""int"" IL_0009: dup IL_000a: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000f: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0014: call ""System.Span<int>..ctor(int[])"" IL_0019: nop IL_001a: ldloc.0 IL_001b: stloc.1 IL_001c: ldc.i4.0 IL_001d: stloc.2 IL_001e: br.s IL_0038 IL_0020: ldloca.s V_1 IL_0022: ldloc.2 IL_0023: call ""ref int System.Span<int>.this[int].get"" IL_0028: ldind.i4 IL_0029: conv.u1 IL_002a: stloc.3 IL_002b: nop IL_002c: ldloc.3 IL_002d: call ""void System.Console.Write(int)"" IL_0032: nop IL_0033: nop IL_0034: ldloc.2 IL_0035: ldc.i4.1 IL_0036: add IL_0037: stloc.2 IL_0038: ldloc.2 IL_0039: ldloca.s V_1 IL_003b: call ""int System.Span<int>.Length.get"" IL_0040: blt.s IL_0020 IL_0042: ret }"); } // Traveled Multi-dimensional jagged arrays [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void TestJaggedArray() { var text = @"using System; public class Test { static void Main(string[] args) { int[][] arr = new int[][] { new int[] { 1, 2 }, new int[] { 4, 5, 6 } }; foreach (int[] outer in arr) { foreach (int i in outer) { Console.WriteLine(i); } } } } "; string expectedOutput = @"1 2 4 5 6"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Optimization to foreach (char c in String) by treating String as a char array [Fact] public void TestString01() { var text = @"using System; public class Test { static void Main(string[] args) { System.String Str = new System.String('\0', 1024); foreach (char C in Str) { } } } "; string expectedOutput = @""; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestString02() { var text = @"using System; public class Test { static public int Main(string[] args) { foreach (var var in ""goo"") { if (!var.GetType().Equals(typeof(char))) { System.Console.WriteLine(-1); return -1; } } return 0; } } "; string expectedOutput = @""; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestString03() { var text = @"using System; public class Test { static public void Main(string[] args) { String Str = null; foreach (char C in Str) { } } } "; string expectedIL = @"{ // Code size 28 (0x1c) .maxstack 2 .locals init (string V_0, int V_1) IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: br.s IL_0012 IL_0006: ldloc.0 IL_0007: ldloc.1 IL_0008: callvirt ""char string.this[int].get"" IL_000d: pop IL_000e: ldloc.1 IL_000f: ldc.i4.1 IL_0010: add IL_0011: stloc.1 IL_0012: ldloc.1 IL_0013: ldloc.0 IL_0014: callvirt ""int string.Length.get"" IL_0019: blt.s IL_0006 IL_001b: ret }"; CompileAndVerify(text).VerifyIL("Test.Main", expectedIL); } // Traversing items in 'Dictionary' [Fact] public void TestDictionary() { var text = @"using System; using System.Collections.Generic; public class Test { static public void Main(string[] args) { Dictionary<int, int> s = new Dictionary<int, int>(); s.Add(1, 2); s.Add(2, 3); s.Add(3, 4); foreach (var pair in s) { Console.WriteLine( pair.Key );} foreach (KeyValuePair<int, int> pair in s) {Console.WriteLine( pair.Value ); } } } "; string expectedOutput = @"1 2 3 2 3 4"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Inner foreach loop referencing the outer foreach loop iteration variable [Fact] public void TestNestedLoop() { var text = @"public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { System.Console.WriteLine(y); } } } } "; string expectedOutput = @"A B C X Y Z"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Breaking from nested Loops [Fact] public void TestBreakInNestedLoop() { var text = @"public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { if (y == 'A') break; else System.Console.WriteLine(y); } System.Console.WriteLine(x); } } } "; string expectedOutput = @"ABC X Y Z XYZ"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Continuing from nested Loops [Fact] public void TestContinueInNestedLoop() { var text = @"public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { if (y == 'C') continue; System.Console.WriteLine(y); } } } } "; string expectedOutput = @"A B X Y Z"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Goto in foreach loops [Fact] public void TestGoto01() { var text = @"public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { System.Console.WriteLine(y); goto stop; } } stop: return; } } "; string expectedOutput = @"A"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestGoto02() { var text = @"public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { System.Console.WriteLine(y); goto outerLoop; } outerLoop: return; } } } "; string expectedOutput = @"A"; CompileAndVerify(text, expectedOutput: expectedOutput); } // 'Return' in foreach [Fact] public void TestReturn() { var text = @"public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { return; } } } "; string expectedIL = @"{ // Code size 39 (0x27) .maxstack 4 .locals init (string[] V_0, int V_1) IL_0000: ldc.i4.2 IL_0001: newarr ""string"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldstr ""ABC"" IL_000d: stelem.ref IL_000e: dup IL_000f: ldc.i4.1 IL_0010: ldstr ""XYZ"" IL_0015: stelem.ref IL_0016: stloc.0 IL_0017: ldc.i4.0 IL_0018: stloc.1 IL_0019: br.s IL_0020 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldelem.ref IL_001e: pop IL_001f: ret IL_0020: ldloc.1 IL_0021: ldloc.0 IL_0022: ldlen IL_0023: conv.i4 IL_0024: blt.s IL_001b IL_0026: ret } "; CompileAndVerify(text).VerifyIL("Test.Main", expectedIL); } // Dynamic works in foreach [Fact] public void TestDynamic() { var text = @"public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (dynamic x in S) { System.Console.WriteLine(x.ToLower()); } } } "; string expectedOutput = @"abc xyz"; CompileAndVerify(text, new[] { CSharpRef }, expectedOutput: expectedOutput); } [Fact] public void TestVar01() { var text = @"using System.Collections.Generic; public class Test { static public void Main(string[] args) { foreach (var var in new List<double> { 1.0, 2.0, 3.0 }) { if (var.GetType().Equals(typeof(double))) { System.Console.WriteLine(true); } } } } "; string expectedOutput = @"True True True"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestVar02() { var text = @" public class Test { static public void Main(string[] args) { foreach (var var in new string[] { ""one"", ""two"", ""three"" }) { if (!var.GetType().Equals(typeof(double))) { System.Console.WriteLine(false); } } } } "; string expectedOutput = @"False False False"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestVar03() { var text = @" public class Test { static public void Main(string[] args) { foreach (var var in new MyClass()) { if (var.GetType().Equals(typeof(int))) { System.Console.WriteLine(true); } } } } class MyClass { public MyEnumerator GetEnumerator() { return new MyEnumerator(); } } class MyEnumerator { int count = 4; public int Current { get { return count; } } public bool MoveNext() { count--; return count != 0; } } "; string expectedOutput = @"True True True"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestQuery() { var text = @" using System.Linq; public class Test { static public void Main(string[] args) { foreach (var x in from x in new[] { 'A', 'B', 'C' } let z = x.ToString() select z into w select w) { System.Console.WriteLine(x.ToLower()); } } } "; string expectedOutput = @"a b c "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: expectedOutput); } [Fact] public void TestYield01() { var text = @" using System.Collections; public class Test { public static void Main(string[] args) { foreach (int i in myClass.Power(2, 8)) { System.Console.WriteLine(""{0}"", i); } } } public class myClass { public static IEnumerable Power(int number, int exponent) { int counter = 0; int result = 1; while (counter++ < exponent) { result = result * number; yield return result; } } } "; string expectedOutput = @"2 4 8 16 32 64 128 256 "; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestYield02() { var text = @" using System.Collections.Generic; public class Test { public static void Main(string[] args) { foreach (int i in FromTo(2,4)) { System.Console.WriteLine(""{0}"", i); } } public static IEnumerable<int> FromTo(int from, int to) { for (int i = from; i <= to; i++) yield return i; } } "; string expectedOutput = @"2 3 4 "; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestYield03() { var text = @" using System.Collections.Generic; public class Test { public static void Main(string[] args) { foreach (var i in EnumerateIt<string>(new List<string>() { ""abc"" })) { System.Console.WriteLine(i); } } public static IEnumerable<T> EnumerateIt<T>(IEnumerable<T> xs) { foreach (T x in xs) yield return x; } } "; string expectedOutput = @"abc"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestYield04() { var text = @" using System.Collections.Generic; public class Test { public static void Main(string[] args) { foreach (int p in EnumerateIt(FromTo(3, 5))) { System.Console.WriteLine(""{0}"", p); } } public static IEnumerable<int> FromTo(int from, int to) { for (int i = from; i <= to; i++) yield return i; } public static IEnumerable<T> EnumerateIt<T>(IEnumerable<T> xs) { foreach (T x in xs) yield return x; } } "; string expectedOutput = @"3 4 5"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestYield05() { var text = @" using System.Collections.Generic; public class Test { public static void Main(string[] args) { foreach (var j in new Gen<double>()) { System.Console.WriteLine(j); } } } public class Gen<T> where T : new() { public IEnumerator<T> GetEnumerator() { yield return new T(); yield return new T(); yield return new T(); } } "; string expectedOutput = @"0 0 0"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestValueTypeIterationVariableCanBeMutatedByInstanceMethods() { const string source = @" struct A { int field; void Set(A a) { this = a; } static void Main() { foreach (var a in new A[1]) { a.Set(new A { field = 5 }); System.Console.Write(a.field); } } }"; CompileAndVerify(source, expectedOutput: "5"); } [Fact, WorkItem(1077204, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077204")] public void TestValueTypeIterationVariableFieldsAreReadonly() { const string source = @" using System; struct A { public B B; static void Main() { A[] array = { default(A) }; foreach (A a in array) { a.B.SetField(5); Console.Write(a.B.Field); } } } struct B { public int Field; public void SetField(int value) { this.Field = value; } }"; CompileAndVerify(source, expectedOutput: "0"); } [Fact] public void TestValueTypeIterationVariableFieldsAreReadonly2() { const string source = @" struct C { public int field; public void SetField(int value) { field = value; } } struct B { public C c; } struct A { B b; static void Main() { foreach (var a in new A[1]) { a.b.c.SetField(5); System.Console.Write(a.b.c.field); } } }"; CompileAndVerify(source, expectedOutput: "0"); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/WithSystemNumerics.csproj
<?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. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject</RootNamespace> <AssemblyName>CSharpProject</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Numerics" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
<?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. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject</RootNamespace> <AssemblyName>CSharpProject</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Numerics" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/VisualBasicTest/Diagnostics/GenerateEnumMember/GenerateEnumMemberTests.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.CodeFixes Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEnumMember Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateEnumMember Public Class GenerateEnumMemberTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New GenerateEnumMemberCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoEmpty() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Red|]) End Sub End Module Enum Color End Enum", "Module Program Sub Main(args As String()) Goo(Color.Red) End Sub End Module Enum Color Red End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoEnumWithSingleMember() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Green|]) End Sub End Module Enum Color Red End Enum", "Module Program Sub Main(args As String()) Goo(Color.Green) End Sub End Module Enum Color Red Green End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithValue() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Green|]) End Sub End Module Enum Color Red = 1 End Enum", "Module Program Sub Main(args As String()) Goo(Color.Green) End Sub End Module Enum Color Red = 1 Green = 2 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateBinaryLiteral() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Green|]) End Sub End Module Enum Color Red = &B01 End Enum", "Module Program Sub Main(args As String()) Goo(Color.Green) End Sub End Module Enum Color Red = &B01 Green = &B10 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoLinearIncreasingSequence() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub End Module Enum Color Red = 1 Green = 2 End Enum", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub End Module Enum Color Red = 1 Green = 2 Blue = 3 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoGeometricSequence() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Purple|]) End Sub End Module Enum Color Red = 1 Green = 2 Blue = 4 End Enum", "Module Program Sub Main(args As String()) Goo(Color.Purple) End Sub End Module Enum Color Red = 1 Green = 2 Blue = 4 Purple = 8 End Enum") End Function <WorkItem(540540, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540540")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithIntegerMaxValue() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub End Module Enum Color Red Green = Integer.MaxValue End Enum", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub End Module Enum Color Red Green = Integer.MaxValue Blue = Integer.MinValue End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestUnsigned16BitEnums() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) [|Color.Green|] End Sub End Module Enum Color As UShort Red = 65535 End Enum", "Module Program Sub Main(args As String()) Color.Green End Sub End Module Enum Color As UShort Red = 65535 Green = 0 End Enum") End Function <WorkItem(540546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540546")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateEnumMemberOfTypeLong() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub End Module Enum Color As Long Red = Long.MinValue End Enum", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub End Module Enum Color As Long Red = Long.MinValue Blue = -9223372036854775807 End Enum") End Function <WorkItem(540636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540636")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithLongMaxValueInHex() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = &H7FFFFFFFFFFFFFFF End Enum", "Class Program Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = &H7FFFFFFFFFFFFFFF Blue = &H8000000000000000 End Enum") End Function <WorkItem(540638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540638")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithLongMinValueInHex() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = &H8000000000000000 End Enum", "Class Program Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = &H8000000000000000 Blue = &H8000000000000001 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterNegativeLongInHex() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = &HFFFFFFFFFFFFFFFF End Enum", "Class Program Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = &HFFFFFFFFFFFFFFFF Blue = &H0 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterPositiveLongInHex() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Color.Orange|] End Sub End Class Enum Color As Long Red = &HFFFFFFFFFFFFFFFF Blue = &H0 End Enum", "Class Program Sub Main(args As String()) Color.Orange End Sub End Class Enum Color As Long Red = &HFFFFFFFFFFFFFFFF Blue = &H0 Orange = &H1 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterPositiveLongExprInHex() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = &H414 / 2 End Enum", "Class Program Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = &H414 / 2 Blue = 523 End Enum") End Function <WorkItem(540632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540632")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithULongMaxValue() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As ULong Red = ULong.MaxValue End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As ULong Red = ULong.MaxValue Blue = 0 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestNegativeRangeIn64BitSignedEnums() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) [|Color.Green|] End Sub End Module Enum Color As Long Red = -10 End Enum", "Module Program Sub Main(args As String()) Color.Green End Sub End Module Enum Color As Long Red = -10 Green = -9 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestUnaryMinusOnUInteger1() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As UInteger Red = -(0 - UInteger.MaxValue) End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As UInteger Red = -(0 - UInteger.MaxValue) Blue = 0 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestDoubleUnaryMinusOnUInteger() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As UInteger Red = --(UInteger.MaxValue - 1) End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As UInteger Red = --(UInteger.MaxValue - 1) Blue = UInteger.MaxValue End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestDoubleUnaryMinusOnUInteger1() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Green|] End Sub End Class Enum Color As UInteger Red = --(UInteger.MaxValue - 1) Blue = 4294967295 End Enum", "Class A Sub Main(args As String()) Color.Green End Sub End Class Enum Color As UInteger Red = --(UInteger.MaxValue - 1) Blue = 4294967295 Green = 0 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateWithImplicitValues() As Task ' Red is implicitly assigned to 0, Green is implicitly Red + 1, So Blue must be 2. Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) [|Color.Blue|] End Sub End Module Enum Color Red Green Yellow = -1 End Enum", "Module Program Sub Main(args As String()) Color.Blue End Sub End Module Enum Color Red Green Yellow = -1 Blue = 2 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateWithImplicitValues2() As Task Await TestInRegularAndScriptAsync( "Class B Sub Main(args As String()) [|Color.Grey|] End Sub End Class Enum Color Red Green = 10 Blue End Enum", "Class B Sub Main(args As String()) Color.Grey End Sub End Class Enum Color Red Green = 10 Blue Grey End Enum") End Function <WorkItem(540549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540549")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestNoExtraneousStatementTerminatorBeforeCommentedMember() As Task Dim code = <Text>Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub End Module Enum Color Red 'Blue End Enum</Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub End Module Enum Color Red Blue 'Blue End Enum</Text>.Value.Replace(vbLf, vbCrLf) Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(540552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540552")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithMinValue() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub End Module Enum Color Red = Integer.MinValue End Enum", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub End Module Enum Color Red = Integer.MinValue Blue = -2147483647 End Enum") End Function <WorkItem(540553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540553")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithMinValuePlusConstant() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub End Module Enum Color Red = Integer.MinValue + 100 End Enum", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub End Module Enum Color Red = Integer.MinValue + 100 Blue = -2147483547 End Enum") End Function <WorkItem(540556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540556")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithByteMaxValue() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub End Module Enum Color As Byte Red = 255 End Enum", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub End Module Enum Color As Byte Red = 255 Blue = 0 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoNegativeSByteInOctal() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As SByte Red = &O1777777777777777777777 End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As SByte Red = &O1777777777777777777777 Blue = &O0 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoPositiveSByteInOctal1() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As SByte Red = &O0 End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As SByte Red = &O0 Blue = &O1 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoPositiveSByteInOctal2() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As SByte Red = &O176 End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As SByte Red = &O176 Blue = &O177 End Enum") End Function <WorkItem(540631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540631")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithSByteMaxValueInOctal() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As SByte Red = &O177 End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As SByte Red = &O177 Blue = &O1777777777777777777600 End Enum") End Function <WorkItem(528207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528207")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestAbsenceOfFixWhenImportingEnums() As Task Await TestMissingInRegularAndScriptAsync( "Imports Color Module Program Sub Main(args As String()) Goo([|Blue|]) End Sub End Module Enum Color As Byte Red End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestPresenceOfFixWhenImportingEnumsYetFullyQualifyingThem() As Task Await TestInRegularAndScriptAsync( "Imports Color Module Program Sub Main(args As String()) Goo([|Color.Green|]) End Sub End Module Enum Color As Long Red = -10 End Enum", "Imports Color Module Program Sub Main(args As String()) Goo(Color.Green) End Sub End Module Enum Color As Long Red = -10 Green = -9 End Enum") End Function <WorkItem(540585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540585")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoBitshiftEnum() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub Enum Color Red = 1 << 0 Green = 1 << 1 Orange = 1 << 2 End Enum End Module", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub Enum Color Red = 1 << 0 Green = 1 << 1 Orange = 1 << 2 Blue = 1 << 3 End Enum End Module") End Function <WorkItem(540566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540566")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestKeywordName() As Task Await TestInRegularAndScriptAsync( "Imports Color Module Program Sub Main(args As String()) Goo([|Color.Enum|]) End Sub End Module Enum Color As Byte Red End Enum", "Imports Color Module Program Sub Main(args As String()) Goo(Color.Enum) End Sub End Module Enum Color As Byte Red [Enum] End Enum") End Function <WorkItem(540547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540547")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestStandaloneReference() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) [|Color.Blue|] End Sub End Module Enum Color As Integer Red = Integer.MinValue Green = 1 End Enum", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Color.Blue End Sub End Module Enum Color As Integer Red = Integer.MinValue Green = 1 Blue = 2 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestCircularEnumsForErrorTolerance() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) [|Circular.C|] End Sub End Module Enum Circular A = B B End Enum", "Module Program Sub Main(args As String()) Circular.C End Sub End Module Enum Circular A = B B C End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestEnumWithIncorrectValueForErrorTolerance() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) [|Color.Green|] End Sub End Module Enum Color As Byte Red = -2 End Enum", "Module Program Sub Main(args As String()) Color.Green End Sub End Module Enum Color As Byte Red = -2 Green End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestHexValues() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) [|RenderType.LastViewedPage|] End Sub End Module <FlagsAttribute()> Enum RenderType None = &H0 DataUri = &H1 GZip = &H2 ContentPage = &H4 ViewPage = &H8 HomePage = &H10 End Enum", "Module Program Sub Main(args As String()) RenderType.LastViewedPage End Sub End Module <FlagsAttribute()> Enum RenderType None = &H0 DataUri = &H1 GZip = &H2 ContentPage = &H4 ViewPage = &H8 HomePage = &H10 LastViewedPage = &H20 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoShadowedEnum() As Task Await TestInRegularAndScriptAsync( "Class B Inherits A Sub Main(args As String()) [|BaseColors.Blue|] End Sub Shadows Enum BaseColors Orange = 3 End Enum End Class Public Class A Public Enum BaseColors Red = 1 Green = 2 End Enum End Class", "Class B Inherits A Sub Main(args As String()) BaseColors.Blue End Sub Shadows Enum BaseColors Orange = 3 Blue = 4 End Enum End Class Public Class A Public Enum BaseColors Red = 1 Green = 2 End Enum End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoDerivedEnumMissingShadowsKeyword() As Task Await TestInRegularAndScriptAsync( "Class B Inherits A Sub Main(args As String()) [|BaseColors.Blue|] End Sub Enum BaseColors Orange = 3 End Enum End Class Public Class A Public Enum BaseColors Red = 1 Green = 2 End Enum End Class", "Class B Inherits A Sub Main(args As String()) BaseColors.Blue End Sub Enum BaseColors Orange = 3 Blue = 4 End Enum End Class Public Class A Public Enum BaseColors Red = 1 Green = 2 End Enum End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoBaseEnum() As Task Await TestInRegularAndScriptAsync( "Class B Inherits A Sub Main(args As String()) [|BaseColors.Blue|] End Sub End Class Public Class A Public Enum BaseColors Red = 1 Green = 2 End Enum End Class", "Class B Inherits A Sub Main(args As String()) BaseColors.Blue End Sub End Class Public Class A Public Enum BaseColors Red = 1 Green = 2 Blue = 3 End Enum End Class") End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestErrorToleranceWithStrictSemantics() As Task Await TestInRegularAndScriptAsync( "Option Strict On Class B Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = 1.5 Green = 2.3 Orange = 3.3 End Enum", "Option Strict On Class B Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = 1.5 Green = 2.3 Orange = 3.3 Blue = 4 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGeometricSequenceWithTypeConversions() As Task Await TestInRegularAndScriptAsync( "Option Strict On Class B Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = CLng(1.5) Green = CLng(2.3) Orange = CLng(3.9) End Enum", "Option Strict On Class B Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = CLng(1.5) Green = CLng(2.3) Orange = CLng(3.9) Blue = 8 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestLinearSequenceWithTypeConversions() As Task Await TestInRegularAndScriptAsync( "Option Strict On Class B Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = CLng(1.5) Green = CLng(2.3) Orange = CLng(4.9) End Enum", "Option Strict On Class B Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = CLng(1.5) Green = CLng(2.3) Orange = CLng(4.9) Blue = 6 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerationWhenMembersShareValues() As Task Await TestInRegularAndScriptAsync( "Option Strict On Class B Sub Main(args As String()) [|Color.Grey|] End Sub End Class Enum Color Red Green Blue Max = Blue End Enum", "Option Strict On Class B Sub Main(args As String()) Color.Grey End Sub End Class Enum Color Red Green Blue Max = Blue Grey = 3 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestInvokeFromAddAssignmentStatement() As Task Await TestInRegularAndScriptAsync( "Class B Sub Main(args As String()) Dim a As Integer = 1 a += [|Color.Grey|] End Sub End Class Enum Color Red Green = 10 Blue End Enum", "Class B Sub Main(args As String()) Dim a As Integer = 1 a += Color.Grey End Sub End Class Enum Color Red Green = 10 Blue Grey End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestMissingOnEnumsFromMetaData() As Task Await TestMissingInRegularAndScriptAsync( "Imports Microsoft.VisualBasic Module Program Sub Main(args As String()) Dim a = [|FirstDayOfWeek.EigthDay|] End Sub End Module") End Function <WorkItem(540638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540638")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestMaxHex() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = &H8000000000000000 End Enum", "Class Program Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = &H8000000000000000 Blue = &H8000000000000001 End Enum") End Function <WorkItem(540636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540636")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestMinHex() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = &H7FFFFFFFFFFFFFFF End Enum", "Class Program Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = &H7FFFFFFFFFFFFFFF Blue = &H8000000000000000 End Enum") End Function <WorkItem(540631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540631")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestOctalBounds1() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As SByte Red = &O177 End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As SByte Red = &O177 Blue = &O1777777777777777777600 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestULongMax() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As ULong Red = ULong.MaxValue End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As ULong Red = ULong.MaxValue Blue = 0 End Enum") End Function <WorkItem(540604, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540604")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestWrapAround1() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) [|Color.Blue|] End Sub End Module Enum Color As Integer Green = Integer.MaxValue Orange = -2147483648 End Enum", "Module Program Sub Main(args As String()) Color.Blue End Sub End Module Enum Color As Integer Green = Integer.MaxValue Orange = -2147483648 Blue = -2147483647 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestMissingOnHiddenEnum() As Task Await TestMissingInRegularAndScriptAsync( "#ExternalSource (""Default.aspx"", 1) Imports System Enum E #End ExternalSource End Enum #ExternalSource (""Default.aspx"", 2) Class C Sub Goo() Console.Write([|E.x|]) End Sub End Class #End ExternalSource") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestMissingOnPartiallyHiddenEnum() As Task Await TestMissingInRegularAndScriptAsync( "#ExternalSource (""Default.aspx"", 1) Imports System Enum E A B C #End ExternalSource End Enum #ExternalSource (""Default.aspx"", 2) Class C Sub Goo() Console.Write([|E.x|]) End Sub End Class #End ExternalSource") End Function <WorkItem(544656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544656")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestShortHexidecimalLiterals() As Task Await TestInRegularAndScriptAsync( "Module M Dim y = [|E.Y|] ' Generate Y End Module Enum E As Short X = &H4000S End Enum", "Module M Dim y = E.Y ' Generate Y End Module Enum E As Short X = &H4000S Y = &H4001S End Enum") End Function <WorkItem(545937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545937")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestUShortEnums() As Task Await TestInRegularAndScriptAsync( "Module M Dim y = [|E.Y|] ' Generate Y End Module Enum E As UShort X = &H4000US End Enum", "Module M Dim y = E.Y ' Generate Y End Module Enum E As UShort X = &H4000US Y = &H8000US End Enum") End Function <WorkItem(49679, "https://github.com/dotnet/roslyn/issues/49679")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestWithLeftShift_Long() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub Enum Color Green = 1L << 0 End Enum End Module", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub Enum Color Green = 1L << 0 Blue = 1L << 1 End Enum End Module") 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.CodeFixes Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEnumMember Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateEnumMember Public Class GenerateEnumMemberTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New GenerateEnumMemberCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoEmpty() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Red|]) End Sub End Module Enum Color End Enum", "Module Program Sub Main(args As String()) Goo(Color.Red) End Sub End Module Enum Color Red End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoEnumWithSingleMember() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Green|]) End Sub End Module Enum Color Red End Enum", "Module Program Sub Main(args As String()) Goo(Color.Green) End Sub End Module Enum Color Red Green End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithValue() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Green|]) End Sub End Module Enum Color Red = 1 End Enum", "Module Program Sub Main(args As String()) Goo(Color.Green) End Sub End Module Enum Color Red = 1 Green = 2 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateBinaryLiteral() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Green|]) End Sub End Module Enum Color Red = &B01 End Enum", "Module Program Sub Main(args As String()) Goo(Color.Green) End Sub End Module Enum Color Red = &B01 Green = &B10 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoLinearIncreasingSequence() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub End Module Enum Color Red = 1 Green = 2 End Enum", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub End Module Enum Color Red = 1 Green = 2 Blue = 3 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoGeometricSequence() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Purple|]) End Sub End Module Enum Color Red = 1 Green = 2 Blue = 4 End Enum", "Module Program Sub Main(args As String()) Goo(Color.Purple) End Sub End Module Enum Color Red = 1 Green = 2 Blue = 4 Purple = 8 End Enum") End Function <WorkItem(540540, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540540")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithIntegerMaxValue() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub End Module Enum Color Red Green = Integer.MaxValue End Enum", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub End Module Enum Color Red Green = Integer.MaxValue Blue = Integer.MinValue End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestUnsigned16BitEnums() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) [|Color.Green|] End Sub End Module Enum Color As UShort Red = 65535 End Enum", "Module Program Sub Main(args As String()) Color.Green End Sub End Module Enum Color As UShort Red = 65535 Green = 0 End Enum") End Function <WorkItem(540546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540546")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateEnumMemberOfTypeLong() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub End Module Enum Color As Long Red = Long.MinValue End Enum", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub End Module Enum Color As Long Red = Long.MinValue Blue = -9223372036854775807 End Enum") End Function <WorkItem(540636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540636")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithLongMaxValueInHex() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = &H7FFFFFFFFFFFFFFF End Enum", "Class Program Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = &H7FFFFFFFFFFFFFFF Blue = &H8000000000000000 End Enum") End Function <WorkItem(540638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540638")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithLongMinValueInHex() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = &H8000000000000000 End Enum", "Class Program Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = &H8000000000000000 Blue = &H8000000000000001 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterNegativeLongInHex() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = &HFFFFFFFFFFFFFFFF End Enum", "Class Program Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = &HFFFFFFFFFFFFFFFF Blue = &H0 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterPositiveLongInHex() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Color.Orange|] End Sub End Class Enum Color As Long Red = &HFFFFFFFFFFFFFFFF Blue = &H0 End Enum", "Class Program Sub Main(args As String()) Color.Orange End Sub End Class Enum Color As Long Red = &HFFFFFFFFFFFFFFFF Blue = &H0 Orange = &H1 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterPositiveLongExprInHex() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = &H414 / 2 End Enum", "Class Program Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = &H414 / 2 Blue = 523 End Enum") End Function <WorkItem(540632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540632")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithULongMaxValue() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As ULong Red = ULong.MaxValue End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As ULong Red = ULong.MaxValue Blue = 0 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestNegativeRangeIn64BitSignedEnums() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) [|Color.Green|] End Sub End Module Enum Color As Long Red = -10 End Enum", "Module Program Sub Main(args As String()) Color.Green End Sub End Module Enum Color As Long Red = -10 Green = -9 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestUnaryMinusOnUInteger1() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As UInteger Red = -(0 - UInteger.MaxValue) End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As UInteger Red = -(0 - UInteger.MaxValue) Blue = 0 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestDoubleUnaryMinusOnUInteger() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As UInteger Red = --(UInteger.MaxValue - 1) End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As UInteger Red = --(UInteger.MaxValue - 1) Blue = UInteger.MaxValue End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestDoubleUnaryMinusOnUInteger1() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Green|] End Sub End Class Enum Color As UInteger Red = --(UInteger.MaxValue - 1) Blue = 4294967295 End Enum", "Class A Sub Main(args As String()) Color.Green End Sub End Class Enum Color As UInteger Red = --(UInteger.MaxValue - 1) Blue = 4294967295 Green = 0 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateWithImplicitValues() As Task ' Red is implicitly assigned to 0, Green is implicitly Red + 1, So Blue must be 2. Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) [|Color.Blue|] End Sub End Module Enum Color Red Green Yellow = -1 End Enum", "Module Program Sub Main(args As String()) Color.Blue End Sub End Module Enum Color Red Green Yellow = -1 Blue = 2 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateWithImplicitValues2() As Task Await TestInRegularAndScriptAsync( "Class B Sub Main(args As String()) [|Color.Grey|] End Sub End Class Enum Color Red Green = 10 Blue End Enum", "Class B Sub Main(args As String()) Color.Grey End Sub End Class Enum Color Red Green = 10 Blue Grey End Enum") End Function <WorkItem(540549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540549")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestNoExtraneousStatementTerminatorBeforeCommentedMember() As Task Dim code = <Text>Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub End Module Enum Color Red 'Blue End Enum</Text>.Value.Replace(vbLf, vbCrLf) Dim expected = <Text>Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub End Module Enum Color Red Blue 'Blue End Enum</Text>.Value.Replace(vbLf, vbCrLf) Await TestInRegularAndScriptAsync(code, expected) End Function <WorkItem(540552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540552")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithMinValue() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub End Module Enum Color Red = Integer.MinValue End Enum", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub End Module Enum Color Red = Integer.MinValue Blue = -2147483647 End Enum") End Function <WorkItem(540553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540553")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithMinValuePlusConstant() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub End Module Enum Color Red = Integer.MinValue + 100 End Enum", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub End Module Enum Color Red = Integer.MinValue + 100 Blue = -2147483547 End Enum") End Function <WorkItem(540556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540556")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithByteMaxValue() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub End Module Enum Color As Byte Red = 255 End Enum", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub End Module Enum Color As Byte Red = 255 Blue = 0 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoNegativeSByteInOctal() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As SByte Red = &O1777777777777777777777 End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As SByte Red = &O1777777777777777777777 Blue = &O0 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoPositiveSByteInOctal1() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As SByte Red = &O0 End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As SByte Red = &O0 Blue = &O1 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoPositiveSByteInOctal2() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As SByte Red = &O176 End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As SByte Red = &O176 Blue = &O177 End Enum") End Function <WorkItem(540631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540631")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateAfterEnumWithSByteMaxValueInOctal() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As SByte Red = &O177 End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As SByte Red = &O177 Blue = &O1777777777777777777600 End Enum") End Function <WorkItem(528207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528207")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestAbsenceOfFixWhenImportingEnums() As Task Await TestMissingInRegularAndScriptAsync( "Imports Color Module Program Sub Main(args As String()) Goo([|Blue|]) End Sub End Module Enum Color As Byte Red End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestPresenceOfFixWhenImportingEnumsYetFullyQualifyingThem() As Task Await TestInRegularAndScriptAsync( "Imports Color Module Program Sub Main(args As String()) Goo([|Color.Green|]) End Sub End Module Enum Color As Long Red = -10 End Enum", "Imports Color Module Program Sub Main(args As String()) Goo(Color.Green) End Sub End Module Enum Color As Long Red = -10 Green = -9 End Enum") End Function <WorkItem(540585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540585")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoBitshiftEnum() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub Enum Color Red = 1 << 0 Green = 1 << 1 Orange = 1 << 2 End Enum End Module", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub Enum Color Red = 1 << 0 Green = 1 << 1 Orange = 1 << 2 Blue = 1 << 3 End Enum End Module") End Function <WorkItem(540566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540566")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestKeywordName() As Task Await TestInRegularAndScriptAsync( "Imports Color Module Program Sub Main(args As String()) Goo([|Color.Enum|]) End Sub End Module Enum Color As Byte Red End Enum", "Imports Color Module Program Sub Main(args As String()) Goo(Color.Enum) End Sub End Module Enum Color As Byte Red [Enum] End Enum") End Function <WorkItem(540547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540547")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestStandaloneReference() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) [|Color.Blue|] End Sub End Module Enum Color As Integer Red = Integer.MinValue Green = 1 End Enum", "Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Color.Blue End Sub End Module Enum Color As Integer Red = Integer.MinValue Green = 1 Blue = 2 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestCircularEnumsForErrorTolerance() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) [|Circular.C|] End Sub End Module Enum Circular A = B B End Enum", "Module Program Sub Main(args As String()) Circular.C End Sub End Module Enum Circular A = B B C End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestEnumWithIncorrectValueForErrorTolerance() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) [|Color.Green|] End Sub End Module Enum Color As Byte Red = -2 End Enum", "Module Program Sub Main(args As String()) Color.Green End Sub End Module Enum Color As Byte Red = -2 Green End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestHexValues() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) [|RenderType.LastViewedPage|] End Sub End Module <FlagsAttribute()> Enum RenderType None = &H0 DataUri = &H1 GZip = &H2 ContentPage = &H4 ViewPage = &H8 HomePage = &H10 End Enum", "Module Program Sub Main(args As String()) RenderType.LastViewedPage End Sub End Module <FlagsAttribute()> Enum RenderType None = &H0 DataUri = &H1 GZip = &H2 ContentPage = &H4 ViewPage = &H8 HomePage = &H10 LastViewedPage = &H20 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoShadowedEnum() As Task Await TestInRegularAndScriptAsync( "Class B Inherits A Sub Main(args As String()) [|BaseColors.Blue|] End Sub Shadows Enum BaseColors Orange = 3 End Enum End Class Public Class A Public Enum BaseColors Red = 1 Green = 2 End Enum End Class", "Class B Inherits A Sub Main(args As String()) BaseColors.Blue End Sub Shadows Enum BaseColors Orange = 3 Blue = 4 End Enum End Class Public Class A Public Enum BaseColors Red = 1 Green = 2 End Enum End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoDerivedEnumMissingShadowsKeyword() As Task Await TestInRegularAndScriptAsync( "Class B Inherits A Sub Main(args As String()) [|BaseColors.Blue|] End Sub Enum BaseColors Orange = 3 End Enum End Class Public Class A Public Enum BaseColors Red = 1 Green = 2 End Enum End Class", "Class B Inherits A Sub Main(args As String()) BaseColors.Blue End Sub Enum BaseColors Orange = 3 Blue = 4 End Enum End Class Public Class A Public Enum BaseColors Red = 1 Green = 2 End Enum End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerateIntoBaseEnum() As Task Await TestInRegularAndScriptAsync( "Class B Inherits A Sub Main(args As String()) [|BaseColors.Blue|] End Sub End Class Public Class A Public Enum BaseColors Red = 1 Green = 2 End Enum End Class", "Class B Inherits A Sub Main(args As String()) BaseColors.Blue End Sub End Class Public Class A Public Enum BaseColors Red = 1 Green = 2 Blue = 3 End Enum End Class") End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestErrorToleranceWithStrictSemantics() As Task Await TestInRegularAndScriptAsync( "Option Strict On Class B Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = 1.5 Green = 2.3 Orange = 3.3 End Enum", "Option Strict On Class B Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = 1.5 Green = 2.3 Orange = 3.3 Blue = 4 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGeometricSequenceWithTypeConversions() As Task Await TestInRegularAndScriptAsync( "Option Strict On Class B Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = CLng(1.5) Green = CLng(2.3) Orange = CLng(3.9) End Enum", "Option Strict On Class B Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = CLng(1.5) Green = CLng(2.3) Orange = CLng(3.9) Blue = 8 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestLinearSequenceWithTypeConversions() As Task Await TestInRegularAndScriptAsync( "Option Strict On Class B Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = CLng(1.5) Green = CLng(2.3) Orange = CLng(4.9) End Enum", "Option Strict On Class B Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = CLng(1.5) Green = CLng(2.3) Orange = CLng(4.9) Blue = 6 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestGenerationWhenMembersShareValues() As Task Await TestInRegularAndScriptAsync( "Option Strict On Class B Sub Main(args As String()) [|Color.Grey|] End Sub End Class Enum Color Red Green Blue Max = Blue End Enum", "Option Strict On Class B Sub Main(args As String()) Color.Grey End Sub End Class Enum Color Red Green Blue Max = Blue Grey = 3 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestInvokeFromAddAssignmentStatement() As Task Await TestInRegularAndScriptAsync( "Class B Sub Main(args As String()) Dim a As Integer = 1 a += [|Color.Grey|] End Sub End Class Enum Color Red Green = 10 Blue End Enum", "Class B Sub Main(args As String()) Dim a As Integer = 1 a += Color.Grey End Sub End Class Enum Color Red Green = 10 Blue Grey End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestMissingOnEnumsFromMetaData() As Task Await TestMissingInRegularAndScriptAsync( "Imports Microsoft.VisualBasic Module Program Sub Main(args As String()) Dim a = [|FirstDayOfWeek.EigthDay|] End Sub End Module") End Function <WorkItem(540638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540638")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestMaxHex() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = &H8000000000000000 End Enum", "Class Program Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = &H8000000000000000 Blue = &H8000000000000001 End Enum") End Function <WorkItem(540636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540636")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestMinHex() As Task Await TestInRegularAndScriptAsync( "Class Program Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As Long Red = &H7FFFFFFFFFFFFFFF End Enum", "Class Program Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As Long Red = &H7FFFFFFFFFFFFFFF Blue = &H8000000000000000 End Enum") End Function <WorkItem(540631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540631")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestOctalBounds1() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As SByte Red = &O177 End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As SByte Red = &O177 Blue = &O1777777777777777777600 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestULongMax() As Task Await TestInRegularAndScriptAsync( "Class A Sub Main(args As String()) [|Color.Blue|] End Sub End Class Enum Color As ULong Red = ULong.MaxValue End Enum", "Class A Sub Main(args As String()) Color.Blue End Sub End Class Enum Color As ULong Red = ULong.MaxValue Blue = 0 End Enum") End Function <WorkItem(540604, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540604")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestWrapAround1() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) [|Color.Blue|] End Sub End Module Enum Color As Integer Green = Integer.MaxValue Orange = -2147483648 End Enum", "Module Program Sub Main(args As String()) Color.Blue End Sub End Module Enum Color As Integer Green = Integer.MaxValue Orange = -2147483648 Blue = -2147483647 End Enum") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestMissingOnHiddenEnum() As Task Await TestMissingInRegularAndScriptAsync( "#ExternalSource (""Default.aspx"", 1) Imports System Enum E #End ExternalSource End Enum #ExternalSource (""Default.aspx"", 2) Class C Sub Goo() Console.Write([|E.x|]) End Sub End Class #End ExternalSource") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestMissingOnPartiallyHiddenEnum() As Task Await TestMissingInRegularAndScriptAsync( "#ExternalSource (""Default.aspx"", 1) Imports System Enum E A B C #End ExternalSource End Enum #ExternalSource (""Default.aspx"", 2) Class C Sub Goo() Console.Write([|E.x|]) End Sub End Class #End ExternalSource") End Function <WorkItem(544656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544656")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestShortHexidecimalLiterals() As Task Await TestInRegularAndScriptAsync( "Module M Dim y = [|E.Y|] ' Generate Y End Module Enum E As Short X = &H4000S End Enum", "Module M Dim y = E.Y ' Generate Y End Module Enum E As Short X = &H4000S Y = &H4001S End Enum") End Function <WorkItem(545937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545937")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestUShortEnums() As Task Await TestInRegularAndScriptAsync( "Module M Dim y = [|E.Y|] ' Generate Y End Module Enum E As UShort X = &H4000US End Enum", "Module M Dim y = E.Y ' Generate Y End Module Enum E As UShort X = &H4000US Y = &H8000US End Enum") End Function <WorkItem(49679, "https://github.com/dotnet/roslyn/issues/49679")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)> Public Async Function TestWithLeftShift_Long() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Goo([|Color.Blue|]) End Sub Enum Color Green = 1L << 0 End Enum End Module", "Module Program Sub Main(args As String()) Goo(Color.Blue) End Sub Enum Color Green = 1L << 0 Blue = 1L << 1 End Enum End Module") End Function End Class End Namespace
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ko.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="ko" original="../CSharpEditorResources.resx"> <body> <trans-unit id="Add_Missing_Usings_on_Paste"> <source>Add Missing Usings on Paste</source> <target state="translated">붙여넣을 때 누락된 using 추가</target> <note>"usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Adding_missing_usings"> <source>Adding missing usings...</source> <target state="translated">누락된 using 추가 중...</target> <note>Shown in a thread await dialog. "usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value"> <source>Avoid expression statements that implicitly ignore value</source> <target state="translated">암시적으로 값을 무시하는 식 문을 사용하지 마세요.</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_value_assignments"> <source>Avoid unused value assignments</source> <target state="translated">사용되지 않는 값 할당을 사용하지 마세요.</target> <note /> </trans-unit> <trans-unit id="Chosen_version_0"> <source>Chosen version: '{0}'</source> <target state="translated">선택한 버전: '{0}'</target> <note /> </trans-unit> <trans-unit id="Complete_statement_on_semicolon"> <source>Complete statement on ;</source> <target state="translated">;에서 문 완성</target> <note /> </trans-unit> <trans-unit id="Could_not_find_by_name_0"> <source>Could not find by name: '{0}'</source> <target state="translated">'{0}' 이름으로 찾을 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Decompilation_log"> <source>Decompilation log</source> <target state="translated">디컴파일 로그</target> <note /> </trans-unit> <trans-unit id="Discard"> <source>Discard</source> <target state="translated">폐기</target> <note /> </trans-unit> <trans-unit id="Elsewhere"> <source>Elsewhere</source> <target state="translated">다른 곳</target> <note /> </trans-unit> <trans-unit id="Fix_interpolated_verbatim_string"> <source>Fix interpolated verbatim string</source> <target state="translated">보간된 축자 문자열 수정</target> <note /> </trans-unit> <trans-unit id="For_built_in_types"> <source>For built-in types</source> <target state="translated">기본 제공 형식인 경우</target> <note /> </trans-unit> <trans-unit id="Found_0_assemblies_for_1"> <source>Found '{0}' assemblies for '{1}':</source> <target state="translated">'{1}'의 어셈블리를 '{0}'개 찾았습니다.</target> <note /> </trans-unit> <trans-unit id="Found_exact_match_0"> <source>Found exact match: '{0}'</source> <target state="translated">정확하게 일치하는 항목을 찾았습니다. '{0}'</target> <note /> </trans-unit> <trans-unit id="Found_higher_version_match_0"> <source>Found higher version match: '{0}'</source> <target state="translated">일치하는 상위 버전을 찾았습니다. '{0}'</target> <note /> </trans-unit> <trans-unit id="Found_single_assembly_0"> <source>Found single assembly: '{0}'</source> <target state="translated">단일 어셈블리를 찾았습니다. '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_Event_Subscription"> <source>Generate Event Subscription</source> <target state="translated">이벤트 구독 생성</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_in_declaration_statements"> <source>Ignore spaces in declaration statements</source> <target state="translated">선언문의 공백 무시</target> <note /> </trans-unit> <trans-unit id="Indent_block_contents"> <source>Indent block contents</source> <target state="translated">블록 내용 들여쓰기</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents"> <source>Indent case contents</source> <target state="translated">case 내용 들여쓰기</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents_when_block"> <source>Indent case contents (when block)</source> <target state="translated">case 내용 들여쓰기(블록)</target> <note /> </trans-unit> <trans-unit id="Indent_case_labels"> <source>Indent case labels</source> <target state="translated">case 레이블 들여쓰기</target> <note /> </trans-unit> <trans-unit id="Indent_open_and_close_braces"> <source>Indent open and close braces</source> <target state="translated">여는 중괄호 및 닫는 중괄호 들여쓰기</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_cast"> <source>Insert space after cast</source> <target state="translated">캐스트 뒤에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration"> <source>Insert space after colon for base or interface in type declaration</source> <target state="translated">형식 선언의 기본 또는 인터페이스에 대한 콜론 뒤에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_comma"> <source>Insert space after comma</source> <target state="translated">쉼표 뒤에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_dot"> <source>Insert space after dot</source> <target state="translated">점 뒤에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_keywords_in_control_flow_statements"> <source>Insert space after keywords in control flow statements</source> <target state="translated">제어 흐름 문의 키워드 뒤에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_semicolon_in_for_statement"> <source>Insert space after semicolon in "for" statement</source> <target state="translated">"for" 문의 세미콜론 뒤에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration"> <source>Insert space before colon for base or interface in type declaration</source> <target state="translated">형식 선언의 기본 또는 인터페이스에 대한 콜론 앞에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_comma"> <source>Insert space before comma</source> <target state="translated">쉼표 앞에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_dot"> <source>Insert space before dot</source> <target state="translated">점 앞에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_open_square_bracket"> <source>Insert space before open square bracket</source> <target state="translated">여는 대괄호 앞에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_semicolon_in_for_statement"> <source>Insert space before semicolon in "for" statement</source> <target state="translated">"for" 문의 세미콜론 앞에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">메서드 이름과 여는 괄호 사이에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">메서드 이름과 여는 괄호 사이에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_argument_list_parentheses"> <source>Insert space within argument list parentheses</source> <target state="translated">인수 목록 괄호의 내부에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_argument_list_parentheses"> <source>Insert space within empty argument list parentheses</source> <target state="translated">빈 인수 목록 괄호 내부에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_parameter_list_parentheses"> <source>Insert space within empty parameter list parentheses</source> <target state="translated">빈 매개 변수 목록 괄호 내에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_square_brackets"> <source>Insert space within empty square brackets</source> <target state="translated">빈 대괄호의 내부에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parameter_list_parentheses"> <source>Insert space within parameter list parentheses</source> <target state="translated">매개 변수 목록 괄호 내에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_expressions"> <source>Insert space within parentheses of expressions</source> <target state="translated">식의 괄호 내부에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_type_casts"> <source>Insert space within parentheses of type casts</source> <target state="translated">형식 캐스팅의 괄호 내부에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements"> <source>Insert spaces within parentheses of control flow statements</source> <target state="translated">제어 흐름 문의 괄호 내부에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_square_brackets"> <source>Insert spaces within square brackets</source> <target state="translated">대괄호 내부에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Inside_namespace"> <source>Inside namespace</source> <target state="translated">namespace 내부</target> <note /> </trans-unit> <trans-unit id="Label_Indentation"> <source>Label Indentation</source> <target state="translated">레이블 들여쓰기</target> <note /> </trans-unit> <trans-unit id="Leave_block_on_single_line"> <source>Leave block on single line</source> <target state="translated">블록을 한 줄에 유지</target> <note /> </trans-unit> <trans-unit id="Leave_statements_and_member_declarations_on_the_same_line"> <source>Leave statements and member declarations on the same line</source> <target state="translated">문과 멤버 선언을 같은 줄에 유지</target> <note /> </trans-unit> <trans-unit id="Load_from_0"> <source>Load from: '{0}'</source> <target state="translated">로드 위치: '{0}'</target> <note /> </trans-unit> <trans-unit id="Module_not_found"> <source>Module not found!</source> <target state="translated">모듈을 찾을 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">안 함 </target> <note /> </trans-unit> <trans-unit id="Outside_namespace"> <source>Outside namespace</source> <target state="translated">외부 namespace</target> <note /> </trans-unit> <trans-unit id="Place_catch_on_new_line"> <source>Place "catch" on new line</source> <target state="translated">"catch"를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_else_on_new_line"> <source>Place "else" on new line</source> <target state="translated">"else"를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_finally_on_new_line"> <source>Place "finally" on new line</source> <target state="translated">"finally"를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_members_in_anonymous_types_on_new_line"> <source>Place members in anonymous types on new line</source> <target state="translated">익명 형식의 멤버를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_members_in_object_initializers_on_new_line"> <source>Place members in object initializers on new line</source> <target state="translated">개체 이니셜라이저의 멤버를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods"> <source>Place open brace on new line for anonymous methods</source> <target state="translated">무명 메서드의 여는 중괄호를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_types"> <source>Place open brace on new line for anonymous types</source> <target state="translated">익명 형식의 여는 중괄호를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_control_blocks"> <source>Place open brace on new line for control blocks</source> <target state="translated">제어 블록의 여는 중괄호를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_lambda_expression"> <source>Place open brace on new line for lambda expression</source> <target state="translated">람다 식의 여는 중괄호를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions"> <source>Place open brace on new line for methods and local functions</source> <target state="translated">메서드 및 로컬 함수의 여는 중괄호를 새 줄에 배치합니다.</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers"> <source>Place open brace on new line for object, collection, array, and with initializers</source> <target state="translated">개체, 컬렉션, 배열 및 with 이니셜라이저의 여는 중괄호를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events"> <source>Place open brace on new line for properties, indexers, and events</source> <target state="translated">속성, 인덱서 및 이벤트의 여는 중괄호를 새 줄에 배치합니다.</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors"> <source>Place open brace on new line for property, indexer, and event accessors</source> <target state="translated">속성, 인덱서 및 이벤트 접근자의 여는 중괄호를 새 줄에 배치합니다.</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_types"> <source>Place open brace on new line for types</source> <target state="translated">형식의 여는 중괄호를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_query_expression_clauses_on_new_line"> <source>Place query expression clauses on new line</source> <target state="translated">쿼리 식의 절을 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_delegate_call"> <source>Prefer conditional delegate call</source> <target state="translated">조건부 대리자 호출 기본 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_deconstructed_variable_declaration"> <source>Prefer deconstructed variable declaration</source> <target state="translated">분해된 변수 선언 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_type"> <source>Prefer explicit type</source> <target state="translated">명시적 형식 기본 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_index_operator"> <source>Prefer index operator</source> <target state="translated">인덱스 연산자 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_inlined_variable_declaration"> <source>Prefer inlined variable declaration</source> <target state="translated">인라인 변수 선언 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_local_function_over_anonymous_function"> <source>Prefer local function over anonymous function</source> <target state="translated">익명 함수보다 로컬 함수 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching"> <source>Prefer pattern matching</source> <target state="translated">패턴 일치 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_as_with_null_check"> <source>Prefer pattern matching over 'as' with 'null' check</source> <target state="translated">null' 검사에서 'as'보다 패턴 일치 기본 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_is_with_cast_check"> <source>Prefer pattern matching over 'is' with 'cast' check</source> <target state="translated">캐스트' 검사에서 'is'보다 패턴 일치 기본 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_mixed_type_check"> <source>Prefer pattern matching over mixed type check</source> <target state="translated">혼합 형식 검사 대신 패턴 일치 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_range_operator"> <source>Prefer range operator</source> <target state="translated">범위 연산자 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_default_expression"> <source>Prefer simple 'default' expression</source> <target state="translated">간단한 'default' 식을 기본으로 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_using_statement"> <source>Prefer simple 'using' statement</source> <target state="translated">간단한 'using' 문 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_static_local_functions"> <source>Prefer static local functions</source> <target state="translated">정적 로컬 함수 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_switch_expression"> <source>Prefer switch expression</source> <target state="translated">switch 식 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_throw_expression"> <source>Prefer throw-expression</source> <target state="translated">throw 식 기본 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_var"> <source>Prefer 'var'</source> <target state="translated">var'을 기본으로 사용합니다.</target> <note /> </trans-unit> <trans-unit id="Preferred_using_directive_placement"> <source>Preferred 'using' directive placement</source> <target state="translated">선호하는 'using' 지시문 배치</target> <note /> </trans-unit> <trans-unit id="Press_TAB_to_insert"> <source> (Press TAB to insert)</source> <target state="translated"> (삽입하려면 &lt;Tab&gt; 키 누름)</target> <note /> </trans-unit> <trans-unit id="Resolve_0"> <source>Resolve: '{0}'</source> <target state="translated">확인: '{0}'</target> <note /> </trans-unit> <trans-unit id="Resolve_module_0_of_1"> <source>Resolve module: '{0}' of '{1}'</source> <target state="translated">모듈 확인: '{0}'/'{1}'</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_operators"> <source>Set spacing for operators</source> <target state="translated">연산자의 간격을 설정합니다.</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">스마트 들여쓰기</target> <note /> </trans-unit> <trans-unit id="Split_string"> <source>Split string</source> <target state="translated">문자열 분할</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">사용하지 않는 로컬</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">접근자에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">생성자에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">인덱서에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambdas"> <source>Use expression body for lambdas</source> <target state="translated">람다에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">로컬 함수의 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">메서드에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">연산자에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">속성에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="WARN_Version_mismatch_Expected_0_Got_1"> <source>WARN: Version mismatch. Expected: '{0}', Got: '{1}'</source> <target state="translated">WARN: 버전이 일치하지 않습니다. 예상: '{0}', 실제: '{1}'</target> <note /> </trans-unit> <trans-unit id="When_on_single_line"> <source>When on single line</source> <target state="translated">한 줄에 있는 경우</target> <note /> </trans-unit> <trans-unit id="When_possible"> <source>When possible</source> <target state="translated">가능한 경우</target> <note /> </trans-unit> <trans-unit id="When_variable_type_is_apparent"> <source>When variable type is apparent</source> <target state="translated">변수 형식이 명백한 경우</target> <note /> </trans-unit> <trans-unit id="_0_items_in_cache"> <source>'{0}' items in cache</source> <target state="translated">캐시의 '{0}'개 항목</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="ko" original="../CSharpEditorResources.resx"> <body> <trans-unit id="Add_Missing_Usings_on_Paste"> <source>Add Missing Usings on Paste</source> <target state="translated">붙여넣을 때 누락된 using 추가</target> <note>"usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Adding_missing_usings"> <source>Adding missing usings...</source> <target state="translated">누락된 using 추가 중...</target> <note>Shown in a thread await dialog. "usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value"> <source>Avoid expression statements that implicitly ignore value</source> <target state="translated">암시적으로 값을 무시하는 식 문을 사용하지 마세요.</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_value_assignments"> <source>Avoid unused value assignments</source> <target state="translated">사용되지 않는 값 할당을 사용하지 마세요.</target> <note /> </trans-unit> <trans-unit id="Chosen_version_0"> <source>Chosen version: '{0}'</source> <target state="translated">선택한 버전: '{0}'</target> <note /> </trans-unit> <trans-unit id="Complete_statement_on_semicolon"> <source>Complete statement on ;</source> <target state="translated">;에서 문 완성</target> <note /> </trans-unit> <trans-unit id="Could_not_find_by_name_0"> <source>Could not find by name: '{0}'</source> <target state="translated">'{0}' 이름으로 찾을 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Decompilation_log"> <source>Decompilation log</source> <target state="translated">디컴파일 로그</target> <note /> </trans-unit> <trans-unit id="Discard"> <source>Discard</source> <target state="translated">폐기</target> <note /> </trans-unit> <trans-unit id="Elsewhere"> <source>Elsewhere</source> <target state="translated">다른 곳</target> <note /> </trans-unit> <trans-unit id="Fix_interpolated_verbatim_string"> <source>Fix interpolated verbatim string</source> <target state="translated">보간된 축자 문자열 수정</target> <note /> </trans-unit> <trans-unit id="For_built_in_types"> <source>For built-in types</source> <target state="translated">기본 제공 형식인 경우</target> <note /> </trans-unit> <trans-unit id="Found_0_assemblies_for_1"> <source>Found '{0}' assemblies for '{1}':</source> <target state="translated">'{1}'의 어셈블리를 '{0}'개 찾았습니다.</target> <note /> </trans-unit> <trans-unit id="Found_exact_match_0"> <source>Found exact match: '{0}'</source> <target state="translated">정확하게 일치하는 항목을 찾았습니다. '{0}'</target> <note /> </trans-unit> <trans-unit id="Found_higher_version_match_0"> <source>Found higher version match: '{0}'</source> <target state="translated">일치하는 상위 버전을 찾았습니다. '{0}'</target> <note /> </trans-unit> <trans-unit id="Found_single_assembly_0"> <source>Found single assembly: '{0}'</source> <target state="translated">단일 어셈블리를 찾았습니다. '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_Event_Subscription"> <source>Generate Event Subscription</source> <target state="translated">이벤트 구독 생성</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_in_declaration_statements"> <source>Ignore spaces in declaration statements</source> <target state="translated">선언문의 공백 무시</target> <note /> </trans-unit> <trans-unit id="Indent_block_contents"> <source>Indent block contents</source> <target state="translated">블록 내용 들여쓰기</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents"> <source>Indent case contents</source> <target state="translated">case 내용 들여쓰기</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents_when_block"> <source>Indent case contents (when block)</source> <target state="translated">case 내용 들여쓰기(블록)</target> <note /> </trans-unit> <trans-unit id="Indent_case_labels"> <source>Indent case labels</source> <target state="translated">case 레이블 들여쓰기</target> <note /> </trans-unit> <trans-unit id="Indent_open_and_close_braces"> <source>Indent open and close braces</source> <target state="translated">여는 중괄호 및 닫는 중괄호 들여쓰기</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_cast"> <source>Insert space after cast</source> <target state="translated">캐스트 뒤에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration"> <source>Insert space after colon for base or interface in type declaration</source> <target state="translated">형식 선언의 기본 또는 인터페이스에 대한 콜론 뒤에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_comma"> <source>Insert space after comma</source> <target state="translated">쉼표 뒤에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_dot"> <source>Insert space after dot</source> <target state="translated">점 뒤에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_keywords_in_control_flow_statements"> <source>Insert space after keywords in control flow statements</source> <target state="translated">제어 흐름 문의 키워드 뒤에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_semicolon_in_for_statement"> <source>Insert space after semicolon in "for" statement</source> <target state="translated">"for" 문의 세미콜론 뒤에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration"> <source>Insert space before colon for base or interface in type declaration</source> <target state="translated">형식 선언의 기본 또는 인터페이스에 대한 콜론 앞에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_comma"> <source>Insert space before comma</source> <target state="translated">쉼표 앞에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_dot"> <source>Insert space before dot</source> <target state="translated">점 앞에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_open_square_bracket"> <source>Insert space before open square bracket</source> <target state="translated">여는 대괄호 앞에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_semicolon_in_for_statement"> <source>Insert space before semicolon in "for" statement</source> <target state="translated">"for" 문의 세미콜론 앞에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">메서드 이름과 여는 괄호 사이에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">메서드 이름과 여는 괄호 사이에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_argument_list_parentheses"> <source>Insert space within argument list parentheses</source> <target state="translated">인수 목록 괄호의 내부에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_argument_list_parentheses"> <source>Insert space within empty argument list parentheses</source> <target state="translated">빈 인수 목록 괄호 내부에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_parameter_list_parentheses"> <source>Insert space within empty parameter list parentheses</source> <target state="translated">빈 매개 변수 목록 괄호 내에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_square_brackets"> <source>Insert space within empty square brackets</source> <target state="translated">빈 대괄호의 내부에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parameter_list_parentheses"> <source>Insert space within parameter list parentheses</source> <target state="translated">매개 변수 목록 괄호 내에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_expressions"> <source>Insert space within parentheses of expressions</source> <target state="translated">식의 괄호 내부에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_type_casts"> <source>Insert space within parentheses of type casts</source> <target state="translated">형식 캐스팅의 괄호 내부에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements"> <source>Insert spaces within parentheses of control flow statements</source> <target state="translated">제어 흐름 문의 괄호 내부에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_square_brackets"> <source>Insert spaces within square brackets</source> <target state="translated">대괄호 내부에 공백 삽입</target> <note /> </trans-unit> <trans-unit id="Inside_namespace"> <source>Inside namespace</source> <target state="translated">namespace 내부</target> <note /> </trans-unit> <trans-unit id="Label_Indentation"> <source>Label Indentation</source> <target state="translated">레이블 들여쓰기</target> <note /> </trans-unit> <trans-unit id="Leave_block_on_single_line"> <source>Leave block on single line</source> <target state="translated">블록을 한 줄에 유지</target> <note /> </trans-unit> <trans-unit id="Leave_statements_and_member_declarations_on_the_same_line"> <source>Leave statements and member declarations on the same line</source> <target state="translated">문과 멤버 선언을 같은 줄에 유지</target> <note /> </trans-unit> <trans-unit id="Load_from_0"> <source>Load from: '{0}'</source> <target state="translated">로드 위치: '{0}'</target> <note /> </trans-unit> <trans-unit id="Module_not_found"> <source>Module not found!</source> <target state="translated">모듈을 찾을 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">안 함 </target> <note /> </trans-unit> <trans-unit id="Outside_namespace"> <source>Outside namespace</source> <target state="translated">외부 namespace</target> <note /> </trans-unit> <trans-unit id="Place_catch_on_new_line"> <source>Place "catch" on new line</source> <target state="translated">"catch"를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_else_on_new_line"> <source>Place "else" on new line</source> <target state="translated">"else"를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_finally_on_new_line"> <source>Place "finally" on new line</source> <target state="translated">"finally"를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_members_in_anonymous_types_on_new_line"> <source>Place members in anonymous types on new line</source> <target state="translated">익명 형식의 멤버를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_members_in_object_initializers_on_new_line"> <source>Place members in object initializers on new line</source> <target state="translated">개체 이니셜라이저의 멤버를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods"> <source>Place open brace on new line for anonymous methods</source> <target state="translated">무명 메서드의 여는 중괄호를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_types"> <source>Place open brace on new line for anonymous types</source> <target state="translated">익명 형식의 여는 중괄호를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_control_blocks"> <source>Place open brace on new line for control blocks</source> <target state="translated">제어 블록의 여는 중괄호를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_lambda_expression"> <source>Place open brace on new line for lambda expression</source> <target state="translated">람다 식의 여는 중괄호를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions"> <source>Place open brace on new line for methods and local functions</source> <target state="translated">메서드 및 로컬 함수의 여는 중괄호를 새 줄에 배치합니다.</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers"> <source>Place open brace on new line for object, collection, array, and with initializers</source> <target state="translated">개체, 컬렉션, 배열 및 with 이니셜라이저의 여는 중괄호를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events"> <source>Place open brace on new line for properties, indexers, and events</source> <target state="translated">속성, 인덱서 및 이벤트의 여는 중괄호를 새 줄에 배치합니다.</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors"> <source>Place open brace on new line for property, indexer, and event accessors</source> <target state="translated">속성, 인덱서 및 이벤트 접근자의 여는 중괄호를 새 줄에 배치합니다.</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_types"> <source>Place open brace on new line for types</source> <target state="translated">형식의 여는 중괄호를 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Place_query_expression_clauses_on_new_line"> <source>Place query expression clauses on new line</source> <target state="translated">쿼리 식의 절을 새 줄에 배치</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_delegate_call"> <source>Prefer conditional delegate call</source> <target state="translated">조건부 대리자 호출 기본 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_deconstructed_variable_declaration"> <source>Prefer deconstructed variable declaration</source> <target state="translated">분해된 변수 선언 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_type"> <source>Prefer explicit type</source> <target state="translated">명시적 형식 기본 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_index_operator"> <source>Prefer index operator</source> <target state="translated">인덱스 연산자 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_inlined_variable_declaration"> <source>Prefer inlined variable declaration</source> <target state="translated">인라인 변수 선언 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_local_function_over_anonymous_function"> <source>Prefer local function over anonymous function</source> <target state="translated">익명 함수보다 로컬 함수 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching"> <source>Prefer pattern matching</source> <target state="translated">패턴 일치 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_as_with_null_check"> <source>Prefer pattern matching over 'as' with 'null' check</source> <target state="translated">null' 검사에서 'as'보다 패턴 일치 기본 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_is_with_cast_check"> <source>Prefer pattern matching over 'is' with 'cast' check</source> <target state="translated">캐스트' 검사에서 'is'보다 패턴 일치 기본 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_mixed_type_check"> <source>Prefer pattern matching over mixed type check</source> <target state="translated">혼합 형식 검사 대신 패턴 일치 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_range_operator"> <source>Prefer range operator</source> <target state="translated">범위 연산자 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_default_expression"> <source>Prefer simple 'default' expression</source> <target state="translated">간단한 'default' 식을 기본으로 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_using_statement"> <source>Prefer simple 'using' statement</source> <target state="translated">간단한 'using' 문 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_static_local_functions"> <source>Prefer static local functions</source> <target state="translated">정적 로컬 함수 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_switch_expression"> <source>Prefer switch expression</source> <target state="translated">switch 식 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_throw_expression"> <source>Prefer throw-expression</source> <target state="translated">throw 식 기본 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_var"> <source>Prefer 'var'</source> <target state="translated">var'을 기본으로 사용합니다.</target> <note /> </trans-unit> <trans-unit id="Preferred_using_directive_placement"> <source>Preferred 'using' directive placement</source> <target state="translated">선호하는 'using' 지시문 배치</target> <note /> </trans-unit> <trans-unit id="Press_TAB_to_insert"> <source> (Press TAB to insert)</source> <target state="translated"> (삽입하려면 &lt;Tab&gt; 키 누름)</target> <note /> </trans-unit> <trans-unit id="Resolve_0"> <source>Resolve: '{0}'</source> <target state="translated">확인: '{0}'</target> <note /> </trans-unit> <trans-unit id="Resolve_module_0_of_1"> <source>Resolve module: '{0}' of '{1}'</source> <target state="translated">모듈 확인: '{0}'/'{1}'</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_operators"> <source>Set spacing for operators</source> <target state="translated">연산자의 간격을 설정합니다.</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">스마트 들여쓰기</target> <note /> </trans-unit> <trans-unit id="Split_string"> <source>Split string</source> <target state="translated">문자열 분할</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">사용하지 않는 로컬</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">접근자에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">생성자에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">인덱서에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambdas"> <source>Use expression body for lambdas</source> <target state="translated">람다에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">로컬 함수의 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">메서드에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">연산자에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">속성에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="WARN_Version_mismatch_Expected_0_Got_1"> <source>WARN: Version mismatch. Expected: '{0}', Got: '{1}'</source> <target state="translated">WARN: 버전이 일치하지 않습니다. 예상: '{0}', 실제: '{1}'</target> <note /> </trans-unit> <trans-unit id="When_on_single_line"> <source>When on single line</source> <target state="translated">한 줄에 있는 경우</target> <note /> </trans-unit> <trans-unit id="When_possible"> <source>When possible</source> <target state="translated">가능한 경우</target> <note /> </trans-unit> <trans-unit id="When_variable_type_is_apparent"> <source>When variable type is apparent</source> <target state="translated">변수 형식이 명백한 경우</target> <note /> </trans-unit> <trans-unit id="_0_items_in_cache"> <source>'{0}' items in cache</source> <target state="translated">캐시의 '{0}'개 항목</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/NamespaceSymbol.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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a namespace. /// </summary> internal abstract partial class NamespaceSymbol : NamespaceOrTypeSymbol, INamespaceSymbolInternal { // PERF: initialization of the following fields will allocate, so we make them lazy private ImmutableArray<NamedTypeSymbol> _lazyTypesMightContainExtensionMethods; private string _lazyQualifiedName; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /// <summary> /// Get all the members of this symbol that are namespaces. /// </summary> /// <returns>An IEnumerable containing all the namespaces that are members of this symbol. /// If this symbol has no namespace members, returns an empty IEnumerable. Never returns /// null.</returns> public IEnumerable<NamespaceSymbol> GetNamespaceMembers() { return this.GetMembers().OfType<NamespaceSymbol>(); } /// <summary> /// Returns whether this namespace is the unnamed, global namespace that is /// at the root of all namespaces. /// </summary> public virtual bool IsGlobalNamespace { get { return (object)ContainingNamespace == null; } } internal abstract NamespaceExtent Extent { get; } /// <summary> /// The kind of namespace: Module, Assembly or Compilation. /// Module namespaces contain only members from the containing module that share the same namespace name. /// Assembly namespaces contain members for all modules in the containing assembly that share the same namespace name. /// Compilation namespaces contain all members, from source or referenced metadata (assemblies and modules) that share the same namespace name. /// </summary> public NamespaceKind NamespaceKind { get { return this.Extent.Kind; } } /// <summary> /// The containing compilation for compilation namespaces. /// </summary> public CSharpCompilation ContainingCompilation { get { return this.NamespaceKind == NamespaceKind.Compilation ? this.Extent.Compilation : null; } } /// <summary> /// If a namespace has Assembly or Compilation extent, it may be composed of multiple /// namespaces that are merged together. If so, ConstituentNamespaces returns /// all the namespaces that were merged. If this namespace was not merged, returns /// an array containing only this namespace. /// </summary> public virtual ImmutableArray<NamespaceSymbol> ConstituentNamespaces { get { return ImmutableArray.Create(this); } } public sealed override NamedTypeSymbol ContainingType { get { return null; } } /// <summary> /// Containing assembly. /// </summary> public abstract override AssemblySymbol ContainingAssembly { get; } internal override ModuleSymbol ContainingModule { get { var extent = this.Extent; if (extent.Kind == NamespaceKind.Module) { return extent.Module; } return null; } } /// <summary> /// Gets the kind of this symbol. /// </summary> public sealed override SymbolKind Kind { get { return SymbolKind.Namespace; } } public sealed override bool IsImplicitlyDeclared { get { return this.IsGlobalNamespace; } } /// <summary> /// Implements visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitNamespace(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitNamespace(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitNamespace(this); } // Only the compiler can create namespace symbols. internal NamespaceSymbol() { } /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns NotApplicable. /// </summary> public sealed override Accessibility DeclaredAccessibility { // C# spec 3.5.1: Namespaces implicitly have public declared accessibility. get { return Accessibility.Public; } } /// <summary> /// Returns true if this symbol is "static"; i.e., declared with the "static" modifier or /// implicitly static. /// </summary> public sealed override bool IsStatic { get { return true; } } /// <summary> /// Returns true if this symbol was declared as requiring an override; i.e., declared with /// the "abstract" modifier. Also returns true on a type declared as "abstract", all /// interface types, and members of interface types. /// </summary> public sealed override bool IsAbstract { get { return false; } } /// <summary> /// Returns true if this symbol was declared to override a base class member and was also /// sealed from further overriding; i.e., declared with the "sealed" modifier. Also set for /// types that do not allow a derived class (declared with "sealed" or "static" or "struct" /// or "enum" or "delegate"). /// </summary> public sealed override bool IsSealed { 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; } } /// <summary> /// Returns an implicit type symbol for this namespace or null if there is none. This type /// wraps misplaced global code. /// </summary> internal NamedTypeSymbol ImplicitType { get { var types = this.GetTypeMembers(TypeSymbol.ImplicitTypeName); if (types.Length == 0) { return null; } Debug.Assert(types.Length == 1); return types[0]; } } /// <summary> /// Lookup a nested namespace. /// </summary> /// <param name="names"> /// Sequence of names for nested child namespaces. /// </param> /// <returns> /// Symbol for the most nested namespace, if found. Nothing /// if namespace or any part of it can not be found. /// </returns> internal NamespaceSymbol LookupNestedNamespace(ImmutableArray<string> names) { NamespaceSymbol scope = this; foreach (string name in names) { NamespaceSymbol nextScope = null; foreach (NamespaceOrTypeSymbol symbol in scope.GetMembers(name)) { var ns = symbol as NamespaceSymbol; if ((object)ns != null) { if ((object)nextScope != null) { Debug.Assert((object)nextScope == null, "Why did we run into an unmerged namespace?"); nextScope = null; break; } nextScope = ns; } } scope = nextScope; if ((object)scope == null) { break; } } return scope; } internal NamespaceSymbol GetNestedNamespace(string name) { foreach (var sym in this.GetMembers(name)) { if (sym.Kind == SymbolKind.Namespace) { return (NamespaceSymbol)sym; } } return null; } internal NamespaceSymbol GetNestedNamespace(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: // DeclarationTreeBuilder.VisitNamespace uses the PlainName, even for generic names case SyntaxKind.IdentifierName: return this.GetNestedNamespace(((SimpleNameSyntax)name).Identifier.ValueText); case SyntaxKind.QualifiedName: var qn = (QualifiedNameSyntax)name; var leftNs = this.GetNestedNamespace(qn.Left); if ((object)leftNs != null) { return leftNs.GetNestedNamespace(qn.Right); } break; case SyntaxKind.AliasQualifiedName: // This is an error scenario, but we should still handle it. // We recover in the same way as DeclarationTreeBuilder.VisitNamespaceDeclaration. return this.GetNestedNamespace(name.GetUnqualifiedName().Identifier.ValueText); } return null; } private ImmutableArray<NamedTypeSymbol> TypesMightContainExtensionMethods { get { var typesWithExtensionMethods = this._lazyTypesMightContainExtensionMethods; if (typesWithExtensionMethods.IsDefault) { this._lazyTypesMightContainExtensionMethods = this.GetTypeMembersUnordered().WhereAsArray(t => t.MightContainExtensionMethods); typesWithExtensionMethods = this._lazyTypesMightContainExtensionMethods; } return typesWithExtensionMethods; } } /// <summary> /// Add all extension methods in this namespace to the given list. If name or arity /// or both are provided, only those extension methods that match are included. /// </summary> /// <param name="methods">Methods list</param> /// <param name="nameOpt">Optional method name</param> /// <param name="arity">Method arity</param> /// <param name="options">Lookup options</param> internal virtual void GetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string nameOpt, int arity, LookupOptions options) { var assembly = this.ContainingAssembly; // Only MergedAssemblySymbol should have a null ContainingAssembly // and MergedAssemblySymbol overrides GetExtensionMethods. Debug.Assert((object)assembly != null); if (!assembly.MightContainExtensionMethods) { return; } var typesWithExtensionMethods = this.TypesMightContainExtensionMethods; foreach (var type in typesWithExtensionMethods) { type.DoGetExtensionMethods(methods, nameOpt, arity, options); } } internal string QualifiedName { get { return _lazyQualifiedName ?? (_lazyQualifiedName = this.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)); } } protected sealed override ISymbol CreateISymbol() { return new PublicModel.NamespaceSymbol(this); } bool INamespaceSymbolInternal.IsGlobalNamespace => this.IsGlobalNamespace; } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a namespace. /// </summary> internal abstract partial class NamespaceSymbol : NamespaceOrTypeSymbol, INamespaceSymbolInternal { // PERF: initialization of the following fields will allocate, so we make them lazy private ImmutableArray<NamedTypeSymbol> _lazyTypesMightContainExtensionMethods; private string _lazyQualifiedName; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /// <summary> /// Get all the members of this symbol that are namespaces. /// </summary> /// <returns>An IEnumerable containing all the namespaces that are members of this symbol. /// If this symbol has no namespace members, returns an empty IEnumerable. Never returns /// null.</returns> public IEnumerable<NamespaceSymbol> GetNamespaceMembers() { return this.GetMembers().OfType<NamespaceSymbol>(); } /// <summary> /// Returns whether this namespace is the unnamed, global namespace that is /// at the root of all namespaces. /// </summary> public virtual bool IsGlobalNamespace { get { return (object)ContainingNamespace == null; } } internal abstract NamespaceExtent Extent { get; } /// <summary> /// The kind of namespace: Module, Assembly or Compilation. /// Module namespaces contain only members from the containing module that share the same namespace name. /// Assembly namespaces contain members for all modules in the containing assembly that share the same namespace name. /// Compilation namespaces contain all members, from source or referenced metadata (assemblies and modules) that share the same namespace name. /// </summary> public NamespaceKind NamespaceKind { get { return this.Extent.Kind; } } /// <summary> /// The containing compilation for compilation namespaces. /// </summary> public CSharpCompilation ContainingCompilation { get { return this.NamespaceKind == NamespaceKind.Compilation ? this.Extent.Compilation : null; } } /// <summary> /// If a namespace has Assembly or Compilation extent, it may be composed of multiple /// namespaces that are merged together. If so, ConstituentNamespaces returns /// all the namespaces that were merged. If this namespace was not merged, returns /// an array containing only this namespace. /// </summary> public virtual ImmutableArray<NamespaceSymbol> ConstituentNamespaces { get { return ImmutableArray.Create(this); } } public sealed override NamedTypeSymbol ContainingType { get { return null; } } /// <summary> /// Containing assembly. /// </summary> public abstract override AssemblySymbol ContainingAssembly { get; } internal override ModuleSymbol ContainingModule { get { var extent = this.Extent; if (extent.Kind == NamespaceKind.Module) { return extent.Module; } return null; } } /// <summary> /// Gets the kind of this symbol. /// </summary> public sealed override SymbolKind Kind { get { return SymbolKind.Namespace; } } public sealed override bool IsImplicitlyDeclared { get { return this.IsGlobalNamespace; } } /// <summary> /// Implements visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitNamespace(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitNamespace(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitNamespace(this); } // Only the compiler can create namespace symbols. internal NamespaceSymbol() { } /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns NotApplicable. /// </summary> public sealed override Accessibility DeclaredAccessibility { // C# spec 3.5.1: Namespaces implicitly have public declared accessibility. get { return Accessibility.Public; } } /// <summary> /// Returns true if this symbol is "static"; i.e., declared with the "static" modifier or /// implicitly static. /// </summary> public sealed override bool IsStatic { get { return true; } } /// <summary> /// Returns true if this symbol was declared as requiring an override; i.e., declared with /// the "abstract" modifier. Also returns true on a type declared as "abstract", all /// interface types, and members of interface types. /// </summary> public sealed override bool IsAbstract { get { return false; } } /// <summary> /// Returns true if this symbol was declared to override a base class member and was also /// sealed from further overriding; i.e., declared with the "sealed" modifier. Also set for /// types that do not allow a derived class (declared with "sealed" or "static" or "struct" /// or "enum" or "delegate"). /// </summary> public sealed override bool IsSealed { 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; } } /// <summary> /// Returns an implicit type symbol for this namespace or null if there is none. This type /// wraps misplaced global code. /// </summary> internal NamedTypeSymbol ImplicitType { get { var types = this.GetTypeMembers(TypeSymbol.ImplicitTypeName); if (types.Length == 0) { return null; } Debug.Assert(types.Length == 1); return types[0]; } } /// <summary> /// Lookup a nested namespace. /// </summary> /// <param name="names"> /// Sequence of names for nested child namespaces. /// </param> /// <returns> /// Symbol for the most nested namespace, if found. Nothing /// if namespace or any part of it can not be found. /// </returns> internal NamespaceSymbol LookupNestedNamespace(ImmutableArray<string> names) { NamespaceSymbol scope = this; foreach (string name in names) { NamespaceSymbol nextScope = null; foreach (NamespaceOrTypeSymbol symbol in scope.GetMembers(name)) { var ns = symbol as NamespaceSymbol; if ((object)ns != null) { if ((object)nextScope != null) { Debug.Assert((object)nextScope == null, "Why did we run into an unmerged namespace?"); nextScope = null; break; } nextScope = ns; } } scope = nextScope; if ((object)scope == null) { break; } } return scope; } internal NamespaceSymbol GetNestedNamespace(string name) { foreach (var sym in this.GetMembers(name)) { if (sym.Kind == SymbolKind.Namespace) { return (NamespaceSymbol)sym; } } return null; } internal NamespaceSymbol GetNestedNamespace(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: // DeclarationTreeBuilder.VisitNamespace uses the PlainName, even for generic names case SyntaxKind.IdentifierName: return this.GetNestedNamespace(((SimpleNameSyntax)name).Identifier.ValueText); case SyntaxKind.QualifiedName: var qn = (QualifiedNameSyntax)name; var leftNs = this.GetNestedNamespace(qn.Left); if ((object)leftNs != null) { return leftNs.GetNestedNamespace(qn.Right); } break; case SyntaxKind.AliasQualifiedName: // This is an error scenario, but we should still handle it. // We recover in the same way as DeclarationTreeBuilder.VisitNamespaceDeclaration. return this.GetNestedNamespace(name.GetUnqualifiedName().Identifier.ValueText); } return null; } private ImmutableArray<NamedTypeSymbol> TypesMightContainExtensionMethods { get { var typesWithExtensionMethods = this._lazyTypesMightContainExtensionMethods; if (typesWithExtensionMethods.IsDefault) { this._lazyTypesMightContainExtensionMethods = this.GetTypeMembersUnordered().WhereAsArray(t => t.MightContainExtensionMethods); typesWithExtensionMethods = this._lazyTypesMightContainExtensionMethods; } return typesWithExtensionMethods; } } /// <summary> /// Add all extension methods in this namespace to the given list. If name or arity /// or both are provided, only those extension methods that match are included. /// </summary> /// <param name="methods">Methods list</param> /// <param name="nameOpt">Optional method name</param> /// <param name="arity">Method arity</param> /// <param name="options">Lookup options</param> internal virtual void GetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string nameOpt, int arity, LookupOptions options) { var assembly = this.ContainingAssembly; // Only MergedAssemblySymbol should have a null ContainingAssembly // and MergedAssemblySymbol overrides GetExtensionMethods. Debug.Assert((object)assembly != null); if (!assembly.MightContainExtensionMethods) { return; } var typesWithExtensionMethods = this.TypesMightContainExtensionMethods; foreach (var type in typesWithExtensionMethods) { type.DoGetExtensionMethods(methods, nameOpt, arity, options); } } internal string QualifiedName { get { return _lazyQualifiedName ?? (_lazyQualifiedName = this.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)); } } protected sealed override ISymbol CreateISymbol() { return new PublicModel.NamespaceSymbol(this); } bool INamespaceSymbolInternal.IsGlobalNamespace => this.IsGlobalNamespace; } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.SymbolKeyWriter.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.Text; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private enum SymbolKeyType { Alias = 'A', BodyLevel = 'B', ConstructedMethod = 'C', NamedType = 'D', ErrorType = 'E', Field = 'F', FunctionPointer = 'G', DynamicType = 'I', Method = 'M', Namespace = 'N', PointerType = 'O', Parameter = 'P', Property = 'Q', ArrayType = 'R', Assembly = 'S', TupleType = 'T', Module = 'U', Event = 'V', AnonymousType = 'W', ReducedExtensionMethod = 'X', TypeParameter = 'Y', AnonymousFunctionOrDelegate = 'Z', // Not to be confused with ArrayType. This indicates an array of elements in the stream. Array = '%', Reference = '#', Null = '!', TypeParameterOrdinal = '@', } private class SymbolKeyWriter : SymbolVisitor, IDisposable { private static readonly ObjectPool<SymbolKeyWriter> s_writerPool = SharedPools.Default<SymbolKeyWriter>(); private readonly Action<ISymbol> _writeSymbolKey; private readonly Action<string?> _writeString; private readonly Action<Location?> _writeLocation; private readonly Action<bool> _writeBoolean; private readonly Action<IParameterSymbol> _writeParameterType; private readonly Action<IParameterSymbol> _writeRefKind; private readonly Dictionary<ISymbol, int> _symbolToId = new(); private readonly StringBuilder _stringBuilder = new(); public CancellationToken CancellationToken { get; private set; } private readonly List<IMethodSymbol> _methodSymbolStack = new(); internal int _nestingCount; private int _nextId; public SymbolKeyWriter() { _writeSymbolKey = WriteSymbolKey; _writeString = WriteString; _writeLocation = WriteLocation; _writeBoolean = WriteBoolean; _writeParameterType = p => WriteSymbolKey(p.Type); _writeRefKind = p => WriteRefKind(p.RefKind); } public void Dispose() { _symbolToId.Clear(); _stringBuilder.Clear(); _methodSymbolStack.Clear(); CancellationToken = default; _nestingCount = 0; _nextId = 0; // Place us back in the pool for future use. s_writerPool.Free(this); } public static SymbolKeyWriter GetWriter(CancellationToken cancellationToken) { var visitor = s_writerPool.Allocate(); visitor.Initialize(cancellationToken); return visitor; } private void Initialize(CancellationToken cancellationToken) => CancellationToken = cancellationToken; public string CreateKey() { Debug.Assert(_nestingCount == 0); return _stringBuilder.ToString(); } private void StartKey() { _stringBuilder.Append('('); _nestingCount++; } private void WriteType(SymbolKeyType type) => _stringBuilder.Append((char)type); private void EndKey() { _nestingCount--; _stringBuilder.Append(')'); } internal void WriteSymbolKey(ISymbol? symbol) { WriteSpace(); if (symbol == null) { WriteType(SymbolKeyType.Null); return; } int id; var shouldWriteOrdinal = ShouldWriteTypeParameterOrdinal(symbol, out _); if (!shouldWriteOrdinal) { if (_symbolToId.TryGetValue(symbol, out id)) { StartKey(); WriteType(SymbolKeyType.Reference); WriteInteger(id); EndKey(); return; } } id = _nextId; _nextId++; StartKey(); if (IsBodyLevelSymbol(symbol)) { WriteType(SymbolKeyType.BodyLevel); BodyLevelSymbolKey.Create(symbol, this); } else { symbol.Accept(this); } if (!shouldWriteOrdinal) { // Note: it is possible in some situations to hit the same symbol // multiple times. For example, if you have: // // Goo<Z>(List<Z> list) // // If we start with the symbol for "list" then we'll see the following // chain of symbols hit: // // List<Z> // Z // Goo<Z>(List<Z>) // List<Z> // // The recursion is prevented because when we hit 'Goo' we mark that // we're writing out a signature. And, in signature mode we only write // out the ordinal for 'Z' without recursing. However, even though // we prevent the recursion, we still hit List<Z> twice. After writing // the innermost one out, we'll give it a reference ID. When we // then hit the outermost one, we want to just reuse that one. if (_symbolToId.TryGetValue(symbol, out var existingId)) { // While we recursed, we already hit this symbol. Use its ID as our // ID. id = existingId; } else { // Haven't hit this symbol before, write out its fresh ID. _symbolToId.Add(symbol, id); } } // Now write out the ID for this symbol so that any future hits of it can // write out a reference to it instead. WriteInteger(id); EndKey(); } private void WriteSpace() => _stringBuilder.Append(' '); internal void WriteFormatVersion(int version) => WriteIntegerRaw_DoNotCallDirectly(version); internal void WriteInteger(int value) { WriteSpace(); WriteIntegerRaw_DoNotCallDirectly(value); } private void WriteIntegerRaw_DoNotCallDirectly(int value) => _stringBuilder.Append(value.ToString(CultureInfo.InvariantCulture)); internal void WriteBoolean(bool value) => WriteInteger(value ? 1 : 0); internal void WriteString(string? value) { // Strings are quoted, with all embedded quotes being doubled to escape them. WriteSpace(); if (value == null) { WriteType(SymbolKeyType.Null); } else { _stringBuilder.Append('"'); _stringBuilder.Append(value.Replace("\"", "\"\"")); _stringBuilder.Append('"'); } } internal void WriteLocation(Location? location) { WriteSpace(); if (location == null) { WriteType(SymbolKeyType.Null); return; } Debug.Assert(location.Kind == LocationKind.None || location.Kind == LocationKind.SourceFile || location.Kind == LocationKind.MetadataFile); WriteInteger((int)location.Kind); if (location.IsInSource) { WriteString(location.SourceTree.FilePath); WriteInteger(location.SourceSpan.Start); WriteInteger(location.SourceSpan.Length); } else if (location.Kind == LocationKind.MetadataFile) { WriteSymbolKey(location.MetadataModule!.ContainingAssembly); WriteString(location.MetadataModule.MetadataName); } } /// <summary> /// Writes out the provided symbols to the key. The array provided must not /// be <c>default</c>. /// </summary> internal void WriteSymbolKeyArray<TSymbol>(ImmutableArray<TSymbol> symbols) where TSymbol : ISymbol { WriteArray(symbols, _writeSymbolKey); } internal void WriteParameterTypesArray(ImmutableArray<IParameterSymbol> symbols) => WriteArray(symbols, _writeParameterType); internal void WriteBooleanArray(ImmutableArray<bool> array) => WriteArray(array, _writeBoolean); // annotating WriteStringArray and WriteLocationArray as allowing null elements // then causes issues where we can't pass ImmutableArrays of non-null elements #nullable disable internal void WriteStringArray(ImmutableArray<string> strings) => WriteArray(strings, _writeString); internal void WriteLocationArray(ImmutableArray<Location> array) => WriteArray(array, _writeLocation); #nullable enable internal void WriteRefKindArray(ImmutableArray<IParameterSymbol> values) => WriteArray(values, _writeRefKind); private void WriteArray<T, U>(ImmutableArray<T> array, Action<U> writeValue) where T : U { WriteSpace(); Debug.Assert(!array.IsDefault); StartKey(); WriteType(SymbolKeyType.Array); WriteInteger(array.Length); foreach (var value in array) { writeValue(value); } EndKey(); } internal void WriteRefKind(RefKind refKind) => WriteInteger((int)refKind); public override void VisitAlias(IAliasSymbol aliasSymbol) { WriteType(SymbolKeyType.Alias); AliasSymbolKey.Create(aliasSymbol, this); } public override void VisitArrayType(IArrayTypeSymbol arrayTypeSymbol) { WriteType(SymbolKeyType.ArrayType); ArrayTypeSymbolKey.Create(arrayTypeSymbol, this); } public override void VisitAssembly(IAssemblySymbol assemblySymbol) { WriteType(SymbolKeyType.Assembly); AssemblySymbolKey.Create(assemblySymbol, this); } public override void VisitDynamicType(IDynamicTypeSymbol dynamicTypeSymbol) { WriteType(SymbolKeyType.DynamicType); DynamicTypeSymbolKey.Create(this); } public override void VisitField(IFieldSymbol fieldSymbol) { WriteType(SymbolKeyType.Field); FieldSymbolKey.Create(fieldSymbol, this); } public override void VisitLabel(ILabelSymbol labelSymbol) => throw ExceptionUtilities.Unreachable; public override void VisitLocal(ILocalSymbol localSymbol) => throw ExceptionUtilities.Unreachable; public override void VisitRangeVariable(IRangeVariableSymbol rangeVariableSymbol) => throw ExceptionUtilities.Unreachable; public override void VisitMethod(IMethodSymbol methodSymbol) { if (!methodSymbol.Equals(methodSymbol.ConstructedFrom)) { WriteType(SymbolKeyType.ConstructedMethod); ConstructedMethodSymbolKey.Create(methodSymbol, this); } else { switch (methodSymbol.MethodKind) { case MethodKind.ReducedExtension: WriteType(SymbolKeyType.ReducedExtensionMethod); ReducedExtensionMethodSymbolKey.Create(methodSymbol, this); break; case MethodKind.AnonymousFunction: WriteType(SymbolKeyType.AnonymousFunctionOrDelegate); AnonymousFunctionOrDelegateSymbolKey.Create(methodSymbol, this); break; case MethodKind.LocalFunction: throw ExceptionUtilities.Unreachable; default: WriteType(SymbolKeyType.Method); MethodSymbolKey.Create(methodSymbol, this); break; } } } public override void VisitModule(IModuleSymbol moduleSymbol) { WriteType(SymbolKeyType.Module); ModuleSymbolKey.Create(moduleSymbol, this); } public override void VisitNamedType(INamedTypeSymbol namedTypeSymbol) { if (namedTypeSymbol.TypeKind == TypeKind.Error) { WriteType(SymbolKeyType.ErrorType); ErrorTypeSymbolKey.Create(namedTypeSymbol, this); } else if (namedTypeSymbol.IsTupleType && namedTypeSymbol.TupleUnderlyingType is INamedTypeSymbol underlyingType && underlyingType != namedTypeSymbol) { // A tuple is a named type with some added information // We only need to store this extra information if there is some // (ie. the current type differs from the underlying type, which has no element names) WriteType(SymbolKeyType.TupleType); TupleTypeSymbolKey.Create(namedTypeSymbol, this); } else if (namedTypeSymbol.IsAnonymousType) { if (namedTypeSymbol.IsAnonymousDelegateType()) { WriteType(SymbolKeyType.AnonymousFunctionOrDelegate); AnonymousFunctionOrDelegateSymbolKey.Create(namedTypeSymbol, this); } else { WriteType(SymbolKeyType.AnonymousType); AnonymousTypeSymbolKey.Create(namedTypeSymbol, this); } } else { WriteType(SymbolKeyType.NamedType); NamedTypeSymbolKey.Create(namedTypeSymbol, this); } } public override void VisitNamespace(INamespaceSymbol namespaceSymbol) { WriteType(SymbolKeyType.Namespace); NamespaceSymbolKey.Create(namespaceSymbol, this); } public override void VisitParameter(IParameterSymbol parameterSymbol) { WriteType(SymbolKeyType.Parameter); ParameterSymbolKey.Create(parameterSymbol, this); } public override void VisitPointerType(IPointerTypeSymbol pointerTypeSymbol) { WriteType(SymbolKeyType.PointerType); PointerTypeSymbolKey.Create(pointerTypeSymbol, this); } public override void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { WriteType(SymbolKeyType.FunctionPointer); FunctionPointerTypeSymbolKey.Create(symbol, this); } public override void VisitProperty(IPropertySymbol propertySymbol) { WriteType(SymbolKeyType.Property); PropertySymbolKey.Create(propertySymbol, this); } public override void VisitEvent(IEventSymbol eventSymbol) { WriteType(SymbolKeyType.Event); EventSymbolKey.Create(eventSymbol, this); } public override void VisitTypeParameter(ITypeParameterSymbol typeParameterSymbol) { // If it's a reference to a method type parameter, and we're currently writing // out a signture, then only write out the ordinal of type parameter. This // helps prevent recursion problems in cases like "Goo<T>(T t). if (ShouldWriteTypeParameterOrdinal(typeParameterSymbol, out var methodIndex)) { WriteType(SymbolKeyType.TypeParameterOrdinal); TypeParameterOrdinalSymbolKey.Create(typeParameterSymbol, methodIndex, this); } else { WriteType(SymbolKeyType.TypeParameter); TypeParameterSymbolKey.Create(typeParameterSymbol, this); } } public bool ShouldWriteTypeParameterOrdinal(ISymbol symbol, out int methodIndex) { if (symbol.Kind == SymbolKind.TypeParameter) { var typeParameter = (ITypeParameterSymbol)symbol; if (typeParameter.TypeParameterKind == TypeParameterKind.Method) { for (int i = 0, n = _methodSymbolStack.Count; i < n; i++) { var method = _methodSymbolStack[i]; if (typeParameter.DeclaringMethod!.Equals(method)) { methodIndex = i; return true; } } } } methodIndex = -1; return false; } public void PushMethod(IMethodSymbol method) => _methodSymbolStack.Add(method); public void PopMethod(IMethodSymbol method) { Contract.ThrowIfTrue(_methodSymbolStack.Count == 0); Contract.ThrowIfFalse(method.Equals(_methodSymbolStack[_methodSymbolStack.Count - 1])); _methodSymbolStack.RemoveAt(_methodSymbolStack.Count - 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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private enum SymbolKeyType { Alias = 'A', BodyLevel = 'B', ConstructedMethod = 'C', NamedType = 'D', ErrorType = 'E', Field = 'F', FunctionPointer = 'G', DynamicType = 'I', Method = 'M', Namespace = 'N', PointerType = 'O', Parameter = 'P', Property = 'Q', ArrayType = 'R', Assembly = 'S', TupleType = 'T', Module = 'U', Event = 'V', AnonymousType = 'W', ReducedExtensionMethod = 'X', TypeParameter = 'Y', AnonymousFunctionOrDelegate = 'Z', // Not to be confused with ArrayType. This indicates an array of elements in the stream. Array = '%', Reference = '#', Null = '!', TypeParameterOrdinal = '@', } private class SymbolKeyWriter : SymbolVisitor, IDisposable { private static readonly ObjectPool<SymbolKeyWriter> s_writerPool = SharedPools.Default<SymbolKeyWriter>(); private readonly Action<ISymbol> _writeSymbolKey; private readonly Action<string?> _writeString; private readonly Action<Location?> _writeLocation; private readonly Action<bool> _writeBoolean; private readonly Action<IParameterSymbol> _writeParameterType; private readonly Action<IParameterSymbol> _writeRefKind; private readonly Dictionary<ISymbol, int> _symbolToId = new(); private readonly StringBuilder _stringBuilder = new(); public CancellationToken CancellationToken { get; private set; } private readonly List<IMethodSymbol> _methodSymbolStack = new(); internal int _nestingCount; private int _nextId; public SymbolKeyWriter() { _writeSymbolKey = WriteSymbolKey; _writeString = WriteString; _writeLocation = WriteLocation; _writeBoolean = WriteBoolean; _writeParameterType = p => WriteSymbolKey(p.Type); _writeRefKind = p => WriteRefKind(p.RefKind); } public void Dispose() { _symbolToId.Clear(); _stringBuilder.Clear(); _methodSymbolStack.Clear(); CancellationToken = default; _nestingCount = 0; _nextId = 0; // Place us back in the pool for future use. s_writerPool.Free(this); } public static SymbolKeyWriter GetWriter(CancellationToken cancellationToken) { var visitor = s_writerPool.Allocate(); visitor.Initialize(cancellationToken); return visitor; } private void Initialize(CancellationToken cancellationToken) => CancellationToken = cancellationToken; public string CreateKey() { Debug.Assert(_nestingCount == 0); return _stringBuilder.ToString(); } private void StartKey() { _stringBuilder.Append('('); _nestingCount++; } private void WriteType(SymbolKeyType type) => _stringBuilder.Append((char)type); private void EndKey() { _nestingCount--; _stringBuilder.Append(')'); } internal void WriteSymbolKey(ISymbol? symbol) { WriteSpace(); if (symbol == null) { WriteType(SymbolKeyType.Null); return; } int id; var shouldWriteOrdinal = ShouldWriteTypeParameterOrdinal(symbol, out _); if (!shouldWriteOrdinal) { if (_symbolToId.TryGetValue(symbol, out id)) { StartKey(); WriteType(SymbolKeyType.Reference); WriteInteger(id); EndKey(); return; } } id = _nextId; _nextId++; StartKey(); if (IsBodyLevelSymbol(symbol)) { WriteType(SymbolKeyType.BodyLevel); BodyLevelSymbolKey.Create(symbol, this); } else { symbol.Accept(this); } if (!shouldWriteOrdinal) { // Note: it is possible in some situations to hit the same symbol // multiple times. For example, if you have: // // Goo<Z>(List<Z> list) // // If we start with the symbol for "list" then we'll see the following // chain of symbols hit: // // List<Z> // Z // Goo<Z>(List<Z>) // List<Z> // // The recursion is prevented because when we hit 'Goo' we mark that // we're writing out a signature. And, in signature mode we only write // out the ordinal for 'Z' without recursing. However, even though // we prevent the recursion, we still hit List<Z> twice. After writing // the innermost one out, we'll give it a reference ID. When we // then hit the outermost one, we want to just reuse that one. if (_symbolToId.TryGetValue(symbol, out var existingId)) { // While we recursed, we already hit this symbol. Use its ID as our // ID. id = existingId; } else { // Haven't hit this symbol before, write out its fresh ID. _symbolToId.Add(symbol, id); } } // Now write out the ID for this symbol so that any future hits of it can // write out a reference to it instead. WriteInteger(id); EndKey(); } private void WriteSpace() => _stringBuilder.Append(' '); internal void WriteFormatVersion(int version) => WriteIntegerRaw_DoNotCallDirectly(version); internal void WriteInteger(int value) { WriteSpace(); WriteIntegerRaw_DoNotCallDirectly(value); } private void WriteIntegerRaw_DoNotCallDirectly(int value) => _stringBuilder.Append(value.ToString(CultureInfo.InvariantCulture)); internal void WriteBoolean(bool value) => WriteInteger(value ? 1 : 0); internal void WriteString(string? value) { // Strings are quoted, with all embedded quotes being doubled to escape them. WriteSpace(); if (value == null) { WriteType(SymbolKeyType.Null); } else { _stringBuilder.Append('"'); _stringBuilder.Append(value.Replace("\"", "\"\"")); _stringBuilder.Append('"'); } } internal void WriteLocation(Location? location) { WriteSpace(); if (location == null) { WriteType(SymbolKeyType.Null); return; } Debug.Assert(location.Kind == LocationKind.None || location.Kind == LocationKind.SourceFile || location.Kind == LocationKind.MetadataFile); WriteInteger((int)location.Kind); if (location.IsInSource) { WriteString(location.SourceTree.FilePath); WriteInteger(location.SourceSpan.Start); WriteInteger(location.SourceSpan.Length); } else if (location.Kind == LocationKind.MetadataFile) { WriteSymbolKey(location.MetadataModule!.ContainingAssembly); WriteString(location.MetadataModule.MetadataName); } } /// <summary> /// Writes out the provided symbols to the key. The array provided must not /// be <c>default</c>. /// </summary> internal void WriteSymbolKeyArray<TSymbol>(ImmutableArray<TSymbol> symbols) where TSymbol : ISymbol { WriteArray(symbols, _writeSymbolKey); } internal void WriteParameterTypesArray(ImmutableArray<IParameterSymbol> symbols) => WriteArray(symbols, _writeParameterType); internal void WriteBooleanArray(ImmutableArray<bool> array) => WriteArray(array, _writeBoolean); // annotating WriteStringArray and WriteLocationArray as allowing null elements // then causes issues where we can't pass ImmutableArrays of non-null elements #nullable disable internal void WriteStringArray(ImmutableArray<string> strings) => WriteArray(strings, _writeString); internal void WriteLocationArray(ImmutableArray<Location> array) => WriteArray(array, _writeLocation); #nullable enable internal void WriteRefKindArray(ImmutableArray<IParameterSymbol> values) => WriteArray(values, _writeRefKind); private void WriteArray<T, U>(ImmutableArray<T> array, Action<U> writeValue) where T : U { WriteSpace(); Debug.Assert(!array.IsDefault); StartKey(); WriteType(SymbolKeyType.Array); WriteInteger(array.Length); foreach (var value in array) { writeValue(value); } EndKey(); } internal void WriteRefKind(RefKind refKind) => WriteInteger((int)refKind); public override void VisitAlias(IAliasSymbol aliasSymbol) { WriteType(SymbolKeyType.Alias); AliasSymbolKey.Create(aliasSymbol, this); } public override void VisitArrayType(IArrayTypeSymbol arrayTypeSymbol) { WriteType(SymbolKeyType.ArrayType); ArrayTypeSymbolKey.Create(arrayTypeSymbol, this); } public override void VisitAssembly(IAssemblySymbol assemblySymbol) { WriteType(SymbolKeyType.Assembly); AssemblySymbolKey.Create(assemblySymbol, this); } public override void VisitDynamicType(IDynamicTypeSymbol dynamicTypeSymbol) { WriteType(SymbolKeyType.DynamicType); DynamicTypeSymbolKey.Create(this); } public override void VisitField(IFieldSymbol fieldSymbol) { WriteType(SymbolKeyType.Field); FieldSymbolKey.Create(fieldSymbol, this); } public override void VisitLabel(ILabelSymbol labelSymbol) => throw ExceptionUtilities.Unreachable; public override void VisitLocal(ILocalSymbol localSymbol) => throw ExceptionUtilities.Unreachable; public override void VisitRangeVariable(IRangeVariableSymbol rangeVariableSymbol) => throw ExceptionUtilities.Unreachable; public override void VisitMethod(IMethodSymbol methodSymbol) { if (!methodSymbol.Equals(methodSymbol.ConstructedFrom)) { WriteType(SymbolKeyType.ConstructedMethod); ConstructedMethodSymbolKey.Create(methodSymbol, this); } else { switch (methodSymbol.MethodKind) { case MethodKind.ReducedExtension: WriteType(SymbolKeyType.ReducedExtensionMethod); ReducedExtensionMethodSymbolKey.Create(methodSymbol, this); break; case MethodKind.AnonymousFunction: WriteType(SymbolKeyType.AnonymousFunctionOrDelegate); AnonymousFunctionOrDelegateSymbolKey.Create(methodSymbol, this); break; case MethodKind.LocalFunction: throw ExceptionUtilities.Unreachable; default: WriteType(SymbolKeyType.Method); MethodSymbolKey.Create(methodSymbol, this); break; } } } public override void VisitModule(IModuleSymbol moduleSymbol) { WriteType(SymbolKeyType.Module); ModuleSymbolKey.Create(moduleSymbol, this); } public override void VisitNamedType(INamedTypeSymbol namedTypeSymbol) { if (namedTypeSymbol.TypeKind == TypeKind.Error) { WriteType(SymbolKeyType.ErrorType); ErrorTypeSymbolKey.Create(namedTypeSymbol, this); } else if (namedTypeSymbol.IsTupleType && namedTypeSymbol.TupleUnderlyingType is INamedTypeSymbol underlyingType && underlyingType != namedTypeSymbol) { // A tuple is a named type with some added information // We only need to store this extra information if there is some // (ie. the current type differs from the underlying type, which has no element names) WriteType(SymbolKeyType.TupleType); TupleTypeSymbolKey.Create(namedTypeSymbol, this); } else if (namedTypeSymbol.IsAnonymousType) { if (namedTypeSymbol.IsAnonymousDelegateType()) { WriteType(SymbolKeyType.AnonymousFunctionOrDelegate); AnonymousFunctionOrDelegateSymbolKey.Create(namedTypeSymbol, this); } else { WriteType(SymbolKeyType.AnonymousType); AnonymousTypeSymbolKey.Create(namedTypeSymbol, this); } } else { WriteType(SymbolKeyType.NamedType); NamedTypeSymbolKey.Create(namedTypeSymbol, this); } } public override void VisitNamespace(INamespaceSymbol namespaceSymbol) { WriteType(SymbolKeyType.Namespace); NamespaceSymbolKey.Create(namespaceSymbol, this); } public override void VisitParameter(IParameterSymbol parameterSymbol) { WriteType(SymbolKeyType.Parameter); ParameterSymbolKey.Create(parameterSymbol, this); } public override void VisitPointerType(IPointerTypeSymbol pointerTypeSymbol) { WriteType(SymbolKeyType.PointerType); PointerTypeSymbolKey.Create(pointerTypeSymbol, this); } public override void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { WriteType(SymbolKeyType.FunctionPointer); FunctionPointerTypeSymbolKey.Create(symbol, this); } public override void VisitProperty(IPropertySymbol propertySymbol) { WriteType(SymbolKeyType.Property); PropertySymbolKey.Create(propertySymbol, this); } public override void VisitEvent(IEventSymbol eventSymbol) { WriteType(SymbolKeyType.Event); EventSymbolKey.Create(eventSymbol, this); } public override void VisitTypeParameter(ITypeParameterSymbol typeParameterSymbol) { // If it's a reference to a method type parameter, and we're currently writing // out a signture, then only write out the ordinal of type parameter. This // helps prevent recursion problems in cases like "Goo<T>(T t). if (ShouldWriteTypeParameterOrdinal(typeParameterSymbol, out var methodIndex)) { WriteType(SymbolKeyType.TypeParameterOrdinal); TypeParameterOrdinalSymbolKey.Create(typeParameterSymbol, methodIndex, this); } else { WriteType(SymbolKeyType.TypeParameter); TypeParameterSymbolKey.Create(typeParameterSymbol, this); } } public bool ShouldWriteTypeParameterOrdinal(ISymbol symbol, out int methodIndex) { if (symbol.Kind == SymbolKind.TypeParameter) { var typeParameter = (ITypeParameterSymbol)symbol; if (typeParameter.TypeParameterKind == TypeParameterKind.Method) { for (int i = 0, n = _methodSymbolStack.Count; i < n; i++) { var method = _methodSymbolStack[i]; if (typeParameter.DeclaringMethod!.Equals(method)) { methodIndex = i; return true; } } } } methodIndex = -1; return false; } public void PushMethod(IMethodSymbol method) => _methodSymbolStack.Add(method); public void PopMethod(IMethodSymbol method) { Contract.ThrowIfTrue(_methodSymbolStack.Count == 0); Contract.ThrowIfFalse(method.Equals(_methodSymbolStack[_methodSymbolStack.Count - 1])); _methodSymbolStack.RemoveAt(_methodSymbolStack.Count - 1); } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/VisualBasicTest/ConvertCast/ConvertTryCastToDirectCastTests.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.VisualBasicCodeRefactoringVerifier(Of Microsoft.CodeAnalysis.VisualBasic.ConvertConversionOperators.VisualBasicConvertTryCastToDirectCastCodeRefactoringProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertCast <Trait(Traits.Feature, Traits.Features.ConvertCast)> Public Class ConvertTryCastToDirectCastTests <Fact> Public Async Function ConvertFromTryCastToDirectCast() As Task Dim markup = " Module Program Sub M() Dim x = TryCast(1[||], Object) End Sub End Module " Dim expected = " Module Program Sub M() Dim x = DirectCast(1, Object) End Sub End Module " Await New VerifyVB.Test With { .TestCode = markup, .FixedCode = expected }.RunAsync() End Function <Theory> <InlineData("TryCast(TryCast(1, [||]object), C)", "TryCast(DirectCast(1, object), C)")> <InlineData("TryCast(TryCast(1, object), [||]C)", "DirectCast(TryCast(1, object), C)")> Public Async Function ConvertFromTryCastNested(DirectCastExpression As String, converted As String) As Task Dim markup = " Public Class C End Class Module Program Sub M() Dim x = " + DirectCastExpression + " End Sub End Module " Dim fixed = " Public Class C End Class Module Program Sub M() Dim x = " + converted + " End Sub End Module " Await New VerifyVB.Test With { .TestCode = markup, .FixedCode = fixed }.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.VisualBasicCodeRefactoringVerifier(Of Microsoft.CodeAnalysis.VisualBasic.ConvertConversionOperators.VisualBasicConvertTryCastToDirectCastCodeRefactoringProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertCast <Trait(Traits.Feature, Traits.Features.ConvertCast)> Public Class ConvertTryCastToDirectCastTests <Fact> Public Async Function ConvertFromTryCastToDirectCast() As Task Dim markup = " Module Program Sub M() Dim x = TryCast(1[||], Object) End Sub End Module " Dim expected = " Module Program Sub M() Dim x = DirectCast(1, Object) End Sub End Module " Await New VerifyVB.Test With { .TestCode = markup, .FixedCode = expected }.RunAsync() End Function <Theory> <InlineData("TryCast(TryCast(1, [||]object), C)", "TryCast(DirectCast(1, object), C)")> <InlineData("TryCast(TryCast(1, object), [||]C)", "DirectCast(TryCast(1, object), C)")> Public Async Function ConvertFromTryCastNested(DirectCastExpression As String, converted As String) As Task Dim markup = " Public Class C End Class Module Program Sub M() Dim x = " + DirectCastExpression + " End Sub End Module " Dim fixed = " Public Class C End Class Module Program Sub M() Dim x = " + converted + " End Sub End Module " Await New VerifyVB.Test With { .TestCode = markup, .FixedCode = fixed }.RunAsync() End Function End Class End Namespace
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Core/Portable/Compilation/SubsystemVersion.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.Globalization; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents subsystem version, see /subsystemversion command line /// option for details and valid values. /// /// The following table lists common subsystem versions of Windows. /// /// Windows version Subsystem version /// - Windows 2000 5.00 /// - Windows XP 5.01 /// - Windows Vista 6.00 /// - Windows 7 6.01 /// - Windows 8 Release Preview 6.02 /// </summary> public struct SubsystemVersion : IEquatable<SubsystemVersion> { /// <summary> /// Major subsystem version /// </summary> public int Major { get; } /// <summary> /// Minor subsystem version /// </summary> public int Minor { get; } /// <summary> /// Subsystem version not specified /// </summary> public static SubsystemVersion None => new SubsystemVersion(); /// <summary> /// Subsystem version: Windows 2000 /// </summary> public static SubsystemVersion Windows2000 => new SubsystemVersion(5, 0); /// <summary> /// Subsystem version: Windows XP /// </summary> public static SubsystemVersion WindowsXP => new SubsystemVersion(5, 1); /// <summary> /// Subsystem version: Windows Vista /// </summary> public static SubsystemVersion WindowsVista => new SubsystemVersion(6, 0); /// <summary> /// Subsystem version: Windows 7 /// </summary> public static SubsystemVersion Windows7 => new SubsystemVersion(6, 1); /// <summary> /// Subsystem version: Windows 8 /// </summary> public static SubsystemVersion Windows8 => new SubsystemVersion(6, 2); private SubsystemVersion(int major, int minor) { this.Major = major; this.Minor = minor; } /// <summary> /// Try parse subsystem version in "x.y" format. Note, no spaces are allowed in string representation. /// </summary> /// <param name="str">String to parse</param> /// <param name="version">the value if successfully parsed or None otherwise</param> /// <returns>true if parsed successfully, false otherwise</returns> public static bool TryParse(string str, out SubsystemVersion version) { version = SubsystemVersion.None; if (!string.IsNullOrWhiteSpace(str)) { string major; string? minor; int index = str.IndexOf('.'); //found a dot if (index >= 0) { //if there's a dot and no following digits, it's an error in the native compiler. if (str.Length == index + 1) return false; major = str.Substring(0, index); minor = str.Substring(index + 1); } else { major = str; minor = null; } int majorValue; if (major != major.Trim() || !int.TryParse(major, NumberStyles.None, CultureInfo.InvariantCulture, out majorValue) || majorValue >= 65356 || majorValue < 0) { return false; } int minorValue = 0; //it's fine to have just a single number specified for the subsystem. if (minor != null) { if (minor != minor.Trim() || !int.TryParse(minor, NumberStyles.None, CultureInfo.InvariantCulture, out minorValue) || minorValue >= 65356 || minorValue < 0) { return false; } } version = new SubsystemVersion(majorValue, minorValue); return true; } return false; } /// <summary> /// Create a new instance of subsystem version with specified major and minor values. /// </summary> /// <param name="major">major subsystem version</param> /// <param name="minor">minor subsystem version</param> /// <returns>subsystem version with provided major and minor</returns> public static SubsystemVersion Create(int major, int minor) { return new SubsystemVersion(major, minor); } /// <summary> /// Subsystem version default for the specified output kind and platform combination /// </summary> /// <param name="outputKind">Output kind</param> /// <param name="platform">Platform</param> /// <returns>Subsystem version</returns> internal static SubsystemVersion Default(OutputKind outputKind, Platform platform) { if (platform == Platform.Arm) return Windows8; switch (outputKind) { case OutputKind.ConsoleApplication: case OutputKind.DynamicallyLinkedLibrary: case OutputKind.NetModule: case OutputKind.WindowsApplication: return new SubsystemVersion(4, 0); case OutputKind.WindowsRuntimeApplication: case OutputKind.WindowsRuntimeMetadata: return Windows8; default: throw new ArgumentOutOfRangeException(CodeAnalysisResources.OutputKindNotSupported, "outputKind"); } } /// <summary> /// True if the subsystem version has a valid value /// </summary> public bool IsValid { get { return this.Major >= 0 && this.Minor >= 0 && this.Major < 65536 && this.Minor < 65536; } } public override bool Equals(object? obj) { return obj is SubsystemVersion && Equals((SubsystemVersion)obj); } public override int GetHashCode() { return Hash.Combine(this.Minor.GetHashCode(), this.Major.GetHashCode()); } public bool Equals(SubsystemVersion other) { return this.Major == other.Major && this.Minor == other.Minor; } public override string ToString() { return string.Format("{0}.{1:00}", this.Major, this.Minor); } } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents subsystem version, see /subsystemversion command line /// option for details and valid values. /// /// The following table lists common subsystem versions of Windows. /// /// Windows version Subsystem version /// - Windows 2000 5.00 /// - Windows XP 5.01 /// - Windows Vista 6.00 /// - Windows 7 6.01 /// - Windows 8 Release Preview 6.02 /// </summary> public struct SubsystemVersion : IEquatable<SubsystemVersion> { /// <summary> /// Major subsystem version /// </summary> public int Major { get; } /// <summary> /// Minor subsystem version /// </summary> public int Minor { get; } /// <summary> /// Subsystem version not specified /// </summary> public static SubsystemVersion None => new SubsystemVersion(); /// <summary> /// Subsystem version: Windows 2000 /// </summary> public static SubsystemVersion Windows2000 => new SubsystemVersion(5, 0); /// <summary> /// Subsystem version: Windows XP /// </summary> public static SubsystemVersion WindowsXP => new SubsystemVersion(5, 1); /// <summary> /// Subsystem version: Windows Vista /// </summary> public static SubsystemVersion WindowsVista => new SubsystemVersion(6, 0); /// <summary> /// Subsystem version: Windows 7 /// </summary> public static SubsystemVersion Windows7 => new SubsystemVersion(6, 1); /// <summary> /// Subsystem version: Windows 8 /// </summary> public static SubsystemVersion Windows8 => new SubsystemVersion(6, 2); private SubsystemVersion(int major, int minor) { this.Major = major; this.Minor = minor; } /// <summary> /// Try parse subsystem version in "x.y" format. Note, no spaces are allowed in string representation. /// </summary> /// <param name="str">String to parse</param> /// <param name="version">the value if successfully parsed or None otherwise</param> /// <returns>true if parsed successfully, false otherwise</returns> public static bool TryParse(string str, out SubsystemVersion version) { version = SubsystemVersion.None; if (!string.IsNullOrWhiteSpace(str)) { string major; string? minor; int index = str.IndexOf('.'); //found a dot if (index >= 0) { //if there's a dot and no following digits, it's an error in the native compiler. if (str.Length == index + 1) return false; major = str.Substring(0, index); minor = str.Substring(index + 1); } else { major = str; minor = null; } int majorValue; if (major != major.Trim() || !int.TryParse(major, NumberStyles.None, CultureInfo.InvariantCulture, out majorValue) || majorValue >= 65356 || majorValue < 0) { return false; } int minorValue = 0; //it's fine to have just a single number specified for the subsystem. if (minor != null) { if (minor != minor.Trim() || !int.TryParse(minor, NumberStyles.None, CultureInfo.InvariantCulture, out minorValue) || minorValue >= 65356 || minorValue < 0) { return false; } } version = new SubsystemVersion(majorValue, minorValue); return true; } return false; } /// <summary> /// Create a new instance of subsystem version with specified major and minor values. /// </summary> /// <param name="major">major subsystem version</param> /// <param name="minor">minor subsystem version</param> /// <returns>subsystem version with provided major and minor</returns> public static SubsystemVersion Create(int major, int minor) { return new SubsystemVersion(major, minor); } /// <summary> /// Subsystem version default for the specified output kind and platform combination /// </summary> /// <param name="outputKind">Output kind</param> /// <param name="platform">Platform</param> /// <returns>Subsystem version</returns> internal static SubsystemVersion Default(OutputKind outputKind, Platform platform) { if (platform == Platform.Arm) return Windows8; switch (outputKind) { case OutputKind.ConsoleApplication: case OutputKind.DynamicallyLinkedLibrary: case OutputKind.NetModule: case OutputKind.WindowsApplication: return new SubsystemVersion(4, 0); case OutputKind.WindowsRuntimeApplication: case OutputKind.WindowsRuntimeMetadata: return Windows8; default: throw new ArgumentOutOfRangeException(CodeAnalysisResources.OutputKindNotSupported, "outputKind"); } } /// <summary> /// True if the subsystem version has a valid value /// </summary> public bool IsValid { get { return this.Major >= 0 && this.Minor >= 0 && this.Major < 65536 && this.Minor < 65536; } } public override bool Equals(object? obj) { return obj is SubsystemVersion && Equals((SubsystemVersion)obj); } public override int GetHashCode() { return Hash.Combine(this.Minor.GetHashCode(), this.Major.GetHashCode()); } public bool Equals(SubsystemVersion other) { return this.Major == other.Major && this.Minor == other.Minor; } public override string ToString() { return string.Format("{0}.{1:00}", this.Major, this.Minor); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Queries/SkipKeywordRecommender.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.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries ''' <summary> ''' Recommends the Skip operator for Skip/Skip While. ''' </summary> Friend Class SkipKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Skip", VBFeaturesResources.Skips_elements_up_to_a_specified_position_in_the_collection)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Return If(context.IsQueryOperatorContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) 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.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries ''' <summary> ''' Recommends the Skip operator for Skip/Skip While. ''' </summary> Friend Class SkipKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Skip", VBFeaturesResources.Skips_elements_up_to_a_specified_position_in_the_collection)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Return If(context.IsQueryOperatorContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Extensions/IVsHierarchyExtensions.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.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal static class IVsHierarchyExtensions { public static bool TryGetItemProperty<T>(this IVsHierarchy hierarchy, uint itemId, int propertyId, [MaybeNullWhen(false)] out T value) { if (ErrorHandler.Failed(hierarchy.GetProperty(itemId, propertyId, out var property)) || !(property is T)) { value = default; return false; } value = (T)property; return true; } public static bool TryGetProperty<T>(this IVsHierarchy hierarchy, int propertyId, [MaybeNullWhen(false)] out T value) { const uint root = VSConstants.VSITEMID_ROOT; return hierarchy.TryGetItemProperty(root, propertyId, out value); } public static bool TryGetProperty<T>(this IVsHierarchy hierarchy, __VSHPROPID propertyId, [MaybeNullWhen(false)] out T value) => hierarchy.TryGetProperty((int)propertyId, out value); public static bool TryGetItemProperty<T>(this IVsHierarchy hierarchy, uint itemId, __VSHPROPID propertyId, [MaybeNullWhen(false)] out T value) => hierarchy.TryGetItemProperty(itemId, (int)propertyId, out value); public static bool TryGetGuidProperty(this IVsHierarchy hierarchy, int propertyId, out Guid guid) => ErrorHandler.Succeeded(hierarchy.GetGuidProperty(VSConstants.VSITEMID_ROOT, propertyId, out guid)); public static bool TryGetGuidProperty(this IVsHierarchy hierarchy, __VSHPROPID propertyId, out Guid guid) => ErrorHandler.Succeeded(hierarchy.GetGuidProperty(VSConstants.VSITEMID_ROOT, (int)propertyId, out guid)); public static bool TryGetProject(this IVsHierarchy hierarchy, [NotNullWhen(returnValue: true)] out EnvDTE.Project? project) => hierarchy.TryGetProperty<EnvDTE.Project>(__VSHPROPID.VSHPROPID_ExtObject, out project); public static bool TryGetName(this IVsHierarchy hierarchy, [NotNullWhen(returnValue: true)] out string? name) => hierarchy.TryGetProperty<string>(__VSHPROPID.VSHPROPID_Name, out name); public static bool TryGetItemName(this IVsHierarchy hierarchy, uint itemId, [NotNullWhen(returnValue: true)] out string? name) => hierarchy.TryGetItemProperty<string>(itemId, __VSHPROPID.VSHPROPID_Name, out name); public static bool TryGetCanonicalName(this IVsHierarchy hierarchy, uint itemId, [NotNullWhen(returnValue: true)] out string? name) => ErrorHandler.Succeeded(hierarchy.GetCanonicalName(itemId, out name)); public static bool TryGetParentHierarchy(this IVsHierarchy hierarchy, [NotNullWhen(returnValue: true)] out IVsHierarchy? parentHierarchy) => hierarchy.TryGetProperty<IVsHierarchy>(__VSHPROPID.VSHPROPID_ParentHierarchy, out parentHierarchy); public static bool TryGetTypeGuid(this IVsHierarchy hierarchy, out Guid typeGuid) => hierarchy.TryGetGuidProperty(__VSHPROPID.VSHPROPID_TypeGuid, out typeGuid); public static bool TryGetTargetFrameworkMoniker(this IVsHierarchy hierarchy, uint itemId, [NotNullWhen(returnValue: true)] out string? targetFrameworkMoniker) => hierarchy.TryGetItemProperty<string>(itemId, (int)__VSHPROPID4.VSHPROPID_TargetFrameworkMoniker, out targetFrameworkMoniker); public static uint TryGetItemId(this IVsHierarchy hierarchy, string moniker) { if (ErrorHandler.Succeeded(hierarchy.ParseCanonicalName(moniker, out var itemid))) { return itemid; } return VSConstants.VSITEMID_NIL; } public static string? TryGetProjectFilePath(this IVsHierarchy hierarchy) { if (ErrorHandler.Succeeded(((IVsProject3)hierarchy).GetMkDocument((uint)VSConstants.VSITEMID.Root, out var projectFilePath)) && !string.IsNullOrEmpty(projectFilePath)) { return projectFilePath; } return 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; using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal static class IVsHierarchyExtensions { public static bool TryGetItemProperty<T>(this IVsHierarchy hierarchy, uint itemId, int propertyId, [MaybeNullWhen(false)] out T value) { if (ErrorHandler.Failed(hierarchy.GetProperty(itemId, propertyId, out var property)) || !(property is T)) { value = default; return false; } value = (T)property; return true; } public static bool TryGetProperty<T>(this IVsHierarchy hierarchy, int propertyId, [MaybeNullWhen(false)] out T value) { const uint root = VSConstants.VSITEMID_ROOT; return hierarchy.TryGetItemProperty(root, propertyId, out value); } public static bool TryGetProperty<T>(this IVsHierarchy hierarchy, __VSHPROPID propertyId, [MaybeNullWhen(false)] out T value) => hierarchy.TryGetProperty((int)propertyId, out value); public static bool TryGetItemProperty<T>(this IVsHierarchy hierarchy, uint itemId, __VSHPROPID propertyId, [MaybeNullWhen(false)] out T value) => hierarchy.TryGetItemProperty(itemId, (int)propertyId, out value); public static bool TryGetGuidProperty(this IVsHierarchy hierarchy, int propertyId, out Guid guid) => ErrorHandler.Succeeded(hierarchy.GetGuidProperty(VSConstants.VSITEMID_ROOT, propertyId, out guid)); public static bool TryGetGuidProperty(this IVsHierarchy hierarchy, __VSHPROPID propertyId, out Guid guid) => ErrorHandler.Succeeded(hierarchy.GetGuidProperty(VSConstants.VSITEMID_ROOT, (int)propertyId, out guid)); public static bool TryGetProject(this IVsHierarchy hierarchy, [NotNullWhen(returnValue: true)] out EnvDTE.Project? project) => hierarchy.TryGetProperty<EnvDTE.Project>(__VSHPROPID.VSHPROPID_ExtObject, out project); public static bool TryGetName(this IVsHierarchy hierarchy, [NotNullWhen(returnValue: true)] out string? name) => hierarchy.TryGetProperty<string>(__VSHPROPID.VSHPROPID_Name, out name); public static bool TryGetItemName(this IVsHierarchy hierarchy, uint itemId, [NotNullWhen(returnValue: true)] out string? name) => hierarchy.TryGetItemProperty<string>(itemId, __VSHPROPID.VSHPROPID_Name, out name); public static bool TryGetCanonicalName(this IVsHierarchy hierarchy, uint itemId, [NotNullWhen(returnValue: true)] out string? name) => ErrorHandler.Succeeded(hierarchy.GetCanonicalName(itemId, out name)); public static bool TryGetParentHierarchy(this IVsHierarchy hierarchy, [NotNullWhen(returnValue: true)] out IVsHierarchy? parentHierarchy) => hierarchy.TryGetProperty<IVsHierarchy>(__VSHPROPID.VSHPROPID_ParentHierarchy, out parentHierarchy); public static bool TryGetTypeGuid(this IVsHierarchy hierarchy, out Guid typeGuid) => hierarchy.TryGetGuidProperty(__VSHPROPID.VSHPROPID_TypeGuid, out typeGuid); public static bool TryGetTargetFrameworkMoniker(this IVsHierarchy hierarchy, uint itemId, [NotNullWhen(returnValue: true)] out string? targetFrameworkMoniker) => hierarchy.TryGetItemProperty<string>(itemId, (int)__VSHPROPID4.VSHPROPID_TargetFrameworkMoniker, out targetFrameworkMoniker); public static uint TryGetItemId(this IVsHierarchy hierarchy, string moniker) { if (ErrorHandler.Succeeded(hierarchy.ParseCanonicalName(moniker, out var itemid))) { return itemid; } return VSConstants.VSITEMID_NIL; } public static string? TryGetProjectFilePath(this IVsHierarchy hierarchy) { if (ErrorHandler.Succeeded(((IVsProject3)hierarchy).GetMkDocument((uint)VSConstants.VSITEMID.Root, out var projectFilePath)) && !string.IsNullOrEmpty(projectFilePath)) { return projectFilePath; } return null; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Def/EditorConfigSettings/CodeStyle/View/ColumnDefinitions/CodeStyleCategoryColumnDefinition.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.ComponentModel.Composition; using System.Windows; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Utilities; using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.CodeStyle; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View.ColumnDefinitions { [Export(typeof(IDefaultColumnGroup))] [Name(nameof(CodeStyleCategoryGroupingSet))] // Required, name of the default group [GroupColumns(Category)] // Required, the names of the columns in the grouping internal class CodeStyleCategoryGroupingSet : IDefaultColumnGroup { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CodeStyleCategoryGroupingSet() { } } [Export(typeof(ITableColumnDefinition))] [Name(Category)] internal class CodeStyleCategoryColumnDefinition : TableColumnDefinitionBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CodeStyleCategoryColumnDefinition() { } public override string Name => Category; public override string DisplayName => ServicesVSResources.Category; public override double MinWidth => 80; public override bool DefaultVisible => false; public override bool IsFilterable => true; public override bool IsSortable => true; public override TextWrapping TextWrapping => TextWrapping.NoWrap; private static string? GetCategoryName(ITableEntryHandle entry) => entry.TryGetValue(Category, out var categoryName) ? categoryName as string : null; public override IEntryBucket? CreateBucketForEntry(ITableEntryHandle entry) { var categoryName = GetCategoryName(entry); return categoryName is not null ? new StringEntryBucket(categoryName) : 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; using System.ComponentModel.Composition; using System.Windows; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Utilities; using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.CodeStyle; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View.ColumnDefinitions { [Export(typeof(IDefaultColumnGroup))] [Name(nameof(CodeStyleCategoryGroupingSet))] // Required, name of the default group [GroupColumns(Category)] // Required, the names of the columns in the grouping internal class CodeStyleCategoryGroupingSet : IDefaultColumnGroup { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CodeStyleCategoryGroupingSet() { } } [Export(typeof(ITableColumnDefinition))] [Name(Category)] internal class CodeStyleCategoryColumnDefinition : TableColumnDefinitionBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CodeStyleCategoryColumnDefinition() { } public override string Name => Category; public override string DisplayName => ServicesVSResources.Category; public override double MinWidth => 80; public override bool DefaultVisible => false; public override bool IsFilterable => true; public override bool IsSortable => true; public override TextWrapping TextWrapping => TextWrapping.NoWrap; private static string? GetCategoryName(ITableEntryHandle entry) => entry.TryGetValue(Category, out var categoryName) ? categoryName as string : null; public override IEntryBucket? CreateBucketForEntry(ITableEntryHandle entry) { var categoryName = GetCategoryName(entry); return categoryName is not null ? new StringEntryBucket(categoryName) : null; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/LanguageServer/ProtocolUnitTests/Definitions/GoToDefinitionTests.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.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Definitions { public class GoToDefinitionTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGotoDefinitionAsync() { var markup = @"class A { string {|definition:aString|} = 'hello'; void M() { var len = {|caret:|}aString.Length; } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoDefinitionAsync_DifferentDocument() { var markups = new string[] { @"namespace One { class A { public static int {|definition:aInt|} = 1; } }", @"namespace One { class B { int bInt = One.A.{|caret:|}aInt; } }" }; using var testLspServer = CreateTestLspServer(markups, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoDefinitionAsync_MappedFile() { var markup = @"class A { string aString = 'hello'; void M() { var len = aString.Length; } }"; using var testLspServer = CreateTestLspServer(string.Empty, out var _); AddMappedDocument(testLspServer.TestWorkspace, markup); var position = new LSP.Position { Line = 5, Character = 18 }; var results = await RunGotoDefinitionAsync(testLspServer, new LSP.Location { Uri = new Uri($"C:\\{TestSpanMapper.GeneratedFileName}"), Range = new LSP.Range { Start = position, End = position } }); AssertLocationsEqual(ImmutableArray.Create(TestSpanMapper.MappedFileLocation), results); } [Fact] public async Task TestGotoDefinitionAsync_InvalidLocation() { var markup = @"class A { void M() {{|caret:|} var len = aString.Length; } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } [Fact, WorkItem(1264627, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1264627")] public async Task TestGotoDefinitionAsync_NoResultsOnNamespace() { var markup = @"namespace {|caret:M|} { class A { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } private static async Task<LSP.Location[]> RunGotoDefinitionAsync(TestLspServer testLspServer, LSP.Location caret) { return await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.Location[]>(LSP.Methods.TextDocumentDefinitionName, CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), null, CancellationToken.None); } } }
// Licensed to the .NET Foundation under one or more 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.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Definitions { public class GoToDefinitionTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGotoDefinitionAsync() { var markup = @"class A { string {|definition:aString|} = 'hello'; void M() { var len = {|caret:|}aString.Length; } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoDefinitionAsync_DifferentDocument() { var markups = new string[] { @"namespace One { class A { public static int {|definition:aInt|} = 1; } }", @"namespace One { class B { int bInt = One.A.{|caret:|}aInt; } }" }; using var testLspServer = CreateTestLspServer(markups, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoDefinitionAsync_MappedFile() { var markup = @"class A { string aString = 'hello'; void M() { var len = aString.Length; } }"; using var testLspServer = CreateTestLspServer(string.Empty, out var _); AddMappedDocument(testLspServer.TestWorkspace, markup); var position = new LSP.Position { Line = 5, Character = 18 }; var results = await RunGotoDefinitionAsync(testLspServer, new LSP.Location { Uri = new Uri($"C:\\{TestSpanMapper.GeneratedFileName}"), Range = new LSP.Range { Start = position, End = position } }); AssertLocationsEqual(ImmutableArray.Create(TestSpanMapper.MappedFileLocation), results); } [Fact] public async Task TestGotoDefinitionAsync_InvalidLocation() { var markup = @"class A { void M() {{|caret:|} var len = aString.Length; } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } [Fact, WorkItem(1264627, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1264627")] public async Task TestGotoDefinitionAsync_NoResultsOnNamespace() { var markup = @"namespace {|caret:M|} { class A { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } private static async Task<LSP.Location[]> RunGotoDefinitionAsync(TestLspServer testLspServer, LSP.Location caret) { return await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.Location[]>(LSP.Methods.TextDocumentDefinitionName, CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), null, CancellationToken.None); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./eng/common/templates/job/job.yml
# Internal resources (telemetry, microbuild) can only be accessed from non-public projects, # and some (Microbuild) should only be applied to non-PR cases for internal builds. parameters: # Job schema parameters - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job cancelTimeoutInMinutes: '' condition: '' container: '' continueOnError: false dependsOn: '' displayName: '' pool: '' steps: [] strategy: '' timeoutInMinutes: '' variables: [] workspace: '' # Job base template specific parameters # See schema documentation - https://github.com/dotnet/arcade/blob/master/Documentation/AzureDevOps/TemplateSchema.md artifacts: '' enableMicrobuild: false enablePublishBuildArtifacts: false enablePublishBuildAssets: false enablePublishTestResults: false enablePublishUsingPipelines: false mergeTestResults: false testRunTitle: '' testResultsFormat: '' name: '' preSteps: [] runAsPublic: false jobs: - job: ${{ parameters.name }} ${{ if ne(parameters.cancelTimeoutInMinutes, '') }}: cancelTimeoutInMinutes: ${{ parameters.cancelTimeoutInMinutes }} ${{ if ne(parameters.condition, '') }}: condition: ${{ parameters.condition }} ${{ if ne(parameters.container, '') }}: container: ${{ parameters.container }} ${{ if ne(parameters.continueOnError, '') }}: continueOnError: ${{ parameters.continueOnError }} ${{ if ne(parameters.dependsOn, '') }}: dependsOn: ${{ parameters.dependsOn }} ${{ if ne(parameters.displayName, '') }}: displayName: ${{ parameters.displayName }} ${{ if ne(parameters.pool, '') }}: pool: ${{ parameters.pool }} ${{ if ne(parameters.strategy, '') }}: strategy: ${{ parameters.strategy }} ${{ if ne(parameters.timeoutInMinutes, '') }}: timeoutInMinutes: ${{ parameters.timeoutInMinutes }} variables: - ${{ if ne(parameters.enableTelemetry, 'false') }}: - name: DOTNET_CLI_TELEMETRY_PROFILE value: '$(Build.Repository.Uri)' - ${{ if eq(parameters.enableRichCodeNavigation, 'true') }}: - name: EnableRichCodeNavigation value: 'true' - ${{ each variable in parameters.variables }}: # handle name-value variable syntax # example: # - name: [key] # value: [value] - ${{ if ne(variable.name, '') }}: - name: ${{ variable.name }} value: ${{ variable.value }} # handle variable groups - ${{ if ne(variable.group, '') }}: - group: ${{ variable.group }} # handle key-value variable syntax. # example: # - [key]: [value] - ${{ if and(eq(variable.name, ''), eq(variable.group, '')) }}: - ${{ each pair in variable }}: - name: ${{ pair.key }} value: ${{ pair.value }} # DotNet-HelixApi-Access provides 'HelixApiAccessToken' for internal builds - ${{ if and(eq(parameters.enableTelemetry, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - group: DotNet-HelixApi-Access ${{ if ne(parameters.workspace, '') }}: workspace: ${{ parameters.workspace }} steps: - ${{ if ne(parameters.preSteps, '') }}: - ${{ each preStep in parameters.preSteps }}: - ${{ preStep }} - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - task: MicroBuildSigningPlugin@2 displayName: Install MicroBuild plugin inputs: signType: $(_SignType) zipSources: false feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json env: TeamName: $(_TeamName) continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) - task: NuGetAuthenticate@0 - ${{ if or(eq(parameters.artifacts.download, 'true'), ne(parameters.artifacts.download, '')) }}: - task: DownloadPipelineArtifact@2 inputs: buildType: current artifactName: ${{ coalesce(parameters.artifacts.download.name, 'Artifacts_$(Agent.OS)_$(_BuildConfig)') }} targetPath: ${{ coalesce(parameters.artifacts.download.path, 'artifacts') }} itemPattern: ${{ coalesce(parameters.artifacts.download.pattern, '**') }} - ${{ each step in parameters.steps }}: - ${{ step }} - ${{ if eq(parameters.enableRichCodeNavigation, true) }}: - task: RichCodeNavIndexer@0 displayName: RichCodeNav Upload inputs: languages: ${{ coalesce(parameters.richCodeNavigationLanguage, 'csharp') }} environment: ${{ coalesce(parameters.richCodeNavigationEnvironment, 'production') }} richNavLogOutputDirectory: $(Build.SourcesDirectory)/artifacts/bin continueOnError: true - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: MicroBuildCleanup@1 displayName: Execute Microbuild cleanup tasks condition: and(always(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) continueOnError: ${{ parameters.continueOnError }} env: TeamName: $(_TeamName) - ${{ if ne(parameters.artifacts.publish, '') }}: - ${{ if or(eq(parameters.artifacts.publish.artifacts, 'true'), ne(parameters.artifacts.publish.artifacts, '')) }}: - task: CopyFiles@2 displayName: Gather binaries for publish to artifacts inputs: SourceFolder: 'artifacts/bin' Contents: '**' TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/bin' - task: CopyFiles@2 displayName: Gather packages for publish to artifacts inputs: SourceFolder: 'artifacts/packages' Contents: '**' TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/packages' - task: PublishBuildArtifacts@1 displayName: Publish pipeline artifacts inputs: PathtoPublish: '$(Build.ArtifactStagingDirectory)/artifacts' PublishLocation: Container ArtifactName: ${{ coalesce(parameters.artifacts.publish.artifacts.name , 'Artifacts_$(Agent.Os)_$(_BuildConfig)') }} continueOnError: true condition: always() - ${{ if or(eq(parameters.artifacts.publish.logs, 'true'), ne(parameters.artifacts.publish.logs, '')) }}: - publish: artifacts/log artifact: ${{ coalesce(parameters.artifacts.publish.logs.name, 'Logs_Build_$(Agent.Os)_$(_BuildConfig)') }} displayName: Publish logs continueOnError: true condition: always() - ${{ if or(eq(parameters.artifacts.publish.manifests, 'true'), ne(parameters.artifacts.publish.manifests, '')) }}: - ${{ if and(ne(parameters.enablePublishUsingPipelines, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: CopyFiles@2 displayName: Gather Asset Manifests inputs: SourceFolder: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/AssetManifest' TargetFolder: '$(Build.ArtifactStagingDirectory)/AssetManifests' continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) - task: PublishBuildArtifacts@1 displayName: Push Asset Manifests inputs: PathtoPublish: '$(Build.ArtifactStagingDirectory)/AssetManifests' PublishLocation: Container ArtifactName: AssetManifests continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) - ${{ if ne(parameters.enablePublishBuildArtifacts, 'false') }}: - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)' PublishLocation: Container ArtifactName: ${{ coalesce(parameters.enablePublishBuildArtifacts.artifactName, '$(Agent.Os)_$(Agent.JobName)' ) }} continueOnError: true condition: always() - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'xunit')) }}: - task: PublishTestResults@2 displayName: Publish XUnit Test Results inputs: testResultsFormat: 'xUnit' testResultsFiles: '*.xml' searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-xunit mergeTestResults: ${{ parameters.mergeTestResults }} continueOnError: true condition: always() - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'vstest')) }}: - task: PublishTestResults@2 displayName: Publish TRX Test Results inputs: testResultsFormat: 'VSTest' testResultsFiles: '*.trx' searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-trx mergeTestResults: ${{ parameters.mergeTestResults }} continueOnError: true condition: always() - ${{ if and(eq(parameters.enablePublishBuildAssets, true), ne(parameters.enablePublishUsingPipelines, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: CopyFiles@2 displayName: Gather Asset Manifests inputs: SourceFolder: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/AssetManifest' TargetFolder: '$(Build.StagingDirectory)/AssetManifests' continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) - task: PublishBuildArtifacts@1 displayName: Push Asset Manifests inputs: PathtoPublish: '$(Build.StagingDirectory)/AssetManifests' PublishLocation: Container ArtifactName: AssetManifests continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true'))
# Internal resources (telemetry, microbuild) can only be accessed from non-public projects, # and some (Microbuild) should only be applied to non-PR cases for internal builds. parameters: # Job schema parameters - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job cancelTimeoutInMinutes: '' condition: '' container: '' continueOnError: false dependsOn: '' displayName: '' pool: '' steps: [] strategy: '' timeoutInMinutes: '' variables: [] workspace: '' # Job base template specific parameters # See schema documentation - https://github.com/dotnet/arcade/blob/master/Documentation/AzureDevOps/TemplateSchema.md artifacts: '' enableMicrobuild: false enablePublishBuildArtifacts: false enablePublishBuildAssets: false enablePublishTestResults: false enablePublishUsingPipelines: false mergeTestResults: false testRunTitle: '' testResultsFormat: '' name: '' preSteps: [] runAsPublic: false jobs: - job: ${{ parameters.name }} ${{ if ne(parameters.cancelTimeoutInMinutes, '') }}: cancelTimeoutInMinutes: ${{ parameters.cancelTimeoutInMinutes }} ${{ if ne(parameters.condition, '') }}: condition: ${{ parameters.condition }} ${{ if ne(parameters.container, '') }}: container: ${{ parameters.container }} ${{ if ne(parameters.continueOnError, '') }}: continueOnError: ${{ parameters.continueOnError }} ${{ if ne(parameters.dependsOn, '') }}: dependsOn: ${{ parameters.dependsOn }} ${{ if ne(parameters.displayName, '') }}: displayName: ${{ parameters.displayName }} ${{ if ne(parameters.pool, '') }}: pool: ${{ parameters.pool }} ${{ if ne(parameters.strategy, '') }}: strategy: ${{ parameters.strategy }} ${{ if ne(parameters.timeoutInMinutes, '') }}: timeoutInMinutes: ${{ parameters.timeoutInMinutes }} variables: - ${{ if ne(parameters.enableTelemetry, 'false') }}: - name: DOTNET_CLI_TELEMETRY_PROFILE value: '$(Build.Repository.Uri)' - ${{ if eq(parameters.enableRichCodeNavigation, 'true') }}: - name: EnableRichCodeNavigation value: 'true' - ${{ each variable in parameters.variables }}: # handle name-value variable syntax # example: # - name: [key] # value: [value] - ${{ if ne(variable.name, '') }}: - name: ${{ variable.name }} value: ${{ variable.value }} # handle variable groups - ${{ if ne(variable.group, '') }}: - group: ${{ variable.group }} # handle key-value variable syntax. # example: # - [key]: [value] - ${{ if and(eq(variable.name, ''), eq(variable.group, '')) }}: - ${{ each pair in variable }}: - name: ${{ pair.key }} value: ${{ pair.value }} # DotNet-HelixApi-Access provides 'HelixApiAccessToken' for internal builds - ${{ if and(eq(parameters.enableTelemetry, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - group: DotNet-HelixApi-Access ${{ if ne(parameters.workspace, '') }}: workspace: ${{ parameters.workspace }} steps: - ${{ if ne(parameters.preSteps, '') }}: - ${{ each preStep in parameters.preSteps }}: - ${{ preStep }} - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - task: MicroBuildSigningPlugin@2 displayName: Install MicroBuild plugin inputs: signType: $(_SignType) zipSources: false feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json env: TeamName: $(_TeamName) continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) - task: NuGetAuthenticate@0 - ${{ if or(eq(parameters.artifacts.download, 'true'), ne(parameters.artifacts.download, '')) }}: - task: DownloadPipelineArtifact@2 inputs: buildType: current artifactName: ${{ coalesce(parameters.artifacts.download.name, 'Artifacts_$(Agent.OS)_$(_BuildConfig)') }} targetPath: ${{ coalesce(parameters.artifacts.download.path, 'artifacts') }} itemPattern: ${{ coalesce(parameters.artifacts.download.pattern, '**') }} - ${{ each step in parameters.steps }}: - ${{ step }} - ${{ if eq(parameters.enableRichCodeNavigation, true) }}: - task: RichCodeNavIndexer@0 displayName: RichCodeNav Upload inputs: languages: ${{ coalesce(parameters.richCodeNavigationLanguage, 'csharp') }} environment: ${{ coalesce(parameters.richCodeNavigationEnvironment, 'production') }} richNavLogOutputDirectory: $(Build.SourcesDirectory)/artifacts/bin continueOnError: true - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: MicroBuildCleanup@1 displayName: Execute Microbuild cleanup tasks condition: and(always(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) continueOnError: ${{ parameters.continueOnError }} env: TeamName: $(_TeamName) - ${{ if ne(parameters.artifacts.publish, '') }}: - ${{ if or(eq(parameters.artifacts.publish.artifacts, 'true'), ne(parameters.artifacts.publish.artifacts, '')) }}: - task: CopyFiles@2 displayName: Gather binaries for publish to artifacts inputs: SourceFolder: 'artifacts/bin' Contents: '**' TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/bin' - task: CopyFiles@2 displayName: Gather packages for publish to artifacts inputs: SourceFolder: 'artifacts/packages' Contents: '**' TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/packages' - task: PublishBuildArtifacts@1 displayName: Publish pipeline artifacts inputs: PathtoPublish: '$(Build.ArtifactStagingDirectory)/artifacts' PublishLocation: Container ArtifactName: ${{ coalesce(parameters.artifacts.publish.artifacts.name , 'Artifacts_$(Agent.Os)_$(_BuildConfig)') }} continueOnError: true condition: always() - ${{ if or(eq(parameters.artifacts.publish.logs, 'true'), ne(parameters.artifacts.publish.logs, '')) }}: - publish: artifacts/log artifact: ${{ coalesce(parameters.artifacts.publish.logs.name, 'Logs_Build_$(Agent.Os)_$(_BuildConfig)') }} displayName: Publish logs continueOnError: true condition: always() - ${{ if or(eq(parameters.artifacts.publish.manifests, 'true'), ne(parameters.artifacts.publish.manifests, '')) }}: - ${{ if and(ne(parameters.enablePublishUsingPipelines, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: CopyFiles@2 displayName: Gather Asset Manifests inputs: SourceFolder: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/AssetManifest' TargetFolder: '$(Build.ArtifactStagingDirectory)/AssetManifests' continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) - task: PublishBuildArtifacts@1 displayName: Push Asset Manifests inputs: PathtoPublish: '$(Build.ArtifactStagingDirectory)/AssetManifests' PublishLocation: Container ArtifactName: AssetManifests continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) - ${{ if ne(parameters.enablePublishBuildArtifacts, 'false') }}: - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)' PublishLocation: Container ArtifactName: ${{ coalesce(parameters.enablePublishBuildArtifacts.artifactName, '$(Agent.Os)_$(Agent.JobName)' ) }} continueOnError: true condition: always() - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'xunit')) }}: - task: PublishTestResults@2 displayName: Publish XUnit Test Results inputs: testResultsFormat: 'xUnit' testResultsFiles: '*.xml' searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-xunit mergeTestResults: ${{ parameters.mergeTestResults }} continueOnError: true condition: always() - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'vstest')) }}: - task: PublishTestResults@2 displayName: Publish TRX Test Results inputs: testResultsFormat: 'VSTest' testResultsFiles: '*.trx' searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-trx mergeTestResults: ${{ parameters.mergeTestResults }} continueOnError: true condition: always() - ${{ if and(eq(parameters.enablePublishBuildAssets, true), ne(parameters.enablePublishUsingPipelines, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: CopyFiles@2 displayName: Gather Asset Manifests inputs: SourceFolder: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/AssetManifest' TargetFolder: '$(Build.StagingDirectory)/AssetManifests' continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) - task: PublishBuildArtifacts@1 displayName: Push Asset Manifests inputs: PathtoPublish: '$(Build.StagingDirectory)/AssetManifests' PublishLocation: Container ArtifactName: AssetManifests continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true'))
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Scripting/Core/ScriptVariable.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.Diagnostics; using System.Reflection; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// A variable declared by the script. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public sealed class ScriptVariable { private readonly object _instance; private readonly FieldInfo _field; internal ScriptVariable(object instance, FieldInfo field) { Debug.Assert(instance != null); Debug.Assert(field != null); _instance = instance; _field = field; } /// <summary> /// The name of the variable. /// </summary> public string Name => _field.Name; /// <summary> /// The type of the variable. /// </summary> public Type Type => _field.FieldType; /// <summary> /// True if the variable can't be written to (it's declared as readonly or a constant). /// </summary> public bool IsReadOnly => _field.IsInitOnly || _field.IsLiteral; /// <summary> /// The value of the variable after running the script. /// </summary> /// <exception cref="InvalidOperationException">Variable is read-only or a constant.</exception> /// <exception cref="ArgumentException">The type of the specified <paramref name="value"/> isn't assignable to the type of the variable.</exception> public object Value { get { return _field.GetValue(_instance); } set { if (_field.IsInitOnly) { throw new InvalidOperationException(ScriptingResources.CannotSetReadOnlyVariable); } if (_field.IsLiteral) { throw new InvalidOperationException(ScriptingResources.CannotSetConstantVariable); } _field.SetValue(_instance, value); } } private string GetDebuggerDisplay() => $"{Name}: {Value ?? "<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. #nullable disable using System; using System.Diagnostics; using System.Reflection; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// A variable declared by the script. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public sealed class ScriptVariable { private readonly object _instance; private readonly FieldInfo _field; internal ScriptVariable(object instance, FieldInfo field) { Debug.Assert(instance != null); Debug.Assert(field != null); _instance = instance; _field = field; } /// <summary> /// The name of the variable. /// </summary> public string Name => _field.Name; /// <summary> /// The type of the variable. /// </summary> public Type Type => _field.FieldType; /// <summary> /// True if the variable can't be written to (it's declared as readonly or a constant). /// </summary> public bool IsReadOnly => _field.IsInitOnly || _field.IsLiteral; /// <summary> /// The value of the variable after running the script. /// </summary> /// <exception cref="InvalidOperationException">Variable is read-only or a constant.</exception> /// <exception cref="ArgumentException">The type of the specified <paramref name="value"/> isn't assignable to the type of the variable.</exception> public object Value { get { return _field.GetValue(_instance); } set { if (_field.IsInitOnly) { throw new InvalidOperationException(ScriptingResources.CannotSetReadOnlyVariable); } if (_field.IsLiteral) { throw new InvalidOperationException(ScriptingResources.CannotSetConstantVariable); } _field.SetValue(_instance, value); } } private string GetDebuggerDisplay() => $"{Name}: {Value ?? "<null>"}"; } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Test/Syntax/Parsing/SeparatedSyntaxListParsingTests.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.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SeparatedSyntaxListParsingTests : ParsingTests { public SeparatedSyntaxListParsingTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options); } [Fact] public void TypeArguments() { UsingTree(@" class C { A<> a1; A<T> a2; A<,> a3; A<T U> a4; A<,,> a5; A<T,> a6; A<,T> a7; A<T U,,> a8; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a2"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a3"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } M(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a4"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a5"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.CommaToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a6"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a7"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } M(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.CommaToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a8"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TypeArguments2() { var tree = UsingTree(@" class C { new C<>(); new C<, >(); C<C<>> a1; C<A<>> a1; object a1 = typeof(C<C<, >, int>); object a2 = Swap<>(1, 1); } class M<,> { } ", options: TestOptions.Regular); CheckTypeArguments2(); } void CheckTypeArguments2() { N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.NewKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CommaToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.NewKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CommaToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.TypeOfExpression); { N(SyntaxKind.TypeOfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a2"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Swap"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); M(SyntaxKind.TypeParameter); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); M(SyntaxKind.TypeParameter); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TypeArguments2WithCSharp6() { var tree = UsingTree(@" class C { new C<>(); new C<, >(); C<C<>> a1; C<A<>> a1; object a1 = typeof(C<C<, >, int>); object a2 = Swap<>(1, 1); } class M<,> { } ", TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); CheckTypeArguments2(); } [Fact] public void ArrayRankSpecifiers() { UsingTree(@" class C { object a1 = new int[]; object a1 = new int[1]; object a1 = new int[,]; object a1 = new int[1 2]; object a1 = new int[,,]; object a1 = new int[1,]; object a1 = new int[,1]; object a1 = new int[1 1 ,,]; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } M(SyntaxKind.CommaToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CommaToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } M(SyntaxKind.CommaToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CommaToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SeparatedSyntaxListParsingTests : ParsingTests { public SeparatedSyntaxListParsingTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options); } [Fact] public void TypeArguments() { UsingTree(@" class C { A<> a1; A<T> a2; A<,> a3; A<T U> a4; A<,,> a5; A<T,> a6; A<,T> a7; A<T U,,> a8; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a2"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a3"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } M(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a4"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a5"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.CommaToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a6"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a7"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } M(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.CommaToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a8"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TypeArguments2() { var tree = UsingTree(@" class C { new C<>(); new C<, >(); C<C<>> a1; C<A<>> a1; object a1 = typeof(C<C<, >, int>); object a2 = Swap<>(1, 1); } class M<,> { } ", options: TestOptions.Regular); CheckTypeArguments2(); } void CheckTypeArguments2() { N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.NewKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CommaToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.NewKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CommaToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.TypeOfExpression); { N(SyntaxKind.TypeOfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a2"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Swap"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.OmittedTypeArgument); { N(SyntaxKind.OmittedTypeArgumentToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); M(SyntaxKind.TypeParameter); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); M(SyntaxKind.TypeParameter); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TypeArguments2WithCSharp6() { var tree = UsingTree(@" class C { new C<>(); new C<, >(); C<C<>> a1; C<A<>> a1; object a1 = typeof(C<C<, >, int>); object a2 = Swap<>(1, 1); } class M<,> { } ", TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); CheckTypeArguments2(); } [Fact] public void ArrayRankSpecifiers() { UsingTree(@" class C { object a1 = new int[]; object a1 = new int[1]; object a1 = new int[,]; object a1 = new int[1 2]; object a1 = new int[,,]; object a1 = new int[1,]; object a1 = new int[,1]; object a1 = new int[1 1 ,,]; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } M(SyntaxKind.CommaToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CommaToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } M(SyntaxKind.CommaToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CommaToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseBracketToken); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/ExpressionEvaluator/Core/Source/ResultProvider/ResultProvider.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 #pragma warning disable CA1825 // Avoid zero-length array allocations. using System; using System.Collections.ObjectModel; using System.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Microsoft.VisualStudio.Debugger.Metadata; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal delegate void CompletionRoutine(); internal delegate void CompletionRoutine<TResult>(TResult result); /// <summary> /// Computes expansion of <see cref="DkmClrValue"/> instances. /// </summary> /// <remarks> /// This class provides implementation for the default ResultProvider component. /// </remarks> public abstract class ResultProvider : IDkmClrResultProvider { static ResultProvider() { FatalError.Handler = FailFast.OnFatalException; } // Fields should be removed and replaced with calls through DkmInspectionContext. // (see https://github.com/dotnet/roslyn/issues/6899). internal readonly IDkmClrFormatter2 Formatter2; internal readonly IDkmClrFullNameProvider FullNameProvider; internal ResultProvider(IDkmClrFormatter2 formatter2, IDkmClrFullNameProvider fullNameProvider) { Formatter2 = formatter2; FullNameProvider = fullNameProvider; } internal abstract string StaticMembersString { get; } internal abstract bool IsPrimitiveType(Type type); void IDkmClrResultProvider.GetResult(DkmClrValue value, DkmWorkList workList, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers, string resultName, string resultFullName, DkmCompletionRoutine<DkmEvaluationAsyncResult> completionRoutine) { if (formatSpecifiers == null) { formatSpecifiers = Formatter.NoFormatSpecifiers; } if (resultFullName != null) { ReadOnlyCollection<string> otherSpecifiers; resultFullName = FullNameProvider.GetClrExpressionAndFormatSpecifiers(inspectionContext, resultFullName, out otherSpecifiers); foreach (var formatSpecifier in otherSpecifiers) { formatSpecifiers = Formatter.AddFormatSpecifier(formatSpecifiers, formatSpecifier); } } var wl = new WorkList(workList, e => completionRoutine(DkmEvaluationAsyncResult.CreateErrorResult(e))); wl.ContinueWith( () => GetRootResultAndContinue( value, wl, declaredType, declaredTypeInfo, inspectionContext, resultName, resultFullName, formatSpecifiers, result => wl.ContinueWith(() => completionRoutine(new DkmEvaluationAsyncResult(result))))); } DkmClrValue IDkmClrResultProvider.GetClrValue(DkmSuccessEvaluationResult evaluationResult) { try { var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>(); if (dataItem == null) { // We don't know about this result. Call next implementation return evaluationResult.GetClrValue(); } return dataItem.Value; } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } internal const DkmEvaluationFlags NotRoot = (DkmEvaluationFlags)0x20000; internal const DkmEvaluationFlags NoResults = (DkmEvaluationFlags)0x40000; void IDkmClrResultProvider.GetChildren(DkmEvaluationResult evaluationResult, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine) { var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>(); if (dataItem == null) { // We don't know about this result. Call next implementation evaluationResult.GetChildren(workList, initialRequestSize, inspectionContext, completionRoutine); return; } var expansion = dataItem.Expansion; if (expansion == null) { var enumContext = DkmEvaluationResultEnumContext.Create(0, evaluationResult.StackFrame, inspectionContext, new EnumContextDataItem(evaluationResult)); completionRoutine(new DkmGetChildrenAsyncResult(new DkmEvaluationResult[0], enumContext)); return; } // Evaluate children with InspectionContext that is not the root. inspectionContext = inspectionContext.With(NotRoot); var rows = ArrayBuilder<EvalResult>.GetInstance(); int index = 0; expansion.GetRows(this, rows, inspectionContext, dataItem, dataItem.Value, 0, initialRequestSize, visitAll: true, index: ref index); var numRows = rows.Count; Debug.Assert(index >= numRows); Debug.Assert(initialRequestSize >= numRows); var initialChildren = new DkmEvaluationResult[numRows]; void onException(Exception e) => completionRoutine(DkmGetChildrenAsyncResult.CreateErrorResult(e)); var wl = new WorkList(workList, onException); wl.ContinueWith(() => GetEvaluationResultsAndContinue(evaluationResult, rows, initialChildren, 0, numRows, wl, inspectionContext, () => wl.ContinueWith( () => { var enumContext = DkmEvaluationResultEnumContext.Create(index, evaluationResult.StackFrame, inspectionContext, new EnumContextDataItem(evaluationResult)); completionRoutine(new DkmGetChildrenAsyncResult(initialChildren, enumContext)); rows.Free(); }), onException)); } void IDkmClrResultProvider.GetItems(DkmEvaluationResultEnumContext enumContext, DkmWorkList workList, int startIndex, int count, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine) { var enumContextDataItem = enumContext.GetDataItem<EnumContextDataItem>(); if (enumContextDataItem == null) { // We don't know about this result. Call next implementation enumContext.GetItems(workList, startIndex, count, completionRoutine); return; } var evaluationResult = enumContextDataItem.Result; var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>(); var expansion = dataItem.Expansion; if (expansion == null) { completionRoutine(new DkmEvaluationEnumAsyncResult(new DkmEvaluationResult[0])); return; } var inspectionContext = enumContext.InspectionContext; var rows = ArrayBuilder<EvalResult>.GetInstance(); int index = 0; expansion.GetRows(this, rows, inspectionContext, dataItem, dataItem.Value, startIndex, count, visitAll: false, index: ref index); var numRows = rows.Count; Debug.Assert(count >= numRows); var results = new DkmEvaluationResult[numRows]; void onException(Exception e) => completionRoutine(DkmEvaluationEnumAsyncResult.CreateErrorResult(e)); var wl = new WorkList(workList, onException); wl.ContinueWith(() => GetEvaluationResultsAndContinue(evaluationResult, rows, results, 0, numRows, wl, inspectionContext, () => wl.ContinueWith( () => { completionRoutine(new DkmEvaluationEnumAsyncResult(results)); rows.Free(); }), onException)); } string IDkmClrResultProvider.GetUnderlyingString(DkmEvaluationResult result) { try { var dataItem = result.GetDataItem<EvalResultDataItem>(); if (dataItem == null) { // We don't know about this result. Call next implementation return result.GetUnderlyingString(); } return dataItem.Value?.GetUnderlyingString(result.InspectionContext); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } private void GetChild( DkmEvaluationResult parent, WorkList workList, EvalResult row, DkmCompletionRoutine<DkmEvaluationAsyncResult> completionRoutine) { var inspectionContext = row.InspectionContext; if ((row.Kind != ExpansionKind.Default) || (row.Value == null)) { CreateEvaluationResultAndContinue( row, workList, row.InspectionContext, parent.StackFrame, child => completionRoutine(new DkmEvaluationAsyncResult(child))); } else { var typeDeclaringMember = row.TypeDeclaringMemberAndInfo; var name = (typeDeclaringMember.Type == null) ? row.Name : GetQualifiedMemberName(row.InspectionContext, typeDeclaringMember, row.Name, FullNameProvider); row.Value.SetDataItem(DkmDataCreationDisposition.CreateAlways, new FavoritesDataItem(row.CanFavorite, row.IsFavorite)); row.Value.GetResult( workList.InnerWorkList, row.DeclaredTypeAndInfo.ClrType, row.DeclaredTypeAndInfo.Info, row.InspectionContext, Formatter.NoFormatSpecifiers, name, row.FullName, result => workList.ContinueWith(() => completionRoutine(result))); } } private void CreateEvaluationResultAndContinue(EvalResult result, WorkList workList, DkmInspectionContext inspectionContext, DkmStackWalkFrame stackFrame, CompletionRoutine<DkmEvaluationResult> completionRoutine) { switch (result.Kind) { case ExpansionKind.Explicit: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, Name: result.DisplayName, FullName: result.FullName, Flags: result.Flags, Value: result.DisplayValue, EditableValue: result.EditableValue, Type: result.DisplayType, Category: DkmEvaluationResultCategory.Data, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.Error: completionRoutine(DkmFailedEvaluationResult.Create( inspectionContext, StackFrame: stackFrame, Name: result.Name, FullName: result.FullName, ErrorMessage: result.DisplayValue, Flags: DkmEvaluationResultFlags.None, Type: null, DataItem: null)); break; case ExpansionKind.NativeView: { var value = result.Value; var name = Resources.NativeView; var fullName = result.FullName; var display = result.Name; DkmEvaluationResult evalResult; if (value.IsError()) { evalResult = DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, Name: name, FullName: fullName, ErrorMessage: display, Flags: result.Flags, Type: null, DataItem: result.ToDataItem()); } else { // For Native View, create a DkmIntermediateEvaluationResult. // This will allow the C++ EE to take over expansion. var process = inspectionContext.RuntimeInstance.Process; var cpp = process.EngineSettings.GetLanguage(new DkmCompilerId(DkmVendorId.Microsoft, DkmLanguageId.Cpp)); evalResult = DkmIntermediateEvaluationResult.Create( inspectionContext, stackFrame, Name: name, FullName: fullName, Expression: display, IntermediateLanguage: cpp, TargetRuntime: process.GetNativeRuntimeInstance(), DataItem: result.ToDataItem()); } completionRoutine(evalResult); } break; case ExpansionKind.NonPublicMembers: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, Name: Resources.NonPublicMembers, FullName: result.FullName, Flags: result.Flags, Value: null, EditableValue: null, Type: string.Empty, Category: DkmEvaluationResultCategory.Data, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.StaticMembers: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, Name: StaticMembersString, FullName: result.FullName, Flags: result.Flags, Value: null, EditableValue: null, Type: string.Empty, Category: DkmEvaluationResultCategory.Class, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.RawView: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, Name: Resources.RawView, FullName: result.FullName, Flags: result.Flags, Value: null, EditableValue: result.EditableValue, Type: string.Empty, Category: DkmEvaluationResultCategory.Data, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.DynamicView: case ExpansionKind.ResultsView: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, result.Name, result.FullName, result.Flags, result.DisplayValue, EditableValue: null, Type: string.Empty, Category: DkmEvaluationResultCategory.Method, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.TypeVariable: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, result.Name, result.FullName, result.Flags, result.DisplayValue, EditableValue: null, Type: result.DisplayValue, Category: DkmEvaluationResultCategory.Data, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.PointerDereference: case ExpansionKind.Default: // This call will evaluate DebuggerDisplayAttributes. GetResultAndContinue( result, workList, declaredType: result.DeclaredTypeAndInfo.ClrType, declaredTypeInfo: result.DeclaredTypeAndInfo.Info, inspectionContext: inspectionContext, useDebuggerDisplay: result.UseDebuggerDisplay, completionRoutine: completionRoutine); break; default: throw ExceptionUtilities.UnexpectedValue(result.Kind); } } private static DkmEvaluationResult CreateEvaluationResult( DkmInspectionContext inspectionContext, DkmClrValue value, string name, string typeName, string display, EvalResult result) { if (value.IsError()) { // Evaluation failed return DkmFailedEvaluationResult.Create( InspectionContext: inspectionContext, StackFrame: value.StackFrame, Name: name, FullName: result.FullName, ErrorMessage: display, Flags: result.Flags, Type: typeName, DataItem: result.ToDataItem()); } else { ReadOnlyCollection<DkmCustomUIVisualizerInfo> customUIVisualizers = null; if (!value.IsNull) { DkmCustomUIVisualizerInfo[] customUIVisualizerInfo = value.Type.GetDebuggerCustomUIVisualizerInfo(); if (customUIVisualizerInfo != null) { customUIVisualizers = new ReadOnlyCollection<DkmCustomUIVisualizerInfo>(customUIVisualizerInfo); } } // If the EvalResultDataItem doesn't specify a particular category, we'll just propagate DkmClrValue.Category, // which typically appears to be set to the default value ("Other"). var category = (result.Category != DkmEvaluationResultCategory.Other) ? result.Category : value.Category; var nullableMemberInfo = value.GetDataItem<NullableMemberInfo>(); // Valid value return DkmSuccessEvaluationResult.Create( InspectionContext: inspectionContext, StackFrame: value.StackFrame, Name: name, FullName: result.FullName, Flags: result.Flags, Value: display, EditableValue: result.EditableValue, Type: typeName, Category: nullableMemberInfo?.Category ?? category, Access: nullableMemberInfo?.Access ?? value.Access, StorageType: nullableMemberInfo?.StorageType ?? value.StorageType, TypeModifierFlags: nullableMemberInfo?.TypeModifierFlags ?? value.TypeModifierFlags, Address: value.Address, CustomUIVisualizers: customUIVisualizers, ExternalModules: null, DataItem: result.ToDataItem()); } } /// <returns> /// The qualified name (i.e. including containing types and namespaces) of a named, pointer, /// or array type followed by the qualified name of the actual runtime type, if provided. /// </returns> internal static string GetTypeName( DkmInspectionContext inspectionContext, DkmClrValue value, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, bool isPointerDereference) { var declaredLmrType = declaredType.GetLmrType(); var runtimeType = value.Type; var declaredTypeName = inspectionContext.GetTypeName(declaredType, declaredTypeInfo, Formatter.NoFormatSpecifiers); // Include the runtime type if distinct. if (!declaredLmrType.IsPointer && !isPointerDereference && (!declaredLmrType.IsNullable() || value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown))) { // Generate the declared type name without tuple element names. var declaredTypeInfoNoTupleElementNames = declaredTypeInfo.WithNoTupleElementNames(); var declaredTypeNameNoTupleElementNames = (declaredTypeInfo == declaredTypeInfoNoTupleElementNames) ? declaredTypeName : inspectionContext.GetTypeName(declaredType, declaredTypeInfoNoTupleElementNames, Formatter.NoFormatSpecifiers); // Generate the runtime type name with no tuple element names and no dynamic. var runtimeTypeName = inspectionContext.GetTypeName(runtimeType, null, FormatSpecifiers: Formatter.NoFormatSpecifiers); // If the two names are distinct, include both. if (!string.Equals(declaredTypeNameNoTupleElementNames, runtimeTypeName, StringComparison.Ordinal)) // Names will reflect "dynamic", types will not. { return string.Format("{0} {{{1}}}", declaredTypeName, runtimeTypeName); } } return declaredTypeName; } internal EvalResult CreateDataItem( DkmInspectionContext inspectionContext, string name, TypeAndCustomInfo typeDeclaringMemberAndInfo, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value, bool useDebuggerDisplay, ExpansionFlags expansionFlags, bool childShouldParenthesize, string fullName, ReadOnlyCollection<string> formatSpecifiers, DkmEvaluationResultCategory category, DkmEvaluationResultFlags flags, DkmEvaluationFlags evalFlags, bool canFavorite, bool isFavorite, bool supportsFavorites) { if ((evalFlags & DkmEvaluationFlags.ShowValueRaw) != 0) { formatSpecifiers = Formatter.AddFormatSpecifier(formatSpecifiers, "raw"); } Expansion expansion; // If the declared type is Nullable<T>, the value should // have no expansion if null, or be expanded as a T. var declaredType = declaredTypeAndInfo.Type; var lmrNullableTypeArg = declaredType.GetNullableTypeArgument(); if (lmrNullableTypeArg != null && !value.HasExceptionThrown()) { Debug.Assert(value.Type.GetProxyType() == null); DkmClrValue nullableValue; if (value.IsError()) { expansion = null; } else if ((nullableValue = value.GetNullableValue(lmrNullableTypeArg, inspectionContext)) == null) { Debug.Assert(declaredType.Equals(value.Type.GetLmrType())); // No expansion of "null". expansion = null; } else { // nullableValue is taken from an internal field. // It may have different category, access, etc comparing the original member. // For example, the orignal member can be a property not a field. // Save original member values to restore them later. if (value != nullableValue) { var nullableMemberInfo = new NullableMemberInfo(value.Category, value.Access, value.StorageType, value.TypeModifierFlags); nullableValue.SetDataItem(DkmDataCreationDisposition.CreateAlways, nullableMemberInfo); } value = nullableValue; Debug.Assert(lmrNullableTypeArg.Equals(value.Type.GetLmrType())); // If this is not the case, add a test for includeRuntimeTypeIfNecessary. // CONSIDER: The DynamicAttribute for the type argument should just be Skip(1) of the original flag array. expansion = this.GetTypeExpansion(inspectionContext, new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, lmrNullableTypeArg)), value, ExpansionFlags.IncludeResultsView, supportsFavorites: supportsFavorites); } } else if (value.IsError() || (inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) != 0) { expansion = null; } else { expansion = DebuggerTypeProxyExpansion.CreateExpansion( this, inspectionContext, name, typeDeclaringMemberAndInfo, declaredTypeAndInfo, value, childShouldParenthesize, fullName, flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName, formatSpecifiers, flags, Formatter2.GetEditableValueString(value, inspectionContext, declaredTypeAndInfo.Info)); if (expansion == null) { expansion = value.HasExceptionThrown() ? this.GetTypeExpansion(inspectionContext, new TypeAndCustomInfo(value.Type), value, expansionFlags, supportsFavorites: false) : this.GetTypeExpansion(inspectionContext, declaredTypeAndInfo, value, expansionFlags, supportsFavorites: supportsFavorites); } } return new EvalResult( ExpansionKind.Default, name, typeDeclaringMemberAndInfo, declaredTypeAndInfo, useDebuggerDisplay: useDebuggerDisplay, value: value, displayValue: null, expansion: expansion, childShouldParenthesize: childShouldParenthesize, fullName: fullName, childFullNamePrefixOpt: flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName, formatSpecifiers: formatSpecifiers, category: category, flags: flags, editableValue: Formatter2.GetEditableValueString(value, inspectionContext, declaredTypeAndInfo.Info), inspectionContext: inspectionContext, canFavorite: canFavorite, isFavorite: isFavorite); } private void GetRootResultAndContinue( DkmClrValue value, WorkList workList, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, DkmInspectionContext inspectionContext, string name, string fullName, ReadOnlyCollection<string> formatSpecifiers, CompletionRoutine<DkmEvaluationResult> completionRoutine) { Debug.Assert(formatSpecifiers != null); var type = value.Type.GetLmrType(); if (type.IsTypeVariables()) { Debug.Assert(type.Equals(declaredType.GetLmrType())); var declaredTypeAndInfo = new TypeAndCustomInfo(declaredType, declaredTypeInfo); var expansion = new TypeVariablesExpansion(declaredTypeAndInfo); var dataItem = new EvalResult( ExpansionKind.Default, name, typeDeclaringMemberAndInfo: default(TypeAndCustomInfo), declaredTypeAndInfo: declaredTypeAndInfo, useDebuggerDisplay: false, value: value, displayValue: null, expansion: expansion, childShouldParenthesize: false, fullName: null, childFullNamePrefixOpt: null, formatSpecifiers: Formatter.NoFormatSpecifiers, category: DkmEvaluationResultCategory.Data, flags: DkmEvaluationResultFlags.ReadOnly, editableValue: null, inspectionContext: inspectionContext); Debug.Assert(dataItem.Flags == (DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.Expandable)); // Note: We're not including value.EvalFlags in Flags parameter // below (there shouldn't be a reason to do so). completionRoutine(DkmSuccessEvaluationResult.Create( InspectionContext: inspectionContext, StackFrame: value.StackFrame, Name: Resources.TypeVariablesName, FullName: dataItem.FullName, Flags: dataItem.Flags, Value: "", EditableValue: null, Type: "", Category: dataItem.Category, Access: value.Access, StorageType: value.StorageType, TypeModifierFlags: value.TypeModifierFlags, Address: value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: dataItem.ToDataItem())); } else if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.ResultsOnly) != 0) { var dataItem = ResultsViewExpansion.CreateResultsOnlyRow( inspectionContext, name, fullName, formatSpecifiers, declaredType, declaredTypeInfo, value, this); CreateEvaluationResultAndContinue( dataItem, workList, inspectionContext, value.StackFrame, completionRoutine); } else if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.DynamicView) != 0) { var dataItem = DynamicViewExpansion.CreateMembersOnlyRow( inspectionContext, name, value, this); CreateEvaluationResultAndContinue( dataItem, workList, inspectionContext, value.StackFrame, completionRoutine); } else { var dataItem = ResultsViewExpansion.CreateResultsOnlyRowIfSynthesizedEnumerable( inspectionContext, name, fullName, formatSpecifiers, declaredType, declaredTypeInfo, value, this); if (dataItem != null) { CreateEvaluationResultAndContinue( dataItem, workList, inspectionContext, value.StackFrame, completionRoutine); } else { var useDebuggerDisplay = (inspectionContext.EvaluationFlags & NotRoot) != 0; var expansionFlags = (inspectionContext.EvaluationFlags & NoResults) != 0 ? ExpansionFlags.IncludeBaseMembers : ExpansionFlags.All; var favortiesDataItem = value.GetDataItem<FavoritesDataItem>(); dataItem = CreateDataItem( inspectionContext, name, typeDeclaringMemberAndInfo: default(TypeAndCustomInfo), declaredTypeAndInfo: new TypeAndCustomInfo(declaredType, declaredTypeInfo), value: value, useDebuggerDisplay: useDebuggerDisplay, expansionFlags: expansionFlags, childShouldParenthesize: (fullName == null) ? false : FullNameProvider.ClrExpressionMayRequireParentheses(inspectionContext, fullName), fullName: fullName, formatSpecifiers: formatSpecifiers, category: DkmEvaluationResultCategory.Other, flags: value.EvalFlags, evalFlags: inspectionContext.EvaluationFlags, canFavorite: favortiesDataItem?.CanFavorite ?? false, isFavorite: favortiesDataItem?.IsFavorite ?? false, supportsFavorites: true); GetResultAndContinue(dataItem, workList, declaredType, declaredTypeInfo, inspectionContext, useDebuggerDisplay, completionRoutine); } } } private void GetResultAndContinue( EvalResult result, WorkList workList, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, DkmInspectionContext inspectionContext, bool useDebuggerDisplay, CompletionRoutine<DkmEvaluationResult> completionRoutine) { var value = result.Value; // Value may have been replaced (specifically, for Nullable<T>). if (value.TryGetDebuggerDisplayInfo(out DebuggerDisplayInfo displayInfo)) { void onException(Exception e) => completionRoutine(CreateEvaluationResultFromException(e, result, inspectionContext)); if (displayInfo.Name != null) { // Favorites currently dependes on the name matching the member name result = result.WithDisableCanAddFavorite(); } var innerWorkList = workList.InnerWorkList; EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, displayInfo.Name, displayName => EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, displayInfo.GetValue(inspectionContext), displayValue => EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, displayInfo.TypeName, displayType => workList.ContinueWith(() => completionRoutine(GetResult(inspectionContext, result, declaredType, declaredTypeInfo, displayName.Result, displayValue.Result, displayType.Result, useDebuggerDisplay))), onException), onException), onException); } else { completionRoutine(GetResult(inspectionContext, result, declaredType, declaredTypeInfo, displayName: null, displayValue: null, displayType: null, useDebuggerDisplay: false)); } } private static void EvaluateDebuggerDisplayStringAndContinue( DkmClrValue value, DkmWorkList workList, DkmInspectionContext inspectionContext, DebuggerDisplayItemInfo displayInfo, CompletionRoutine<DkmEvaluateDebuggerDisplayStringAsyncResult> onCompleted, CompletionRoutine<Exception> onException) { void completionRoutine(DkmEvaluateDebuggerDisplayStringAsyncResult result) { try { onCompleted(result); } catch (Exception e) { onException(e); } } if (displayInfo == null) { completionRoutine(default(DkmEvaluateDebuggerDisplayStringAsyncResult)); } else { value.EvaluateDebuggerDisplayString(workList, inspectionContext, displayInfo.TargetType, displayInfo.Value, completionRoutine); } } private DkmEvaluationResult GetResult( DkmInspectionContext inspectionContext, EvalResult result, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, string displayName, string displayValue, string displayType, bool useDebuggerDisplay) { var name = result.Name; Debug.Assert(name != null); var typeDeclaringMemberAndInfo = result.TypeDeclaringMemberAndInfo; // Note: Don't respect the debugger display name on the root element: // 1) In the Watch window, that's where the user's text goes. // 2) In the Locals window, that's where the local name goes. // Note: Dev12 respects the debugger display name in the Locals window, // but not in the Watch window, but we can't distinguish and this // behavior seems reasonable. if (displayName != null && useDebuggerDisplay) { name = displayName; } else if (typeDeclaringMemberAndInfo.Type != null) { name = GetQualifiedMemberName(inspectionContext, typeDeclaringMemberAndInfo, name, FullNameProvider); } var value = result.Value; string display; if (value.HasExceptionThrown()) { display = result.DisplayValue ?? value.GetExceptionMessage(inspectionContext, result.FullNameWithoutFormatSpecifiers ?? result.Name); } else if (displayValue != null) { display = value.IncludeObjectId(displayValue); } else { display = value.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers); } var typeName = displayType ?? GetTypeName(inspectionContext, value, declaredType, declaredTypeInfo, result.Kind == ExpansionKind.PointerDereference); return CreateEvaluationResult(inspectionContext, value, name, typeName, display, result); } private void GetEvaluationResultsAndContinue( DkmEvaluationResult parent, ArrayBuilder<EvalResult> rows, DkmEvaluationResult[] results, int index, int numRows, WorkList workList, DkmInspectionContext inspectionContext, CompletionRoutine onCompleted, CompletionRoutine<Exception> onException) { void completionRoutine(DkmEvaluationAsyncResult result) { try { results[index] = result.Result; GetEvaluationResultsAndContinue(parent, rows, results, index + 1, numRows, workList, inspectionContext, onCompleted, onException); } catch (Exception e) { onException(e); } } if (index < numRows) { GetChild( parent, workList, rows[index], child => workList.ContinueWith(() => completionRoutine(child))); } else { onCompleted(); } } internal Expansion GetTypeExpansion( DkmInspectionContext inspectionContext, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value, ExpansionFlags flags, bool supportsFavorites) { var declaredType = declaredTypeAndInfo.Type; Debug.Assert(!declaredType.IsTypeVariables()); if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) != 0) { return null; } var runtimeType = value.Type.GetLmrType(); // If the value is an array, expand the array elements. if (runtimeType.IsArray) { var sizes = value.ArrayDimensions; if (sizes == null) { // Null array. No expansion. return null; } var lowerBounds = value.ArrayLowerBounds; Type elementType; DkmClrCustomTypeInfo elementTypeInfo; if (declaredType.IsArray) { elementType = declaredType.GetElementType(); elementTypeInfo = CustomTypeInfo.SkipOne(declaredTypeAndInfo.Info); } else { elementType = runtimeType.GetElementType(); elementTypeInfo = null; } return ArrayExpansion.CreateExpansion(new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, elementType), elementTypeInfo), sizes, lowerBounds); } if (this.IsPrimitiveType(runtimeType)) { return null; } if (declaredType.IsFunctionPointer()) { // Function pointers have no expansion return null; } if (declaredType.IsPointer) { // If this assert fails, the element type info is just .SkipOne(). Debug.Assert(declaredTypeAndInfo.Info?.PayloadTypeId != CustomTypeInfo.PayloadTypeId); var elementType = declaredType.GetElementType(); return value.IsNull || elementType.IsVoid() ? null : new PointerDereferenceExpansion(new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, elementType))); } if (value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown) && runtimeType.IsEmptyResultsViewException()) { // The value is an exception thrown expanding an empty // IEnumerable. Use the runtime type of the exception and // skip base types. (This matches the native EE behavior // to expose a single property from the exception.) flags &= ~ExpansionFlags.IncludeBaseMembers; } int cardinality; if (runtimeType.IsTupleCompatible(out cardinality)) { return TupleExpansion.CreateExpansion(inspectionContext, declaredTypeAndInfo, value, cardinality); } return MemberExpansion.CreateExpansion(inspectionContext, declaredTypeAndInfo, value, flags, TypeHelpers.IsVisibleMember, this, isProxyType: false, supportsFavorites); } private static DkmEvaluationResult CreateEvaluationResultFromException(Exception e, EvalResult result, DkmInspectionContext inspectionContext) { return DkmFailedEvaluationResult.Create( inspectionContext, result.Value.StackFrame, Name: result.Name, FullName: null, ErrorMessage: e.Message, Flags: DkmEvaluationResultFlags.None, Type: null, DataItem: null); } private static string GetQualifiedMemberName( DkmInspectionContext inspectionContext, TypeAndCustomInfo typeDeclaringMember, string memberName, IDkmClrFullNameProvider fullNameProvider) { var typeName = fullNameProvider.GetClrTypeName(inspectionContext, typeDeclaringMember.ClrType, typeDeclaringMember.Info) ?? inspectionContext.GetTypeName(typeDeclaringMember.ClrType, typeDeclaringMember.Info, Formatter.NoFormatSpecifiers); return typeDeclaringMember.Type.IsInterface ? $"{typeName}.{memberName}" : $"{memberName} ({typeName})"; } // Track remaining evaluations so that each subsequent evaluation // is executed at the entry point from the host rather than on the // callstack of the previous evaluation. private sealed class WorkList { private enum State { Initialized, Executing, Executed } internal readonly DkmWorkList InnerWorkList; private readonly CompletionRoutine<Exception> _onException; private CompletionRoutine _completionRoutine; private State _state; internal WorkList(DkmWorkList workList, CompletionRoutine<Exception> onException) { InnerWorkList = workList; _onException = onException; _state = State.Initialized; } /// <summary> /// Run the continuation synchronously if there is no current /// continuation. Otherwise hold on to the continuation for /// the current execution to complete. /// </summary> internal void ContinueWith(CompletionRoutine completionRoutine) { Debug.Assert(_completionRoutine == null); _completionRoutine = completionRoutine; if (_state != State.Executing) { Execute(); } } private void Execute() { Debug.Assert(_state != State.Executing); _state = State.Executing; while (_completionRoutine != null) { var completionRoutine = _completionRoutine; _completionRoutine = null; try { completionRoutine(); } catch (Exception e) { _onException(e); } } _state = State.Executed; } } private class NullableMemberInfo : DkmDataItem { public readonly DkmEvaluationResultCategory Category; public readonly DkmEvaluationResultAccessType Access; public readonly DkmEvaluationResultStorageType StorageType; public readonly DkmEvaluationResultTypeModifierFlags TypeModifierFlags; public NullableMemberInfo(DkmEvaluationResultCategory category, DkmEvaluationResultAccessType access, DkmEvaluationResultStorageType storageType, DkmEvaluationResultTypeModifierFlags typeModifierFlags) { Category = category; Access = access; StorageType = storageType; TypeModifierFlags = typeModifierFlags; } } } }
// Licensed to the .NET Foundation under one or more 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 #pragma warning disable CA1825 // Avoid zero-length array allocations. using System; using System.Collections.ObjectModel; using System.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Microsoft.VisualStudio.Debugger.Metadata; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal delegate void CompletionRoutine(); internal delegate void CompletionRoutine<TResult>(TResult result); /// <summary> /// Computes expansion of <see cref="DkmClrValue"/> instances. /// </summary> /// <remarks> /// This class provides implementation for the default ResultProvider component. /// </remarks> public abstract class ResultProvider : IDkmClrResultProvider { static ResultProvider() { FatalError.Handler = FailFast.OnFatalException; } // Fields should be removed and replaced with calls through DkmInspectionContext. // (see https://github.com/dotnet/roslyn/issues/6899). internal readonly IDkmClrFormatter2 Formatter2; internal readonly IDkmClrFullNameProvider FullNameProvider; internal ResultProvider(IDkmClrFormatter2 formatter2, IDkmClrFullNameProvider fullNameProvider) { Formatter2 = formatter2; FullNameProvider = fullNameProvider; } internal abstract string StaticMembersString { get; } internal abstract bool IsPrimitiveType(Type type); void IDkmClrResultProvider.GetResult(DkmClrValue value, DkmWorkList workList, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers, string resultName, string resultFullName, DkmCompletionRoutine<DkmEvaluationAsyncResult> completionRoutine) { if (formatSpecifiers == null) { formatSpecifiers = Formatter.NoFormatSpecifiers; } if (resultFullName != null) { ReadOnlyCollection<string> otherSpecifiers; resultFullName = FullNameProvider.GetClrExpressionAndFormatSpecifiers(inspectionContext, resultFullName, out otherSpecifiers); foreach (var formatSpecifier in otherSpecifiers) { formatSpecifiers = Formatter.AddFormatSpecifier(formatSpecifiers, formatSpecifier); } } var wl = new WorkList(workList, e => completionRoutine(DkmEvaluationAsyncResult.CreateErrorResult(e))); wl.ContinueWith( () => GetRootResultAndContinue( value, wl, declaredType, declaredTypeInfo, inspectionContext, resultName, resultFullName, formatSpecifiers, result => wl.ContinueWith(() => completionRoutine(new DkmEvaluationAsyncResult(result))))); } DkmClrValue IDkmClrResultProvider.GetClrValue(DkmSuccessEvaluationResult evaluationResult) { try { var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>(); if (dataItem == null) { // We don't know about this result. Call next implementation return evaluationResult.GetClrValue(); } return dataItem.Value; } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } internal const DkmEvaluationFlags NotRoot = (DkmEvaluationFlags)0x20000; internal const DkmEvaluationFlags NoResults = (DkmEvaluationFlags)0x40000; void IDkmClrResultProvider.GetChildren(DkmEvaluationResult evaluationResult, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine) { var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>(); if (dataItem == null) { // We don't know about this result. Call next implementation evaluationResult.GetChildren(workList, initialRequestSize, inspectionContext, completionRoutine); return; } var expansion = dataItem.Expansion; if (expansion == null) { var enumContext = DkmEvaluationResultEnumContext.Create(0, evaluationResult.StackFrame, inspectionContext, new EnumContextDataItem(evaluationResult)); completionRoutine(new DkmGetChildrenAsyncResult(new DkmEvaluationResult[0], enumContext)); return; } // Evaluate children with InspectionContext that is not the root. inspectionContext = inspectionContext.With(NotRoot); var rows = ArrayBuilder<EvalResult>.GetInstance(); int index = 0; expansion.GetRows(this, rows, inspectionContext, dataItem, dataItem.Value, 0, initialRequestSize, visitAll: true, index: ref index); var numRows = rows.Count; Debug.Assert(index >= numRows); Debug.Assert(initialRequestSize >= numRows); var initialChildren = new DkmEvaluationResult[numRows]; void onException(Exception e) => completionRoutine(DkmGetChildrenAsyncResult.CreateErrorResult(e)); var wl = new WorkList(workList, onException); wl.ContinueWith(() => GetEvaluationResultsAndContinue(evaluationResult, rows, initialChildren, 0, numRows, wl, inspectionContext, () => wl.ContinueWith( () => { var enumContext = DkmEvaluationResultEnumContext.Create(index, evaluationResult.StackFrame, inspectionContext, new EnumContextDataItem(evaluationResult)); completionRoutine(new DkmGetChildrenAsyncResult(initialChildren, enumContext)); rows.Free(); }), onException)); } void IDkmClrResultProvider.GetItems(DkmEvaluationResultEnumContext enumContext, DkmWorkList workList, int startIndex, int count, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine) { var enumContextDataItem = enumContext.GetDataItem<EnumContextDataItem>(); if (enumContextDataItem == null) { // We don't know about this result. Call next implementation enumContext.GetItems(workList, startIndex, count, completionRoutine); return; } var evaluationResult = enumContextDataItem.Result; var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>(); var expansion = dataItem.Expansion; if (expansion == null) { completionRoutine(new DkmEvaluationEnumAsyncResult(new DkmEvaluationResult[0])); return; } var inspectionContext = enumContext.InspectionContext; var rows = ArrayBuilder<EvalResult>.GetInstance(); int index = 0; expansion.GetRows(this, rows, inspectionContext, dataItem, dataItem.Value, startIndex, count, visitAll: false, index: ref index); var numRows = rows.Count; Debug.Assert(count >= numRows); var results = new DkmEvaluationResult[numRows]; void onException(Exception e) => completionRoutine(DkmEvaluationEnumAsyncResult.CreateErrorResult(e)); var wl = new WorkList(workList, onException); wl.ContinueWith(() => GetEvaluationResultsAndContinue(evaluationResult, rows, results, 0, numRows, wl, inspectionContext, () => wl.ContinueWith( () => { completionRoutine(new DkmEvaluationEnumAsyncResult(results)); rows.Free(); }), onException)); } string IDkmClrResultProvider.GetUnderlyingString(DkmEvaluationResult result) { try { var dataItem = result.GetDataItem<EvalResultDataItem>(); if (dataItem == null) { // We don't know about this result. Call next implementation return result.GetUnderlyingString(); } return dataItem.Value?.GetUnderlyingString(result.InspectionContext); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } private void GetChild( DkmEvaluationResult parent, WorkList workList, EvalResult row, DkmCompletionRoutine<DkmEvaluationAsyncResult> completionRoutine) { var inspectionContext = row.InspectionContext; if ((row.Kind != ExpansionKind.Default) || (row.Value == null)) { CreateEvaluationResultAndContinue( row, workList, row.InspectionContext, parent.StackFrame, child => completionRoutine(new DkmEvaluationAsyncResult(child))); } else { var typeDeclaringMember = row.TypeDeclaringMemberAndInfo; var name = (typeDeclaringMember.Type == null) ? row.Name : GetQualifiedMemberName(row.InspectionContext, typeDeclaringMember, row.Name, FullNameProvider); row.Value.SetDataItem(DkmDataCreationDisposition.CreateAlways, new FavoritesDataItem(row.CanFavorite, row.IsFavorite)); row.Value.GetResult( workList.InnerWorkList, row.DeclaredTypeAndInfo.ClrType, row.DeclaredTypeAndInfo.Info, row.InspectionContext, Formatter.NoFormatSpecifiers, name, row.FullName, result => workList.ContinueWith(() => completionRoutine(result))); } } private void CreateEvaluationResultAndContinue(EvalResult result, WorkList workList, DkmInspectionContext inspectionContext, DkmStackWalkFrame stackFrame, CompletionRoutine<DkmEvaluationResult> completionRoutine) { switch (result.Kind) { case ExpansionKind.Explicit: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, Name: result.DisplayName, FullName: result.FullName, Flags: result.Flags, Value: result.DisplayValue, EditableValue: result.EditableValue, Type: result.DisplayType, Category: DkmEvaluationResultCategory.Data, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.Error: completionRoutine(DkmFailedEvaluationResult.Create( inspectionContext, StackFrame: stackFrame, Name: result.Name, FullName: result.FullName, ErrorMessage: result.DisplayValue, Flags: DkmEvaluationResultFlags.None, Type: null, DataItem: null)); break; case ExpansionKind.NativeView: { var value = result.Value; var name = Resources.NativeView; var fullName = result.FullName; var display = result.Name; DkmEvaluationResult evalResult; if (value.IsError()) { evalResult = DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, Name: name, FullName: fullName, ErrorMessage: display, Flags: result.Flags, Type: null, DataItem: result.ToDataItem()); } else { // For Native View, create a DkmIntermediateEvaluationResult. // This will allow the C++ EE to take over expansion. var process = inspectionContext.RuntimeInstance.Process; var cpp = process.EngineSettings.GetLanguage(new DkmCompilerId(DkmVendorId.Microsoft, DkmLanguageId.Cpp)); evalResult = DkmIntermediateEvaluationResult.Create( inspectionContext, stackFrame, Name: name, FullName: fullName, Expression: display, IntermediateLanguage: cpp, TargetRuntime: process.GetNativeRuntimeInstance(), DataItem: result.ToDataItem()); } completionRoutine(evalResult); } break; case ExpansionKind.NonPublicMembers: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, Name: Resources.NonPublicMembers, FullName: result.FullName, Flags: result.Flags, Value: null, EditableValue: null, Type: string.Empty, Category: DkmEvaluationResultCategory.Data, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.StaticMembers: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, Name: StaticMembersString, FullName: result.FullName, Flags: result.Flags, Value: null, EditableValue: null, Type: string.Empty, Category: DkmEvaluationResultCategory.Class, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.RawView: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, Name: Resources.RawView, FullName: result.FullName, Flags: result.Flags, Value: null, EditableValue: result.EditableValue, Type: string.Empty, Category: DkmEvaluationResultCategory.Data, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.DynamicView: case ExpansionKind.ResultsView: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, result.Name, result.FullName, result.Flags, result.DisplayValue, EditableValue: null, Type: string.Empty, Category: DkmEvaluationResultCategory.Method, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.TypeVariable: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, result.Name, result.FullName, result.Flags, result.DisplayValue, EditableValue: null, Type: result.DisplayValue, Category: DkmEvaluationResultCategory.Data, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.PointerDereference: case ExpansionKind.Default: // This call will evaluate DebuggerDisplayAttributes. GetResultAndContinue( result, workList, declaredType: result.DeclaredTypeAndInfo.ClrType, declaredTypeInfo: result.DeclaredTypeAndInfo.Info, inspectionContext: inspectionContext, useDebuggerDisplay: result.UseDebuggerDisplay, completionRoutine: completionRoutine); break; default: throw ExceptionUtilities.UnexpectedValue(result.Kind); } } private static DkmEvaluationResult CreateEvaluationResult( DkmInspectionContext inspectionContext, DkmClrValue value, string name, string typeName, string display, EvalResult result) { if (value.IsError()) { // Evaluation failed return DkmFailedEvaluationResult.Create( InspectionContext: inspectionContext, StackFrame: value.StackFrame, Name: name, FullName: result.FullName, ErrorMessage: display, Flags: result.Flags, Type: typeName, DataItem: result.ToDataItem()); } else { ReadOnlyCollection<DkmCustomUIVisualizerInfo> customUIVisualizers = null; if (!value.IsNull) { DkmCustomUIVisualizerInfo[] customUIVisualizerInfo = value.Type.GetDebuggerCustomUIVisualizerInfo(); if (customUIVisualizerInfo != null) { customUIVisualizers = new ReadOnlyCollection<DkmCustomUIVisualizerInfo>(customUIVisualizerInfo); } } // If the EvalResultDataItem doesn't specify a particular category, we'll just propagate DkmClrValue.Category, // which typically appears to be set to the default value ("Other"). var category = (result.Category != DkmEvaluationResultCategory.Other) ? result.Category : value.Category; var nullableMemberInfo = value.GetDataItem<NullableMemberInfo>(); // Valid value return DkmSuccessEvaluationResult.Create( InspectionContext: inspectionContext, StackFrame: value.StackFrame, Name: name, FullName: result.FullName, Flags: result.Flags, Value: display, EditableValue: result.EditableValue, Type: typeName, Category: nullableMemberInfo?.Category ?? category, Access: nullableMemberInfo?.Access ?? value.Access, StorageType: nullableMemberInfo?.StorageType ?? value.StorageType, TypeModifierFlags: nullableMemberInfo?.TypeModifierFlags ?? value.TypeModifierFlags, Address: value.Address, CustomUIVisualizers: customUIVisualizers, ExternalModules: null, DataItem: result.ToDataItem()); } } /// <returns> /// The qualified name (i.e. including containing types and namespaces) of a named, pointer, /// or array type followed by the qualified name of the actual runtime type, if provided. /// </returns> internal static string GetTypeName( DkmInspectionContext inspectionContext, DkmClrValue value, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, bool isPointerDereference) { var declaredLmrType = declaredType.GetLmrType(); var runtimeType = value.Type; var declaredTypeName = inspectionContext.GetTypeName(declaredType, declaredTypeInfo, Formatter.NoFormatSpecifiers); // Include the runtime type if distinct. if (!declaredLmrType.IsPointer && !isPointerDereference && (!declaredLmrType.IsNullable() || value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown))) { // Generate the declared type name without tuple element names. var declaredTypeInfoNoTupleElementNames = declaredTypeInfo.WithNoTupleElementNames(); var declaredTypeNameNoTupleElementNames = (declaredTypeInfo == declaredTypeInfoNoTupleElementNames) ? declaredTypeName : inspectionContext.GetTypeName(declaredType, declaredTypeInfoNoTupleElementNames, Formatter.NoFormatSpecifiers); // Generate the runtime type name with no tuple element names and no dynamic. var runtimeTypeName = inspectionContext.GetTypeName(runtimeType, null, FormatSpecifiers: Formatter.NoFormatSpecifiers); // If the two names are distinct, include both. if (!string.Equals(declaredTypeNameNoTupleElementNames, runtimeTypeName, StringComparison.Ordinal)) // Names will reflect "dynamic", types will not. { return string.Format("{0} {{{1}}}", declaredTypeName, runtimeTypeName); } } return declaredTypeName; } internal EvalResult CreateDataItem( DkmInspectionContext inspectionContext, string name, TypeAndCustomInfo typeDeclaringMemberAndInfo, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value, bool useDebuggerDisplay, ExpansionFlags expansionFlags, bool childShouldParenthesize, string fullName, ReadOnlyCollection<string> formatSpecifiers, DkmEvaluationResultCategory category, DkmEvaluationResultFlags flags, DkmEvaluationFlags evalFlags, bool canFavorite, bool isFavorite, bool supportsFavorites) { if ((evalFlags & DkmEvaluationFlags.ShowValueRaw) != 0) { formatSpecifiers = Formatter.AddFormatSpecifier(formatSpecifiers, "raw"); } Expansion expansion; // If the declared type is Nullable<T>, the value should // have no expansion if null, or be expanded as a T. var declaredType = declaredTypeAndInfo.Type; var lmrNullableTypeArg = declaredType.GetNullableTypeArgument(); if (lmrNullableTypeArg != null && !value.HasExceptionThrown()) { Debug.Assert(value.Type.GetProxyType() == null); DkmClrValue nullableValue; if (value.IsError()) { expansion = null; } else if ((nullableValue = value.GetNullableValue(lmrNullableTypeArg, inspectionContext)) == null) { Debug.Assert(declaredType.Equals(value.Type.GetLmrType())); // No expansion of "null". expansion = null; } else { // nullableValue is taken from an internal field. // It may have different category, access, etc comparing the original member. // For example, the orignal member can be a property not a field. // Save original member values to restore them later. if (value != nullableValue) { var nullableMemberInfo = new NullableMemberInfo(value.Category, value.Access, value.StorageType, value.TypeModifierFlags); nullableValue.SetDataItem(DkmDataCreationDisposition.CreateAlways, nullableMemberInfo); } value = nullableValue; Debug.Assert(lmrNullableTypeArg.Equals(value.Type.GetLmrType())); // If this is not the case, add a test for includeRuntimeTypeIfNecessary. // CONSIDER: The DynamicAttribute for the type argument should just be Skip(1) of the original flag array. expansion = this.GetTypeExpansion(inspectionContext, new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, lmrNullableTypeArg)), value, ExpansionFlags.IncludeResultsView, supportsFavorites: supportsFavorites); } } else if (value.IsError() || (inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) != 0) { expansion = null; } else { expansion = DebuggerTypeProxyExpansion.CreateExpansion( this, inspectionContext, name, typeDeclaringMemberAndInfo, declaredTypeAndInfo, value, childShouldParenthesize, fullName, flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName, formatSpecifiers, flags, Formatter2.GetEditableValueString(value, inspectionContext, declaredTypeAndInfo.Info)); if (expansion == null) { expansion = value.HasExceptionThrown() ? this.GetTypeExpansion(inspectionContext, new TypeAndCustomInfo(value.Type), value, expansionFlags, supportsFavorites: false) : this.GetTypeExpansion(inspectionContext, declaredTypeAndInfo, value, expansionFlags, supportsFavorites: supportsFavorites); } } return new EvalResult( ExpansionKind.Default, name, typeDeclaringMemberAndInfo, declaredTypeAndInfo, useDebuggerDisplay: useDebuggerDisplay, value: value, displayValue: null, expansion: expansion, childShouldParenthesize: childShouldParenthesize, fullName: fullName, childFullNamePrefixOpt: flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName, formatSpecifiers: formatSpecifiers, category: category, flags: flags, editableValue: Formatter2.GetEditableValueString(value, inspectionContext, declaredTypeAndInfo.Info), inspectionContext: inspectionContext, canFavorite: canFavorite, isFavorite: isFavorite); } private void GetRootResultAndContinue( DkmClrValue value, WorkList workList, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, DkmInspectionContext inspectionContext, string name, string fullName, ReadOnlyCollection<string> formatSpecifiers, CompletionRoutine<DkmEvaluationResult> completionRoutine) { Debug.Assert(formatSpecifiers != null); var type = value.Type.GetLmrType(); if (type.IsTypeVariables()) { Debug.Assert(type.Equals(declaredType.GetLmrType())); var declaredTypeAndInfo = new TypeAndCustomInfo(declaredType, declaredTypeInfo); var expansion = new TypeVariablesExpansion(declaredTypeAndInfo); var dataItem = new EvalResult( ExpansionKind.Default, name, typeDeclaringMemberAndInfo: default(TypeAndCustomInfo), declaredTypeAndInfo: declaredTypeAndInfo, useDebuggerDisplay: false, value: value, displayValue: null, expansion: expansion, childShouldParenthesize: false, fullName: null, childFullNamePrefixOpt: null, formatSpecifiers: Formatter.NoFormatSpecifiers, category: DkmEvaluationResultCategory.Data, flags: DkmEvaluationResultFlags.ReadOnly, editableValue: null, inspectionContext: inspectionContext); Debug.Assert(dataItem.Flags == (DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.Expandable)); // Note: We're not including value.EvalFlags in Flags parameter // below (there shouldn't be a reason to do so). completionRoutine(DkmSuccessEvaluationResult.Create( InspectionContext: inspectionContext, StackFrame: value.StackFrame, Name: Resources.TypeVariablesName, FullName: dataItem.FullName, Flags: dataItem.Flags, Value: "", EditableValue: null, Type: "", Category: dataItem.Category, Access: value.Access, StorageType: value.StorageType, TypeModifierFlags: value.TypeModifierFlags, Address: value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: dataItem.ToDataItem())); } else if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.ResultsOnly) != 0) { var dataItem = ResultsViewExpansion.CreateResultsOnlyRow( inspectionContext, name, fullName, formatSpecifiers, declaredType, declaredTypeInfo, value, this); CreateEvaluationResultAndContinue( dataItem, workList, inspectionContext, value.StackFrame, completionRoutine); } else if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.DynamicView) != 0) { var dataItem = DynamicViewExpansion.CreateMembersOnlyRow( inspectionContext, name, value, this); CreateEvaluationResultAndContinue( dataItem, workList, inspectionContext, value.StackFrame, completionRoutine); } else { var dataItem = ResultsViewExpansion.CreateResultsOnlyRowIfSynthesizedEnumerable( inspectionContext, name, fullName, formatSpecifiers, declaredType, declaredTypeInfo, value, this); if (dataItem != null) { CreateEvaluationResultAndContinue( dataItem, workList, inspectionContext, value.StackFrame, completionRoutine); } else { var useDebuggerDisplay = (inspectionContext.EvaluationFlags & NotRoot) != 0; var expansionFlags = (inspectionContext.EvaluationFlags & NoResults) != 0 ? ExpansionFlags.IncludeBaseMembers : ExpansionFlags.All; var favortiesDataItem = value.GetDataItem<FavoritesDataItem>(); dataItem = CreateDataItem( inspectionContext, name, typeDeclaringMemberAndInfo: default(TypeAndCustomInfo), declaredTypeAndInfo: new TypeAndCustomInfo(declaredType, declaredTypeInfo), value: value, useDebuggerDisplay: useDebuggerDisplay, expansionFlags: expansionFlags, childShouldParenthesize: (fullName == null) ? false : FullNameProvider.ClrExpressionMayRequireParentheses(inspectionContext, fullName), fullName: fullName, formatSpecifiers: formatSpecifiers, category: DkmEvaluationResultCategory.Other, flags: value.EvalFlags, evalFlags: inspectionContext.EvaluationFlags, canFavorite: favortiesDataItem?.CanFavorite ?? false, isFavorite: favortiesDataItem?.IsFavorite ?? false, supportsFavorites: true); GetResultAndContinue(dataItem, workList, declaredType, declaredTypeInfo, inspectionContext, useDebuggerDisplay, completionRoutine); } } } private void GetResultAndContinue( EvalResult result, WorkList workList, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, DkmInspectionContext inspectionContext, bool useDebuggerDisplay, CompletionRoutine<DkmEvaluationResult> completionRoutine) { var value = result.Value; // Value may have been replaced (specifically, for Nullable<T>). if (value.TryGetDebuggerDisplayInfo(out DebuggerDisplayInfo displayInfo)) { void onException(Exception e) => completionRoutine(CreateEvaluationResultFromException(e, result, inspectionContext)); if (displayInfo.Name != null) { // Favorites currently dependes on the name matching the member name result = result.WithDisableCanAddFavorite(); } var innerWorkList = workList.InnerWorkList; EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, displayInfo.Name, displayName => EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, displayInfo.GetValue(inspectionContext), displayValue => EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, displayInfo.TypeName, displayType => workList.ContinueWith(() => completionRoutine(GetResult(inspectionContext, result, declaredType, declaredTypeInfo, displayName.Result, displayValue.Result, displayType.Result, useDebuggerDisplay))), onException), onException), onException); } else { completionRoutine(GetResult(inspectionContext, result, declaredType, declaredTypeInfo, displayName: null, displayValue: null, displayType: null, useDebuggerDisplay: false)); } } private static void EvaluateDebuggerDisplayStringAndContinue( DkmClrValue value, DkmWorkList workList, DkmInspectionContext inspectionContext, DebuggerDisplayItemInfo displayInfo, CompletionRoutine<DkmEvaluateDebuggerDisplayStringAsyncResult> onCompleted, CompletionRoutine<Exception> onException) { void completionRoutine(DkmEvaluateDebuggerDisplayStringAsyncResult result) { try { onCompleted(result); } catch (Exception e) { onException(e); } } if (displayInfo == null) { completionRoutine(default(DkmEvaluateDebuggerDisplayStringAsyncResult)); } else { value.EvaluateDebuggerDisplayString(workList, inspectionContext, displayInfo.TargetType, displayInfo.Value, completionRoutine); } } private DkmEvaluationResult GetResult( DkmInspectionContext inspectionContext, EvalResult result, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, string displayName, string displayValue, string displayType, bool useDebuggerDisplay) { var name = result.Name; Debug.Assert(name != null); var typeDeclaringMemberAndInfo = result.TypeDeclaringMemberAndInfo; // Note: Don't respect the debugger display name on the root element: // 1) In the Watch window, that's where the user's text goes. // 2) In the Locals window, that's where the local name goes. // Note: Dev12 respects the debugger display name in the Locals window, // but not in the Watch window, but we can't distinguish and this // behavior seems reasonable. if (displayName != null && useDebuggerDisplay) { name = displayName; } else if (typeDeclaringMemberAndInfo.Type != null) { name = GetQualifiedMemberName(inspectionContext, typeDeclaringMemberAndInfo, name, FullNameProvider); } var value = result.Value; string display; if (value.HasExceptionThrown()) { display = result.DisplayValue ?? value.GetExceptionMessage(inspectionContext, result.FullNameWithoutFormatSpecifiers ?? result.Name); } else if (displayValue != null) { display = value.IncludeObjectId(displayValue); } else { display = value.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers); } var typeName = displayType ?? GetTypeName(inspectionContext, value, declaredType, declaredTypeInfo, result.Kind == ExpansionKind.PointerDereference); return CreateEvaluationResult(inspectionContext, value, name, typeName, display, result); } private void GetEvaluationResultsAndContinue( DkmEvaluationResult parent, ArrayBuilder<EvalResult> rows, DkmEvaluationResult[] results, int index, int numRows, WorkList workList, DkmInspectionContext inspectionContext, CompletionRoutine onCompleted, CompletionRoutine<Exception> onException) { void completionRoutine(DkmEvaluationAsyncResult result) { try { results[index] = result.Result; GetEvaluationResultsAndContinue(parent, rows, results, index + 1, numRows, workList, inspectionContext, onCompleted, onException); } catch (Exception e) { onException(e); } } if (index < numRows) { GetChild( parent, workList, rows[index], child => workList.ContinueWith(() => completionRoutine(child))); } else { onCompleted(); } } internal Expansion GetTypeExpansion( DkmInspectionContext inspectionContext, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value, ExpansionFlags flags, bool supportsFavorites) { var declaredType = declaredTypeAndInfo.Type; Debug.Assert(!declaredType.IsTypeVariables()); if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) != 0) { return null; } var runtimeType = value.Type.GetLmrType(); // If the value is an array, expand the array elements. if (runtimeType.IsArray) { var sizes = value.ArrayDimensions; if (sizes == null) { // Null array. No expansion. return null; } var lowerBounds = value.ArrayLowerBounds; Type elementType; DkmClrCustomTypeInfo elementTypeInfo; if (declaredType.IsArray) { elementType = declaredType.GetElementType(); elementTypeInfo = CustomTypeInfo.SkipOne(declaredTypeAndInfo.Info); } else { elementType = runtimeType.GetElementType(); elementTypeInfo = null; } return ArrayExpansion.CreateExpansion(new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, elementType), elementTypeInfo), sizes, lowerBounds); } if (this.IsPrimitiveType(runtimeType)) { return null; } if (declaredType.IsFunctionPointer()) { // Function pointers have no expansion return null; } if (declaredType.IsPointer) { // If this assert fails, the element type info is just .SkipOne(). Debug.Assert(declaredTypeAndInfo.Info?.PayloadTypeId != CustomTypeInfo.PayloadTypeId); var elementType = declaredType.GetElementType(); return value.IsNull || elementType.IsVoid() ? null : new PointerDereferenceExpansion(new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, elementType))); } if (value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown) && runtimeType.IsEmptyResultsViewException()) { // The value is an exception thrown expanding an empty // IEnumerable. Use the runtime type of the exception and // skip base types. (This matches the native EE behavior // to expose a single property from the exception.) flags &= ~ExpansionFlags.IncludeBaseMembers; } int cardinality; if (runtimeType.IsTupleCompatible(out cardinality)) { return TupleExpansion.CreateExpansion(inspectionContext, declaredTypeAndInfo, value, cardinality); } return MemberExpansion.CreateExpansion(inspectionContext, declaredTypeAndInfo, value, flags, TypeHelpers.IsVisibleMember, this, isProxyType: false, supportsFavorites); } private static DkmEvaluationResult CreateEvaluationResultFromException(Exception e, EvalResult result, DkmInspectionContext inspectionContext) { return DkmFailedEvaluationResult.Create( inspectionContext, result.Value.StackFrame, Name: result.Name, FullName: null, ErrorMessage: e.Message, Flags: DkmEvaluationResultFlags.None, Type: null, DataItem: null); } private static string GetQualifiedMemberName( DkmInspectionContext inspectionContext, TypeAndCustomInfo typeDeclaringMember, string memberName, IDkmClrFullNameProvider fullNameProvider) { var typeName = fullNameProvider.GetClrTypeName(inspectionContext, typeDeclaringMember.ClrType, typeDeclaringMember.Info) ?? inspectionContext.GetTypeName(typeDeclaringMember.ClrType, typeDeclaringMember.Info, Formatter.NoFormatSpecifiers); return typeDeclaringMember.Type.IsInterface ? $"{typeName}.{memberName}" : $"{memberName} ({typeName})"; } // Track remaining evaluations so that each subsequent evaluation // is executed at the entry point from the host rather than on the // callstack of the previous evaluation. private sealed class WorkList { private enum State { Initialized, Executing, Executed } internal readonly DkmWorkList InnerWorkList; private readonly CompletionRoutine<Exception> _onException; private CompletionRoutine _completionRoutine; private State _state; internal WorkList(DkmWorkList workList, CompletionRoutine<Exception> onException) { InnerWorkList = workList; _onException = onException; _state = State.Initialized; } /// <summary> /// Run the continuation synchronously if there is no current /// continuation. Otherwise hold on to the continuation for /// the current execution to complete. /// </summary> internal void ContinueWith(CompletionRoutine completionRoutine) { Debug.Assert(_completionRoutine == null); _completionRoutine = completionRoutine; if (_state != State.Executing) { Execute(); } } private void Execute() { Debug.Assert(_state != State.Executing); _state = State.Executing; while (_completionRoutine != null) { var completionRoutine = _completionRoutine; _completionRoutine = null; try { completionRoutine(); } catch (Exception e) { _onException(e); } } _state = State.Executed; } } private class NullableMemberInfo : DkmDataItem { public readonly DkmEvaluationResultCategory Category; public readonly DkmEvaluationResultAccessType Access; public readonly DkmEvaluationResultStorageType StorageType; public readonly DkmEvaluationResultTypeModifierFlags TypeModifierFlags; public NullableMemberInfo(DkmEvaluationResultCategory category, DkmEvaluationResultAccessType access, DkmEvaluationResultStorageType storageType, DkmEvaluationResultTypeModifierFlags typeModifierFlags) { Category = category; Access = access; StorageType = storageType; TypeModifierFlags = typeModifierFlags; } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService.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 System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeActions.WorkspaceServices; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService), ServiceLayer.Host), Shared] internal sealed class VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService : IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService() { } public CodeActionOperation CreateAddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (assemblyIdentity == null) { throw new ArgumentNullException(nameof(assemblyIdentity)); } return new AddMetadataReferenceOperation(projectId, assemblyIdentity); } private class AddMetadataReferenceOperation : Microsoft.CodeAnalysis.CodeActions.CodeActionOperation { private readonly AssemblyIdentity _assemblyIdentity; private readonly ProjectId _projectId; public AddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity) { _projectId = projectId; _assemblyIdentity = assemblyIdentity; } public override void Apply(Microsoft.CodeAnalysis.Workspace workspace, CancellationToken cancellationToken = default) { var visualStudioWorkspace = (VisualStudioWorkspaceImpl)workspace; if (!visualStudioWorkspace.TryAddReferenceToProject(_projectId, "*" + _assemblyIdentity.GetDisplayName())) { // We failed to add the reference, which means the project system wasn't able to bind. // We'll pop up the Add Reference dialog to let the user figure this out themselves. // This is the same approach done in CVBErrorFixApply::ApplyAddMetaReferenceFix if (visualStudioWorkspace.GetHierarchy(_projectId) is IVsUIHierarchy uiHierarchy) { var command = new OLECMD[1]; command[0].cmdID = (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE; if (ErrorHandler.Succeeded(uiHierarchy.QueryStatusCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, 1, command, IntPtr.Zero))) { if ((((OLECMDF)command[0].cmdf) & OLECMDF.OLECMDF_ENABLED) != 0) { uiHierarchy.ExecCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE, 0, IntPtr.Zero, IntPtr.Zero); } } } } } public override string Title => string.Format(ServicesVSResources.Add_a_reference_to_0, _assemblyIdentity.GetDisplayName()); } } }
// Licensed to the .NET Foundation under one or more 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 System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeActions.WorkspaceServices; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService), ServiceLayer.Host), Shared] internal sealed class VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService : IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService() { } public CodeActionOperation CreateAddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (assemblyIdentity == null) { throw new ArgumentNullException(nameof(assemblyIdentity)); } return new AddMetadataReferenceOperation(projectId, assemblyIdentity); } private class AddMetadataReferenceOperation : Microsoft.CodeAnalysis.CodeActions.CodeActionOperation { private readonly AssemblyIdentity _assemblyIdentity; private readonly ProjectId _projectId; public AddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity) { _projectId = projectId; _assemblyIdentity = assemblyIdentity; } public override void Apply(Microsoft.CodeAnalysis.Workspace workspace, CancellationToken cancellationToken = default) { var visualStudioWorkspace = (VisualStudioWorkspaceImpl)workspace; if (!visualStudioWorkspace.TryAddReferenceToProject(_projectId, "*" + _assemblyIdentity.GetDisplayName())) { // We failed to add the reference, which means the project system wasn't able to bind. // We'll pop up the Add Reference dialog to let the user figure this out themselves. // This is the same approach done in CVBErrorFixApply::ApplyAddMetaReferenceFix if (visualStudioWorkspace.GetHierarchy(_projectId) is IVsUIHierarchy uiHierarchy) { var command = new OLECMD[1]; command[0].cmdID = (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE; if (ErrorHandler.Succeeded(uiHierarchy.QueryStatusCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, 1, command, IntPtr.Zero))) { if ((((OLECMDF)command[0].cmdf) & OLECMDF.OLECMDF_ENABLED) != 0) { uiHierarchy.ExecCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE, 0, IntPtr.Zero, IntPtr.Zero); } } } } } public override string Title => string.Format(ServicesVSResources.Add_a_reference_to_0, _assemblyIdentity.GetDisplayName()); } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Compilers/CSharp/Test/Semantic/SourceGeneration/StateTableTests.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.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class StateTableTests { [Fact] public void Node_Table_Entries_Can_Be_Enumerated() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); builder.AddEntries(ImmutableArray.Create(2), EntryState.Added); builder.AddEntries(ImmutableArray.Create(3), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Table_Entries_Are_Flattened_When_Enumerated() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Added); builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added), (5, EntryState.Added), (6, EntryState.Added), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Table_Entries_Can_Be_The_Same_Object() { var o = new object(); var builder = NodeStateTable<object>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(o, o, o), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((o, EntryState.Added), (o, EntryState.Added), (o, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Table_Entries_Can_Be_Null() { object? o = new object(); var builder = NodeStateTable<object?>.Empty.ToBuilder(); builder.AddEntry(o, EntryState.Added); builder.AddEntry(null, EntryState.Added); builder.AddEntry(o, EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((o, EntryState.Added), (null, EntryState.Added), (o, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Builder_Can_Add_Entries_From_Previous_Table() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); builder.AddEntries(ImmutableArray.Create(2, 3), EntryState.Cached); builder.AddEntries(ImmutableArray.Create(4, 5), EntryState.Modified); builder.AddEntries(ImmutableArray.Create(6), EntryState.Added); var previousTable = builder.ToImmutableAndFree(); builder = previousTable.ToBuilder(); builder.AddEntries(ImmutableArray.Create(10, 11), EntryState.Added); builder.TryUseCachedEntries(); // ((2, EntryState.Cached), (3, EntryState.Cached)) builder.AddEntries(ImmutableArray.Create(20, 21, 22), EntryState.Modified); builder.RemoveEntries(); //((6, EntryState.Removed))); var newTable = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((10, EntryState.Added), (11, EntryState.Added), (2, EntryState.Cached), (3, EntryState.Cached), (20, EntryState.Modified), (21, EntryState.Modified), (22, EntryState.Modified), (6, EntryState.Removed)); AssertTableEntries(newTable, expected); } [Fact] public void Node_Table_Entries_Are_Cached_Or_Dropped_When_Cached() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Removed); builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Removed), (5, EntryState.Removed), (6, EntryState.Removed), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added)); AssertTableEntries(table, expected); var compactedTable = table.AsCached(); expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (7, EntryState.Cached), (8, EntryState.Cached), (9, EntryState.Cached)); AssertTableEntries(compactedTable, expected); } [Fact] public void Node_Table_AsCached_Occurs_Only_Once() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Removed); builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Removed), (5, EntryState.Removed), (6, EntryState.Removed), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added)); AssertTableEntries(table, expected); var compactedTable = table.AsCached(); expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (7, EntryState.Cached), (8, EntryState.Cached), (9, EntryState.Cached)); AssertTableEntries(compactedTable, expected); // calling as cached a second time just returns the same instance var compactedTable2 = compactedTable.AsCached(); Assert.Same(compactedTable, compactedTable2); } [Fact] public void Node_Table_Single_Returns_First_Item() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); var table = builder.ToImmutableAndFree(); Assert.Equal(1, table.Single()); } [Fact] public void Node_Table_Single_Returns_Second_Item_When_First_Is_Removed() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); var table = builder.ToImmutableAndFree(); AssertTableEntries(table, new[] { (1, EntryState.Added) }); // remove the first item and replace it in the table builder = table.ToBuilder(); builder.RemoveEntries(); builder.AddEntries(ImmutableArray.Create(2), EntryState.Added); table = builder.ToImmutableAndFree(); AssertTableEntries(table, new[] { (1, EntryState.Removed), (2, EntryState.Added) }); Assert.Equal(2, table.Single()); } [Fact] public void Node_Builder_Handles_Modification_When_Both_Tables_Have_Empty_Entries() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2), EntryState.Added); builder.AddEntries(ImmutableArray<int>.Empty, EntryState.Added); builder.AddEntries(ImmutableArray.Create(3, 4), EntryState.Added); var previousTable = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added)); AssertTableEntries(previousTable, expected); builder = previousTable.ToBuilder(); Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 2), EqualityComparer<int>.Default)); // ((3, EntryState.Modified), (2, EntryState.Cached)) Assert.True(builder.TryModifyEntries(ImmutableArray<int>.Empty, EqualityComparer<int>.Default)); // nothing Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 5), EqualityComparer<int>.Default)); // ((3, EntryState.Cached), (5, EntryState.Modified)) var newTable = builder.ToImmutableAndFree(); expected = ImmutableArray.Create((3, EntryState.Modified), (2, EntryState.Cached), (3, EntryState.Cached), (5, EntryState.Modified)); AssertTableEntries(newTable, expected); } [Fact] public void Node_Table_Doesnt_Modify_Single_Item_Multiple_Times_When_Same() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); builder.AddEntries(ImmutableArray.Create(2), EntryState.Added); builder.AddEntries(ImmutableArray.Create(3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4), EntryState.Added); var previousTable = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added)); AssertTableEntries(previousTable, expected); builder = previousTable.ToBuilder(); Assert.True(builder.TryModifyEntry(1, EqualityComparer<int>.Default)); // ((1, EntryState.Cached)) Assert.True(builder.TryModifyEntry(2, EqualityComparer<int>.Default)); // ((2, EntryState.Cached)) Assert.True(builder.TryModifyEntry(5, EqualityComparer<int>.Default)); // ((5, EntryState.Modified)) Assert.True(builder.TryModifyEntry(4, EqualityComparer<int>.Default)); // ((4, EntryState.Cached)) var newTable = builder.ToImmutableAndFree(); expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (5, EntryState.Modified), (4, EntryState.Cached)); AssertTableEntries(newTable, expected); } [Fact] public void Driver_Table_Calls_Into_Node_With_Self() { DriverStateTable.Builder? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = b; return s; }); DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(builder, passedIn); } [Fact] public void Driver_Table_Calls_Into_Node_With_EmptyState_FirstTime() { NodeStateTable<int>? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = s; return s; }); DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(NodeStateTable<int>.Empty, passedIn); } [Fact] public void Driver_Table_Calls_Into_Node_With_PreviousTable() { var nodeBuilder = NodeStateTable<int>.Empty.ToBuilder(); nodeBuilder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Cached); var newTable = nodeBuilder.ToImmutableAndFree(); NodeStateTable<int>? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = s; return newTable; }); // empty first time DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(NodeStateTable<int>.Empty, passedIn); // gives the returned table the second time around DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable()); builder2.GetLatestStateTableForNode(callbackNode); Assert.NotNull(passedIn); AssertTableEntries(passedIn!, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached) }); } [Fact] public void Driver_Table_Compacts_State_Tables_When_Made_Immutable() { var nodeBuilder = NodeStateTable<int>.Empty.ToBuilder(); nodeBuilder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); nodeBuilder.AddEntries(ImmutableArray.Create(4), EntryState.Removed); nodeBuilder.AddEntries(ImmutableArray.Create(5, 6), EntryState.Modified); var newTable = nodeBuilder.ToImmutableAndFree(); NodeStateTable<int>? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = s; return newTable; }); // empty first time DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(NodeStateTable<int>.Empty, passedIn); // gives the returned table the second time around DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable()); builder2.GetLatestStateTableForNode(callbackNode); // table returned from the first instance was compacted by the builder Assert.NotNull(passedIn); AssertTableEntries(passedIn!, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (5, EntryState.Cached), (6, EntryState.Cached) }); } [Fact] public void Driver_Table_Builder_Doesnt_Build_Twice() { int callCount = 0; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { callCount++; return s; }); // multiple gets will only call it once DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); builder.GetLatestStateTableForNode(callbackNode); builder.GetLatestStateTableForNode(callbackNode); Assert.Equal(1, callCount); // second time around we'll call it once, but no more DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable()); builder2.GetLatestStateTableForNode(callbackNode); builder2.GetLatestStateTableForNode(callbackNode); builder2.GetLatestStateTableForNode(callbackNode); Assert.Equal(2, callCount); } private void AssertTableEntries<T>(NodeStateTable<T> table, IList<(T item, EntryState state)> expected) { int index = 0; foreach (var entry in table) { Assert.Equal(expected[index].item, entry.item); Assert.Equal(expected[index].state, entry.state); index++; } } private DriverStateTable.Builder GetBuilder(DriverStateTable previous) { var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10); var c = CSharpCompilation.Create("empty"); var state = new GeneratorDriverState(options, CompilerAnalyzerConfigOptionsProvider.Empty, ImmutableArray<ISourceGenerator>.Empty, ImmutableArray<IIncrementalGenerator>.Empty, ImmutableArray<AdditionalText>.Empty, ImmutableArray<GeneratorState>.Empty, previous, enableIncremental: true, disabledOutputs: IncrementalGeneratorOutputKind.None); return new DriverStateTable.Builder(c, state, ImmutableArray<ISyntaxInputNode>.Empty); } private class CallbackNode<T> : IIncrementalGeneratorNode<T> { private readonly Func<DriverStateTable.Builder, NodeStateTable<T>, NodeStateTable<T>> _callback; public CallbackNode(Func<DriverStateTable.Builder, NodeStateTable<T>, NodeStateTable<T>> callback) { _callback = callback; } public NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken) { return _callback(graphState, previousTable); } public IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer) => this; public void RegisterOutput(IIncrementalGeneratorOutputNode output) { } } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class StateTableTests { [Fact] public void Node_Table_Entries_Can_Be_Enumerated() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); builder.AddEntries(ImmutableArray.Create(2), EntryState.Added); builder.AddEntries(ImmutableArray.Create(3), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Table_Entries_Are_Flattened_When_Enumerated() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Added); builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added), (5, EntryState.Added), (6, EntryState.Added), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Table_Entries_Can_Be_The_Same_Object() { var o = new object(); var builder = NodeStateTable<object>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(o, o, o), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((o, EntryState.Added), (o, EntryState.Added), (o, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Table_Entries_Can_Be_Null() { object? o = new object(); var builder = NodeStateTable<object?>.Empty.ToBuilder(); builder.AddEntry(o, EntryState.Added); builder.AddEntry(null, EntryState.Added); builder.AddEntry(o, EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((o, EntryState.Added), (null, EntryState.Added), (o, EntryState.Added)); AssertTableEntries(table, expected); } [Fact] public void Node_Builder_Can_Add_Entries_From_Previous_Table() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); builder.AddEntries(ImmutableArray.Create(2, 3), EntryState.Cached); builder.AddEntries(ImmutableArray.Create(4, 5), EntryState.Modified); builder.AddEntries(ImmutableArray.Create(6), EntryState.Added); var previousTable = builder.ToImmutableAndFree(); builder = previousTable.ToBuilder(); builder.AddEntries(ImmutableArray.Create(10, 11), EntryState.Added); builder.TryUseCachedEntries(); // ((2, EntryState.Cached), (3, EntryState.Cached)) builder.AddEntries(ImmutableArray.Create(20, 21, 22), EntryState.Modified); builder.RemoveEntries(); //((6, EntryState.Removed))); var newTable = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((10, EntryState.Added), (11, EntryState.Added), (2, EntryState.Cached), (3, EntryState.Cached), (20, EntryState.Modified), (21, EntryState.Modified), (22, EntryState.Modified), (6, EntryState.Removed)); AssertTableEntries(newTable, expected); } [Fact] public void Node_Table_Entries_Are_Cached_Or_Dropped_When_Cached() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Removed); builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Removed), (5, EntryState.Removed), (6, EntryState.Removed), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added)); AssertTableEntries(table, expected); var compactedTable = table.AsCached(); expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (7, EntryState.Cached), (8, EntryState.Cached), (9, EntryState.Cached)); AssertTableEntries(compactedTable, expected); } [Fact] public void Node_Table_AsCached_Occurs_Only_Once() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Removed); builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added); var table = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Removed), (5, EntryState.Removed), (6, EntryState.Removed), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added)); AssertTableEntries(table, expected); var compactedTable = table.AsCached(); expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (7, EntryState.Cached), (8, EntryState.Cached), (9, EntryState.Cached)); AssertTableEntries(compactedTable, expected); // calling as cached a second time just returns the same instance var compactedTable2 = compactedTable.AsCached(); Assert.Same(compactedTable, compactedTable2); } [Fact] public void Node_Table_Single_Returns_First_Item() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); var table = builder.ToImmutableAndFree(); Assert.Equal(1, table.Single()); } [Fact] public void Node_Table_Single_Returns_Second_Item_When_First_Is_Removed() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); var table = builder.ToImmutableAndFree(); AssertTableEntries(table, new[] { (1, EntryState.Added) }); // remove the first item and replace it in the table builder = table.ToBuilder(); builder.RemoveEntries(); builder.AddEntries(ImmutableArray.Create(2), EntryState.Added); table = builder.ToImmutableAndFree(); AssertTableEntries(table, new[] { (1, EntryState.Removed), (2, EntryState.Added) }); Assert.Equal(2, table.Single()); } [Fact] public void Node_Builder_Handles_Modification_When_Both_Tables_Have_Empty_Entries() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1, 2), EntryState.Added); builder.AddEntries(ImmutableArray<int>.Empty, EntryState.Added); builder.AddEntries(ImmutableArray.Create(3, 4), EntryState.Added); var previousTable = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added)); AssertTableEntries(previousTable, expected); builder = previousTable.ToBuilder(); Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 2), EqualityComparer<int>.Default)); // ((3, EntryState.Modified), (2, EntryState.Cached)) Assert.True(builder.TryModifyEntries(ImmutableArray<int>.Empty, EqualityComparer<int>.Default)); // nothing Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 5), EqualityComparer<int>.Default)); // ((3, EntryState.Cached), (5, EntryState.Modified)) var newTable = builder.ToImmutableAndFree(); expected = ImmutableArray.Create((3, EntryState.Modified), (2, EntryState.Cached), (3, EntryState.Cached), (5, EntryState.Modified)); AssertTableEntries(newTable, expected); } [Fact] public void Node_Table_Doesnt_Modify_Single_Item_Multiple_Times_When_Same() { var builder = NodeStateTable<int>.Empty.ToBuilder(); builder.AddEntries(ImmutableArray.Create(1), EntryState.Added); builder.AddEntries(ImmutableArray.Create(2), EntryState.Added); builder.AddEntries(ImmutableArray.Create(3), EntryState.Added); builder.AddEntries(ImmutableArray.Create(4), EntryState.Added); var previousTable = builder.ToImmutableAndFree(); var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added)); AssertTableEntries(previousTable, expected); builder = previousTable.ToBuilder(); Assert.True(builder.TryModifyEntry(1, EqualityComparer<int>.Default)); // ((1, EntryState.Cached)) Assert.True(builder.TryModifyEntry(2, EqualityComparer<int>.Default)); // ((2, EntryState.Cached)) Assert.True(builder.TryModifyEntry(5, EqualityComparer<int>.Default)); // ((5, EntryState.Modified)) Assert.True(builder.TryModifyEntry(4, EqualityComparer<int>.Default)); // ((4, EntryState.Cached)) var newTable = builder.ToImmutableAndFree(); expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (5, EntryState.Modified), (4, EntryState.Cached)); AssertTableEntries(newTable, expected); } [Fact] public void Driver_Table_Calls_Into_Node_With_Self() { DriverStateTable.Builder? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = b; return s; }); DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(builder, passedIn); } [Fact] public void Driver_Table_Calls_Into_Node_With_EmptyState_FirstTime() { NodeStateTable<int>? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = s; return s; }); DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(NodeStateTable<int>.Empty, passedIn); } [Fact] public void Driver_Table_Calls_Into_Node_With_PreviousTable() { var nodeBuilder = NodeStateTable<int>.Empty.ToBuilder(); nodeBuilder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Cached); var newTable = nodeBuilder.ToImmutableAndFree(); NodeStateTable<int>? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = s; return newTable; }); // empty first time DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(NodeStateTable<int>.Empty, passedIn); // gives the returned table the second time around DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable()); builder2.GetLatestStateTableForNode(callbackNode); Assert.NotNull(passedIn); AssertTableEntries(passedIn!, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached) }); } [Fact] public void Driver_Table_Compacts_State_Tables_When_Made_Immutable() { var nodeBuilder = NodeStateTable<int>.Empty.ToBuilder(); nodeBuilder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added); nodeBuilder.AddEntries(ImmutableArray.Create(4), EntryState.Removed); nodeBuilder.AddEntries(ImmutableArray.Create(5, 6), EntryState.Modified); var newTable = nodeBuilder.ToImmutableAndFree(); NodeStateTable<int>? passedIn = null; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { passedIn = s; return newTable; }); // empty first time DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); Assert.Same(NodeStateTable<int>.Empty, passedIn); // gives the returned table the second time around DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable()); builder2.GetLatestStateTableForNode(callbackNode); // table returned from the first instance was compacted by the builder Assert.NotNull(passedIn); AssertTableEntries(passedIn!, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (5, EntryState.Cached), (6, EntryState.Cached) }); } [Fact] public void Driver_Table_Builder_Doesnt_Build_Twice() { int callCount = 0; CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) => { callCount++; return s; }); // multiple gets will only call it once DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty); builder.GetLatestStateTableForNode(callbackNode); builder.GetLatestStateTableForNode(callbackNode); builder.GetLatestStateTableForNode(callbackNode); Assert.Equal(1, callCount); // second time around we'll call it once, but no more DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable()); builder2.GetLatestStateTableForNode(callbackNode); builder2.GetLatestStateTableForNode(callbackNode); builder2.GetLatestStateTableForNode(callbackNode); Assert.Equal(2, callCount); } [Fact] public void Batch_Node_Is_Cached_If_All_Inputs_Are_Cached() { var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, 3)); BatchNode<int> batchNode = new BatchNode<int>(inputNode); // first time through will always be added (because it's not been run before) DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty); _ = dstBuilder.GetLatestStateTableForNode(batchNode); // second time through should show as cached dstBuilder = GetBuilder(dstBuilder.ToImmutable()); var table = dstBuilder.GetLatestStateTableForNode(batchNode); AssertTableEntries(table, new[] { (ImmutableArray.Create(1, 2, 3), EntryState.Cached) }); } [Fact] public void Batch_Node_Is_Not_Cached_When_Inputs_Are_Changed() { int third = 3; var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, third++)); BatchNode<int> batchNode = new BatchNode<int>(inputNode); // first time through will always be added (because it's not been run before) DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty); _ = dstBuilder.GetLatestStateTableForNode(batchNode); // second time through should show as modified dstBuilder = GetBuilder(dstBuilder.ToImmutable()); var table = dstBuilder.GetLatestStateTableForNode(batchNode); AssertTableEntries(table, new[] { (ImmutableArray.Create(1, 2, 4), EntryState.Modified) }); } [Fact] public void User_Comparer_Is_Not_Used_To_Determine_Inputs() { var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, 3)) .WithComparer(new LambdaComparer<int>((a, b) => false)); // first time through will always be added (because it's not been run before) DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty); _ = dstBuilder.GetLatestStateTableForNode(inputNode); // second time through should show as cached, even though we supplied a comparer (comparer should only used to turn modified => cached) dstBuilder = GetBuilder(dstBuilder.ToImmutable()); var table = dstBuilder.GetLatestStateTableForNode(inputNode); AssertTableEntries(table, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached) }); } private void AssertTableEntries<T>(NodeStateTable<T> table, IList<(T item, EntryState state)> expected) { int index = 0; foreach (var entry in table) { Assert.Equal(expected[index].item, entry.item); Assert.Equal(expected[index].state, entry.state); index++; } } private void AssertTableEntries<T>(NodeStateTable<ImmutableArray<T>> table, IList<(ImmutableArray<T> item, EntryState state)> expected) { int index = 0; foreach (var entry in table) { AssertEx.Equal(expected[index].item, entry.item); Assert.Equal(expected[index].state, entry.state); index++; } } private DriverStateTable.Builder GetBuilder(DriverStateTable previous) { var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10); var c = CSharpCompilation.Create("empty"); var state = new GeneratorDriverState(options, CompilerAnalyzerConfigOptionsProvider.Empty, ImmutableArray<ISourceGenerator>.Empty, ImmutableArray<IIncrementalGenerator>.Empty, ImmutableArray<AdditionalText>.Empty, ImmutableArray<GeneratorState>.Empty, previous, enableIncremental: true, disabledOutputs: IncrementalGeneratorOutputKind.None); return new DriverStateTable.Builder(c, state, ImmutableArray<ISyntaxInputNode>.Empty); } private class CallbackNode<T> : IIncrementalGeneratorNode<T> { private readonly Func<DriverStateTable.Builder, NodeStateTable<T>, NodeStateTable<T>> _callback; public CallbackNode(Func<DriverStateTable.Builder, NodeStateTable<T>, NodeStateTable<T>> callback) { _callback = callback; } public NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken) { return _callback(graphState, previousTable); } public IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer) => this; public void RegisterOutput(IIncrementalGeneratorOutputNode output) { } } } }
1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Compilers/Core/Portable/SourceGeneration/Nodes/BatchNode.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.Threading; namespace Microsoft.CodeAnalysis { internal sealed class BatchNode<TInput> : IIncrementalGeneratorNode<ImmutableArray<TInput>> { private readonly IIncrementalGeneratorNode<TInput> _sourceNode; private readonly IEqualityComparer<ImmutableArray<TInput>> _comparer; public BatchNode(IIncrementalGeneratorNode<TInput> sourceNode, IEqualityComparer<ImmutableArray<TInput>>? comparer = null) { _sourceNode = sourceNode; _comparer = comparer ?? EqualityComparer<ImmutableArray<TInput>>.Default; } public IIncrementalGeneratorNode<ImmutableArray<TInput>> WithComparer(IEqualityComparer<ImmutableArray<TInput>> comparer) => new BatchNode<TInput>(_sourceNode, comparer); public NodeStateTable<ImmutableArray<TInput>> UpdateStateTable(DriverStateTable.Builder builder, NodeStateTable<ImmutableArray<TInput>> previousTable, CancellationToken cancellationToken) { // grab the source inputs var sourceTable = builder.GetLatestStateTableForNode(_sourceNode); // Semantics of a batch transform: // Batches will always exist (a batch of the empty table is still []) // There is only ever one input, the batch of the upstream table // - Output is cached when upstream is all cached // - Added when the previous table was empty // - Modified otherwise var source = ImmutableArray.Create(sourceTable.Batch()); // update the table var newTable = previousTable.ToBuilder(); if (!newTable.TryModifyEntries(source, _comparer)) { newTable.AddEntries(source, EntryState.Added); } return newTable.ToImmutableAndFree(); } public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _sourceNode.RegisterOutput(output); } }
// Licensed to the .NET Foundation under one or more 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.Threading; namespace Microsoft.CodeAnalysis { internal sealed class BatchNode<TInput> : IIncrementalGeneratorNode<ImmutableArray<TInput>> { private readonly IIncrementalGeneratorNode<TInput> _sourceNode; private readonly IEqualityComparer<ImmutableArray<TInput>> _comparer; public BatchNode(IIncrementalGeneratorNode<TInput> sourceNode, IEqualityComparer<ImmutableArray<TInput>>? comparer = null) { _sourceNode = sourceNode; _comparer = comparer ?? EqualityComparer<ImmutableArray<TInput>>.Default; } public IIncrementalGeneratorNode<ImmutableArray<TInput>> WithComparer(IEqualityComparer<ImmutableArray<TInput>> comparer) => new BatchNode<TInput>(_sourceNode, comparer); public NodeStateTable<ImmutableArray<TInput>> UpdateStateTable(DriverStateTable.Builder builder, NodeStateTable<ImmutableArray<TInput>> previousTable, CancellationToken cancellationToken) { // grab the source inputs var sourceTable = builder.GetLatestStateTableForNode(_sourceNode); // Semantics of a batch transform: // Batches will always exist (a batch of the empty table is still []) // There is only ever one input, the batch of the upstream table // - Output is cached when upstream is all cached // - Added when the previous table was empty // - Modified otherwise var source = sourceTable.Batch(); // update the table var newTable = previousTable.ToBuilder(); if (!sourceTable.IsCached || !newTable.TryUseCachedEntries()) { if (!newTable.TryModifyEntry(source, _comparer)) { newTable.AddEntry(source, EntryState.Added); } } return newTable.ToImmutableAndFree(); } public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _sourceNode.RegisterOutput(output); } }
1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Compilers/Core/Portable/SourceGeneration/Nodes/InputNode.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Input nodes are the 'root' nodes in the graph, and get their values from the inputs of the driver state table /// </summary> /// <typeparam name="T">The type of the input</typeparam> internal sealed class InputNode<T> : IIncrementalGeneratorNode<T> { private readonly Func<DriverStateTable.Builder, ImmutableArray<T>> _getInput; private readonly Action<IIncrementalGeneratorOutputNode> _registerOutput; private readonly IEqualityComparer<T> _comparer; public InputNode(Func<DriverStateTable.Builder, ImmutableArray<T>> getInput) : this(getInput, registerOutput: null, comparer: null) { } private InputNode(Func<DriverStateTable.Builder, ImmutableArray<T>> getInput, Action<IIncrementalGeneratorOutputNode>? registerOutput, IEqualityComparer<T>? comparer = null) { _getInput = getInput; _comparer = comparer ?? EqualityComparer<T>.Default; _registerOutput = registerOutput ?? (o => throw ExceptionUtilities.Unreachable); } public NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken) { var inputItems = _getInput(graphState); // create a mutable hashset of the new items we can check against HashSet<T> itemsSet = new HashSet<T>(_comparer); foreach (var item in inputItems) { var added = itemsSet.Add(item); Debug.Assert(added); } var builder = previousTable.ToBuilder(); // for each item in the previous table, check if its still in the new items int itemIndex = 0; foreach ((var oldItem, _) in previousTable) { if (itemsSet.Remove(oldItem)) { // we're iterating the table, so know that it has entries var usedCache = builder.TryUseCachedEntries(); Debug.Assert(usedCache); } else if (inputItems.Length == previousTable.Count) { // When the number of items matches the previous iteration, we use a heuristic to mark the input as modified // This allows us to correctly 'replace' items even when they aren't actually the same. In the case that the // item really isn't modified, but a new item, we still function correctly as we mostly treat them the same, // but will perform an extra comparison that is omitted in the pure 'added' case. var modified = builder.TryModifyEntry(inputItems[itemIndex], _comparer); Debug.Assert(modified); itemsSet.Remove(inputItems[itemIndex]); } else { builder.RemoveEntries(); } itemIndex++; } // any remaining new items are added foreach (var newItem in itemsSet) { builder.AddEntry(newItem, EntryState.Added); } return builder.ToImmutableAndFree(); } public IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer) => new InputNode<T>(_getInput, _registerOutput, comparer); public InputNode<T> WithRegisterOutput(Action<IIncrementalGeneratorOutputNode> registerOutput) => new InputNode<T>(_getInput, registerOutput, _comparer); public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _registerOutput(output); } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Input nodes are the 'root' nodes in the graph, and get their values from the inputs of the driver state table /// </summary> /// <typeparam name="T">The type of the input</typeparam> internal sealed class InputNode<T> : IIncrementalGeneratorNode<T> { private readonly Func<DriverStateTable.Builder, ImmutableArray<T>> _getInput; private readonly Action<IIncrementalGeneratorOutputNode> _registerOutput; private readonly IEqualityComparer<T> _comparer; public InputNode(Func<DriverStateTable.Builder, ImmutableArray<T>> getInput) : this(getInput, registerOutput: null, comparer: null) { } private InputNode(Func<DriverStateTable.Builder, ImmutableArray<T>> getInput, Action<IIncrementalGeneratorOutputNode>? registerOutput, IEqualityComparer<T>? comparer = null) { _getInput = getInput; _comparer = comparer ?? EqualityComparer<T>.Default; _registerOutput = registerOutput ?? (o => throw ExceptionUtilities.Unreachable); } public NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken) { var inputItems = _getInput(graphState); // create a mutable hashset of the new items we can check against HashSet<T> itemsSet = new HashSet<T>(); foreach (var item in inputItems) { var added = itemsSet.Add(item); Debug.Assert(added); } var builder = previousTable.ToBuilder(); // for each item in the previous table, check if its still in the new items int itemIndex = 0; foreach ((var oldItem, _) in previousTable) { if (itemsSet.Remove(oldItem)) { // we're iterating the table, so know that it has entries var usedCache = builder.TryUseCachedEntries(); Debug.Assert(usedCache); } else if (inputItems.Length == previousTable.Count) { // When the number of items matches the previous iteration, we use a heuristic to mark the input as modified // This allows us to correctly 'replace' items even when they aren't actually the same. In the case that the // item really isn't modified, but a new item, we still function correctly as we mostly treat them the same, // but will perform an extra comparison that is omitted in the pure 'added' case. var modified = builder.TryModifyEntry(inputItems[itemIndex], _comparer); Debug.Assert(modified); itemsSet.Remove(inputItems[itemIndex]); } else { builder.RemoveEntries(); } itemIndex++; } // any remaining new items are added foreach (var newItem in itemsSet) { builder.AddEntry(newItem, EntryState.Added); } return builder.ToImmutableAndFree(); } public IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer) => new InputNode<T>(_getInput, _registerOutput, comparer); public InputNode<T> WithRegisterOutput(Action<IIncrementalGeneratorOutputNode> registerOutput) => new InputNode<T>(_getInput, registerOutput, _comparer); public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _registerOutput(output); } }
1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/EditorFeatures/Core/Implementation/Interactive/Completion/InteractiveCommandCompletionService.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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Interactive; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Completion { [ExportLanguageServiceFactory(typeof(CompletionService), InteractiveLanguageNames.InteractiveCommand), Shared] internal class InteractiveCommandCompletionServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InteractiveCommandCompletionServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => new InteractiveCommandCompletionService(languageServices.WorkspaceServices.Workspace); } internal class InteractiveCommandCompletionService : CompletionServiceWithProviders { public InteractiveCommandCompletionService(Workspace workspace) : base(workspace) { } public override string Language { get { return InteractiveLanguageNames.InteractiveCommand; } } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Interactive; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Completion { [ExportLanguageServiceFactory(typeof(CompletionService), InteractiveLanguageNames.InteractiveCommand), Shared] internal class InteractiveCommandCompletionServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InteractiveCommandCompletionServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => new InteractiveCommandCompletionService(languageServices.WorkspaceServices.Workspace); } internal class InteractiveCommandCompletionService : CompletionServiceWithProviders { public InteractiveCommandCompletionService(Workspace workspace) : base(workspace) { } public override string Language { get { return InteractiveLanguageNames.InteractiveCommand; } } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/EditorFeatures/CSharpTest/GenerateDefaultConstructors/GenerateDefaultConstructorsTests.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.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.GenerateDefaultConstructors; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateDefaultConstructors { public class GenerateDefaultConstructorsTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new GenerateDefaultConstructorsCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestProtectedBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { protected B(int x) { } }", @"class C : B { protected C(int x) : base(x) { } } class B { protected B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestPublicBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } class B { public B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestInternalBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } }", @"class C : B { internal C(int x) : base(x) { } } class B { internal B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestPrivateBase() { await TestMissingInRegularAndScriptAsync( @"class C : [||]B { } class B { private B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRefOutParams() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(ref int x, out string s, params bool[] b) { } }", @"class C : B { internal C(ref int x, out string s, params bool[] b) : base(ref x, out s, b) { } } class B { internal B(ref int x, out string s, params bool[] b) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFix1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFix2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { protected C(string x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRefactoring1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) : base(x) { } protected C(string x) : base(x) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C(bool x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) { } protected C(string x) : base(x) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll_WithTuples() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C((bool, bool) x) { } } class B { internal B((int, int) x) { } protected B((string, string) x) { } public B((bool, bool) x) { } }", @"class C : B { public C((bool, bool) x) { } protected C((string, string) x) : base(x) { } internal C((int, int) x) : base(x) { } } class B { internal B((int, int) x) { } protected B((string, string) x) { } public B((bool, bool) x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestMissing1() { await TestMissingInRegularAndScriptAsync( @"class C : [||]B { public C(int x) { } } class B { internal B(int x) { } }"); } [WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestDefaultConstructorGeneration_1() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C(int y) { } } class B { internal B(int x) { } }", @"class C : B { public C(int y) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } }"); } [WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestDefaultConstructorGeneration_2() { await TestInRegularAndScriptAsync( @"class C : [||]B { private C(int y) { } } class B { internal B(int x) { } }", @"class C : B { internal C(int x) : base(x) { } private C(int y) { } } class B { internal B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixCount1() { await TestActionCountAsync( @"class C : [||]B { } class B { public B(int x) { } }", count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] [WorkItem(544070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544070")] public async Task TestException1() { await TestInRegularAndScriptAsync( @"using System; class Program : Excep[||]tion { }", @"using System; using System.Runtime.Serialization; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(SerializationInfo info, StreamingContext context) : base(info, context) { } }", index: 4); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException2() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program() { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(SerializationInfo info, StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", index: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException3() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException4() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors), CompilerTrait(CompilerFeature.Tuples)] public async Task Tuple() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B((int, string) x) { } }", @"class C : B { public C((int, string) x) : base(x) { } } class B { public B((int, string) x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors), CompilerTrait(CompilerFeature.Tuples)] public async Task TupleWithNames() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B((int a, string b) x) { } }", @"class C : B { public C((int a, string b) x) : base(x) { } } class B { public B((int a, string b) x) { } }"); } [WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)] public async Task TestGenerateFromDerivedClass() { await TestInRegularAndScriptAsync( @"class Base { public Base(string value) { } } class [||]Derived : Base { }", @"class Base { public Base(string value) { } } class Derived : Base { public Derived(string value) : base(value) { } }"); } [WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)] public async Task TestGenerateFromDerivedClass2() { await TestInRegularAndScriptAsync( @"class Base { public Base(int a, string value = null) { } } class [||]Derived : Base { }", @"class Base { public Base(int a, string value = null) { } } class Derived : Base { public Derived(int a, string value = null) : base(a, value) { } }"); } [WorkItem(19953, "https://github.com/dotnet/roslyn/issues/19953")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestNotOnEnum() { await TestMissingInRegularAndScriptAsync( @"enum [||]E { }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { protected B(int x) { } }", @"abstract class C : B { protected C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { protected B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(48318, "https://github.com/dotnet/roslyn/issues/48318")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructorCursorAtTypeOpening() { await TestInRegularAndScriptAsync( @"class C : B { [||] } abstract class B { protected B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(48318, "https://github.com/dotnet/roslyn/issues/48318")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructorCursorBetweenTypeMembers() { await TestInRegularAndScriptAsync( @"class C : B { int X; [||] int Y; } abstract class B { protected B(int x) { } }", @"class C : B { int X; int Y; public C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(35208, "https://github.com/dotnet/roslyn/issues/35208")] [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorInAbstractClassFromPublicConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { public B(int x) { } }", @"abstract class C : B { protected C(int x) : base(x) { } } abstract class B { public B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromPublicConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { public B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { public B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromInternalConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { internal B(int x) { } }", @"abstract class C : B { internal C(int x) : base(x) { } } abstract class B { internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromInternalConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { internal B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedInternalConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { protected internal B(int x) { } }", @"abstract class C : B { protected internal C(int x) : base(x) { } } abstract class B { protected internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedInternalConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { protected internal B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { protected internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromPrivateProtectedConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { private protected B(int x) { } }", @"abstract class C : B { private protected C(int x) : base(x) { } } abstract class B { private protected B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromPrivateProtectedConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { private protected internal B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { private protected internal B(int x) { } }"); } [WorkItem(40586, "https://github.com/dotnet/roslyn/issues/40586")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGeneratePublicConstructorInSealedClassForProtectedBase() { await TestInRegularAndScriptAsync( @"class Base { protected Base() { } } sealed class Program : [||]Base { }", @"class Base { protected Base() { } } sealed class Program : Base { public Program() { } }"); } [WorkItem(40586, "https://github.com/dotnet/roslyn/issues/40586")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateInternalConstructorInSealedClassForProtectedOrInternalBase() { await TestInRegularAndScriptAsync( @"class Base { protected internal Base() { } } sealed class Program : [||]Base { }", @"class Base { protected internal Base() { } } sealed class Program : Base { internal Program() { } }"); } [WorkItem(40586, "https://github.com/dotnet/roslyn/issues/40586")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateInternalConstructorInSealedClassForProtectedAndInternalBase() { await TestInRegularAndScriptAsync( @"class Base { private protected Base() { } } sealed class Program : [||]Base { }", @"class Base { private protected Base() { } } sealed class Program : Base { internal Program() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRecord() { await TestInRegularAndScriptAsync( @"record C : [||]B { } record B { public B(int x) { } }", @"record C : B { public C(int x) : base(x) { } } record B { public B(int x) { } }", index: 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.GenerateDefaultConstructors; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateDefaultConstructors { public class GenerateDefaultConstructorsTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new GenerateDefaultConstructorsCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestProtectedBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { protected B(int x) { } }", @"class C : B { protected C(int x) : base(x) { } } class B { protected B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestPublicBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } class B { public B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestInternalBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } }", @"class C : B { internal C(int x) : base(x) { } } class B { internal B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestPrivateBase() { await TestMissingInRegularAndScriptAsync( @"class C : [||]B { } class B { private B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRefOutParams() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(ref int x, out string s, params bool[] b) { } }", @"class C : B { internal C(ref int x, out string s, params bool[] b) : base(ref x, out s, b) { } } class B { internal B(ref int x, out string s, params bool[] b) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFix1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFix2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { protected C(string x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRefactoring1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) : base(x) { } protected C(string x) : base(x) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C(bool x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) { } protected C(string x) : base(x) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll_WithTuples() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C((bool, bool) x) { } } class B { internal B((int, int) x) { } protected B((string, string) x) { } public B((bool, bool) x) { } }", @"class C : B { public C((bool, bool) x) { } protected C((string, string) x) : base(x) { } internal C((int, int) x) : base(x) { } } class B { internal B((int, int) x) { } protected B((string, string) x) { } public B((bool, bool) x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestMissing1() { await TestMissingInRegularAndScriptAsync( @"class C : [||]B { public C(int x) { } } class B { internal B(int x) { } }"); } [WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestDefaultConstructorGeneration_1() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C(int y) { } } class B { internal B(int x) { } }", @"class C : B { public C(int y) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } }"); } [WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestDefaultConstructorGeneration_2() { await TestInRegularAndScriptAsync( @"class C : [||]B { private C(int y) { } } class B { internal B(int x) { } }", @"class C : B { internal C(int x) : base(x) { } private C(int y) { } } class B { internal B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixCount1() { await TestActionCountAsync( @"class C : [||]B { } class B { public B(int x) { } }", count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] [WorkItem(544070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544070")] public async Task TestException1() { await TestInRegularAndScriptAsync( @"using System; class Program : Excep[||]tion { }", @"using System; using System.Runtime.Serialization; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(SerializationInfo info, StreamingContext context) : base(info, context) { } }", index: 4); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException2() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program() { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(SerializationInfo info, StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", index: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException3() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException4() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors), CompilerTrait(CompilerFeature.Tuples)] public async Task Tuple() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B((int, string) x) { } }", @"class C : B { public C((int, string) x) : base(x) { } } class B { public B((int, string) x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors), CompilerTrait(CompilerFeature.Tuples)] public async Task TupleWithNames() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B((int a, string b) x) { } }", @"class C : B { public C((int a, string b) x) : base(x) { } } class B { public B((int a, string b) x) { } }"); } [WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)] public async Task TestGenerateFromDerivedClass() { await TestInRegularAndScriptAsync( @"class Base { public Base(string value) { } } class [||]Derived : Base { }", @"class Base { public Base(string value) { } } class Derived : Base { public Derived(string value) : base(value) { } }"); } [WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)] public async Task TestGenerateFromDerivedClass2() { await TestInRegularAndScriptAsync( @"class Base { public Base(int a, string value = null) { } } class [||]Derived : Base { }", @"class Base { public Base(int a, string value = null) { } } class Derived : Base { public Derived(int a, string value = null) : base(a, value) { } }"); } [WorkItem(19953, "https://github.com/dotnet/roslyn/issues/19953")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestNotOnEnum() { await TestMissingInRegularAndScriptAsync( @"enum [||]E { }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { protected B(int x) { } }", @"abstract class C : B { protected C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { protected B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(48318, "https://github.com/dotnet/roslyn/issues/48318")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructorCursorAtTypeOpening() { await TestInRegularAndScriptAsync( @"class C : B { [||] } abstract class B { protected B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(48318, "https://github.com/dotnet/roslyn/issues/48318")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructorCursorBetweenTypeMembers() { await TestInRegularAndScriptAsync( @"class C : B { int X; [||] int Y; } abstract class B { protected B(int x) { } }", @"class C : B { int X; int Y; public C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(35208, "https://github.com/dotnet/roslyn/issues/35208")] [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorInAbstractClassFromPublicConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { public B(int x) { } }", @"abstract class C : B { protected C(int x) : base(x) { } } abstract class B { public B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromPublicConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { public B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { public B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromInternalConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { internal B(int x) { } }", @"abstract class C : B { internal C(int x) : base(x) { } } abstract class B { internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromInternalConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { internal B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedInternalConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { protected internal B(int x) { } }", @"abstract class C : B { protected internal C(int x) : base(x) { } } abstract class B { protected internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedInternalConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { protected internal B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { protected internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromPrivateProtectedConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { private protected B(int x) { } }", @"abstract class C : B { private protected C(int x) : base(x) { } } abstract class B { private protected B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromPrivateProtectedConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { private protected internal B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { private protected internal B(int x) { } }"); } [WorkItem(40586, "https://github.com/dotnet/roslyn/issues/40586")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGeneratePublicConstructorInSealedClassForProtectedBase() { await TestInRegularAndScriptAsync( @"class Base { protected Base() { } } sealed class Program : [||]Base { }", @"class Base { protected Base() { } } sealed class Program : Base { public Program() { } }"); } [WorkItem(40586, "https://github.com/dotnet/roslyn/issues/40586")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateInternalConstructorInSealedClassForProtectedOrInternalBase() { await TestInRegularAndScriptAsync( @"class Base { protected internal Base() { } } sealed class Program : [||]Base { }", @"class Base { protected internal Base() { } } sealed class Program : Base { internal Program() { } }"); } [WorkItem(40586, "https://github.com/dotnet/roslyn/issues/40586")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateInternalConstructorInSealedClassForProtectedAndInternalBase() { await TestInRegularAndScriptAsync( @"class Base { private protected Base() { } } sealed class Program : [||]Base { }", @"class Base { private protected Base() { } } sealed class Program : Base { internal Program() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRecord() { await TestInRegularAndScriptAsync( @"record C : [||]B { } record B { public B(int x) { } }", @"record C : B { public C(int x) : base(x) { } } record B { public B(int x) { } }", index: 1); } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Features/CSharp/Portable/Diagnostics/CSharpAnalyzerDriverService.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 System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Diagnostics { [ExportLanguageService(typeof(IAnalyzerDriverService), LanguageNames.CSharp), Shared] internal sealed class CSharpAnalyzerDriverService : IAnalyzerDriverService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpAnalyzerDriverService() { } public void ComputeDeclarationsInSpan( SemanticModel model, TextSpan span, bool getSymbol, ArrayBuilder<DeclarationInfo> builder, CancellationToken cancellationToken) { CSharpDeclarationComputer.ComputeDeclarationsInSpan(model, span, getSymbol, builder, 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; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Diagnostics { [ExportLanguageService(typeof(IAnalyzerDriverService), LanguageNames.CSharp), Shared] internal sealed class CSharpAnalyzerDriverService : IAnalyzerDriverService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpAnalyzerDriverService() { } public void ComputeDeclarationsInSpan( SemanticModel model, TextSpan span, bool getSymbol, ArrayBuilder<DeclarationInfo> builder, CancellationToken cancellationToken) { CSharpDeclarationComputer.ComputeDeclarationsInSpan(model, span, getSymbol, builder, cancellationToken); } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/VisualStudio/Core/Def/Implementation/Progression/GraphQueries/IsUsedByGraphQuery.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.Linq; 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.CodeSchema; using Microsoft.VisualStudio.GraphModel.Schemas; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class IsUsedByGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.GraphQuery_IsUsedBy, 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); var references = await SymbolFinder.FindReferencesAsync(symbol, solution, cancellationToken).ConfigureAwait(false); foreach (var reference in references) { var referencedSymbol = reference.Definition; var projectId = graphBuilder.GetContextProject(node, cancellationToken).Id; var allLocations = referencedSymbol.Locations.Concat(reference.Locations.Select(r => r.Location)) .Where(l => l != null && l.IsInSource); foreach (var location in allLocations) { var locationNode = GetLocationNode(location, context, projectId, cancellationToken); graphBuilder.AddLink(node, CodeLinkCategories.SourceReferences, locationNode, cancellationToken); } } } return graphBuilder; } } internal GraphNode GetLocationNode(Location location, IGraphContext context, ProjectId projectId, CancellationToken cancellationToken) { var span = location.GetLineSpan(); var lineText = location.SourceTree.GetText(cancellationToken).Lines[span.StartLinePosition.Line].ToString(); var filePath = location.SourceTree.FilePath; var sourceLocation = new SourceLocation(filePath, new Position(span.StartLinePosition.Line, span.StartLinePosition.Character), new Position(span.EndLinePosition.Line, span.EndLinePosition.Character)); var label = string.Format("{0} ({1}, {2}): {3}", System.IO.Path.GetFileName(filePath), span.StartLinePosition.Line + 1, span.StartLinePosition.Character + 1, lineText.TrimStart()); var locationNode = context.Graph.Nodes.GetOrCreate(sourceLocation.CreateGraphNodeId(), label, CodeNodeCategories.SourceLocation); locationNode[CodeNodeProperties.SourceLocation] = sourceLocation; locationNode[RoslynGraphProperties.ContextProjectId] = projectId; locationNode[DgmlNodeProperties.Icon] = IconHelper.GetIconName("Reference", Accessibility.NotApplicable); return locationNode; } } }
// Licensed to the .NET Foundation under one or more 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.Linq; 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.CodeSchema; using Microsoft.VisualStudio.GraphModel.Schemas; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class IsUsedByGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.GraphQuery_IsUsedBy, 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); var references = await SymbolFinder.FindReferencesAsync(symbol, solution, cancellationToken).ConfigureAwait(false); foreach (var reference in references) { var referencedSymbol = reference.Definition; var projectId = graphBuilder.GetContextProject(node, cancellationToken).Id; var allLocations = referencedSymbol.Locations.Concat(reference.Locations.Select(r => r.Location)) .Where(l => l != null && l.IsInSource); foreach (var location in allLocations) { var locationNode = GetLocationNode(location, context, projectId, cancellationToken); graphBuilder.AddLink(node, CodeLinkCategories.SourceReferences, locationNode, cancellationToken); } } } return graphBuilder; } } internal GraphNode GetLocationNode(Location location, IGraphContext context, ProjectId projectId, CancellationToken cancellationToken) { var span = location.GetLineSpan(); var lineText = location.SourceTree.GetText(cancellationToken).Lines[span.StartLinePosition.Line].ToString(); var filePath = location.SourceTree.FilePath; var sourceLocation = new SourceLocation(filePath, new Position(span.StartLinePosition.Line, span.StartLinePosition.Character), new Position(span.EndLinePosition.Line, span.EndLinePosition.Character)); var label = string.Format("{0} ({1}, {2}): {3}", System.IO.Path.GetFileName(filePath), span.StartLinePosition.Line + 1, span.StartLinePosition.Character + 1, lineText.TrimStart()); var locationNode = context.Graph.Nodes.GetOrCreate(sourceLocation.CreateGraphNodeId(), label, CodeNodeCategories.SourceLocation); locationNode[CodeNodeProperties.SourceLocation] = sourceLocation; locationNode[RoslynGraphProperties.ContextProjectId] = projectId; locationNode[DgmlNodeProperties.Icon] = IconHelper.GetIconName("Reference", Accessibility.NotApplicable); return locationNode; } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/VisualStudio/Core/Def/Implementation/TableDataSource/MiscTodoListTableControlEventProcessorProvider.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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { [Export(typeof(ITableControlEventProcessorProvider))] [DataSourceType(StandardTableDataSources.CommentTableDataSource)] [DataSource(MiscellaneousTodoListTableWorkspaceEventListener.IdentifierString)] [Name(Name)] [Order(Before = "default")] internal sealed class MiscTodoListTableControlEventProcessorProvider : AbstractTableControlEventProcessorProvider<TodoTableItem> { internal const string Name = "Misc C#/VB Todo List Table Event Processor"; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MiscTodoListTableControlEventProcessorProvider() { } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { [Export(typeof(ITableControlEventProcessorProvider))] [DataSourceType(StandardTableDataSources.CommentTableDataSource)] [DataSource(MiscellaneousTodoListTableWorkspaceEventListener.IdentifierString)] [Name(Name)] [Order(Before = "default")] internal sealed class MiscTodoListTableControlEventProcessorProvider : AbstractTableControlEventProcessorProvider<TodoTableItem> { internal const string Name = "Misc C#/VB Todo List Table Event Processor"; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MiscTodoListTableControlEventProcessorProvider() { } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Compilers/CSharp/Portable/Symbols/Source/CrefTypeParameterSymbol.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.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Type parameters in documentation comments are complicated since they sort of act as declarations, /// rather than references. Consider the following example: /// /// <![CDATA[ /// /// <summary>See <see cref="B{U}.M(U)" />.</summary> /// class B<T> { void M(T t) { } } /// ]]> /// /// We make some key observations: /// 1) The type parameter name in the cref is not tied to the type parameter name in the type declaration. /// 2) A relationship exists between the two occurrences of "U" in the cref: they both refer to (or define) /// the same symbol. /// /// In Roslyn, we've decided on the following representation: within the (entire) scope of a cref, the names /// of all type parameters "declared" in the cref are in scope and bind to the corresponding type parameters. /// This representation has one major advantage: as long as the appropriate binder (i.e. the one that knows /// about the implicitly-declared type parameters) is used, TypeSyntaxes within the cref can be bound by /// calling BindType. In addition to eliminating the necessity for custom binding code in the batch case, /// this reduces the problem of exposing such nodes in the SemanticModel to one of ensuring that the right /// enclosing binder is chosen. That is, new code will have to be written to handle CrefSyntaxes, but the /// existing code for TypeSyntaxes should just work! /// /// In the example above, this means that, between the cref quotation marks, the name "U" binds to an /// implicitly declared type parameter, whether it is in "B{U}", "M{U}", or "M{List{U[]}}". /// /// Of course, it's not all gravy. One thing we're giving up by using this representation is the ability to /// distinguish between "declared" type parameters with the same name. Consider the following example: /// /// <![CDATA[ /// <summary>See <see cref=""A{T, T}.M(T)""/>.</summary> /// class A<T, U> /// { /// void M(T t) { } /// void M(U u) { } /// } /// ]]> /// </summary> /// /// The native compiler interprets this in the same way as it would interpret A{T1, T2}.M(T2) and unambiguously /// (i.e. without a warning) binds to A{T, U}.M(U). Since Roslyn does not distinguish between the T's, Roslyn /// reports an ambiguity warning and picks the first method. Furthermore, renaming one 'T' will rename all of /// them. /// /// This class represents such an implicitly declared type parameter. The declaring syntax is expected to be /// an IdentifierNameSyntax in the type argument list of a QualifiedNameSyntax. internal sealed class CrefTypeParameterSymbol : TypeParameterSymbol { private readonly string _name; private readonly int _ordinal; private readonly SyntaxReference _declaringSyntax; public CrefTypeParameterSymbol(string name, int ordinal, IdentifierNameSyntax declaringSyntax) { _name = name; _ordinal = ordinal; _declaringSyntax = declaringSyntax.GetReference(); } public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Cref; } } public override string Name { get { return _name; } } public override int Ordinal { get { return _ordinal; } } internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { if (ReferenceEquals(this, t2)) { return true; } if ((object)t2 == null) { return false; } CrefTypeParameterSymbol other = t2 as CrefTypeParameterSymbol; return (object)other != null && other._name == _name && other._ordinal == _ordinal && other._declaringSyntax.GetSyntax() == _declaringSyntax.GetSyntax(); } public override int GetHashCode() { return Hash.Combine(_name, _ordinal); } public override VarianceKind Variance { get { return VarianceKind.None; } } public override bool HasValueTypeConstraint { get { return false; } } public override bool IsValueTypeFromConstraintTypes { get { return false; } } public override bool HasReferenceTypeConstraint { get { return false; } } public override bool IsReferenceTypeFromConstraintTypes { get { return false; } } internal override bool? ReferenceTypeConstraintIsNullable { get { return false; } } public override bool HasNotNullConstraint => false; internal override bool? IsNotNullable => null; public override bool HasUnmanagedTypeConstraint { get { return false; } } public override bool HasConstructorConstraint { get { return false; } } public override Symbol ContainingSymbol { get { return null; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray.Create<Location>(_declaringSyntax.GetLocation()); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray.Create<SyntaxReference>(_declaringSyntax); } } internal override void EnsureAllConstraintsAreResolved() { } internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress) { return ImmutableArray<TypeWithAnnotations>.Empty; } internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress) { return ImmutableArray<NamedTypeSymbol>.Empty; } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress) { // Constraints are not checked in crefs, so this should never be examined. throw ExceptionUtilities.Unreachable; } internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress) { // Constraints are not checked in crefs, so this should never be examined. throw ExceptionUtilities.Unreachable; } public override bool IsImplicitlyDeclared { 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Type parameters in documentation comments are complicated since they sort of act as declarations, /// rather than references. Consider the following example: /// /// <![CDATA[ /// /// <summary>See <see cref="B{U}.M(U)" />.</summary> /// class B<T> { void M(T t) { } } /// ]]> /// /// We make some key observations: /// 1) The type parameter name in the cref is not tied to the type parameter name in the type declaration. /// 2) A relationship exists between the two occurrences of "U" in the cref: they both refer to (or define) /// the same symbol. /// /// In Roslyn, we've decided on the following representation: within the (entire) scope of a cref, the names /// of all type parameters "declared" in the cref are in scope and bind to the corresponding type parameters. /// This representation has one major advantage: as long as the appropriate binder (i.e. the one that knows /// about the implicitly-declared type parameters) is used, TypeSyntaxes within the cref can be bound by /// calling BindType. In addition to eliminating the necessity for custom binding code in the batch case, /// this reduces the problem of exposing such nodes in the SemanticModel to one of ensuring that the right /// enclosing binder is chosen. That is, new code will have to be written to handle CrefSyntaxes, but the /// existing code for TypeSyntaxes should just work! /// /// In the example above, this means that, between the cref quotation marks, the name "U" binds to an /// implicitly declared type parameter, whether it is in "B{U}", "M{U}", or "M{List{U[]}}". /// /// Of course, it's not all gravy. One thing we're giving up by using this representation is the ability to /// distinguish between "declared" type parameters with the same name. Consider the following example: /// /// <![CDATA[ /// <summary>See <see cref=""A{T, T}.M(T)""/>.</summary> /// class A<T, U> /// { /// void M(T t) { } /// void M(U u) { } /// } /// ]]> /// </summary> /// /// The native compiler interprets this in the same way as it would interpret A{T1, T2}.M(T2) and unambiguously /// (i.e. without a warning) binds to A{T, U}.M(U). Since Roslyn does not distinguish between the T's, Roslyn /// reports an ambiguity warning and picks the first method. Furthermore, renaming one 'T' will rename all of /// them. /// /// This class represents such an implicitly declared type parameter. The declaring syntax is expected to be /// an IdentifierNameSyntax in the type argument list of a QualifiedNameSyntax. internal sealed class CrefTypeParameterSymbol : TypeParameterSymbol { private readonly string _name; private readonly int _ordinal; private readonly SyntaxReference _declaringSyntax; public CrefTypeParameterSymbol(string name, int ordinal, IdentifierNameSyntax declaringSyntax) { _name = name; _ordinal = ordinal; _declaringSyntax = declaringSyntax.GetReference(); } public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Cref; } } public override string Name { get { return _name; } } public override int Ordinal { get { return _ordinal; } } internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { if (ReferenceEquals(this, t2)) { return true; } if ((object)t2 == null) { return false; } CrefTypeParameterSymbol other = t2 as CrefTypeParameterSymbol; return (object)other != null && other._name == _name && other._ordinal == _ordinal && other._declaringSyntax.GetSyntax() == _declaringSyntax.GetSyntax(); } public override int GetHashCode() { return Hash.Combine(_name, _ordinal); } public override VarianceKind Variance { get { return VarianceKind.None; } } public override bool HasValueTypeConstraint { get { return false; } } public override bool IsValueTypeFromConstraintTypes { get { return false; } } public override bool HasReferenceTypeConstraint { get { return false; } } public override bool IsReferenceTypeFromConstraintTypes { get { return false; } } internal override bool? ReferenceTypeConstraintIsNullable { get { return false; } } public override bool HasNotNullConstraint => false; internal override bool? IsNotNullable => null; public override bool HasUnmanagedTypeConstraint { get { return false; } } public override bool HasConstructorConstraint { get { return false; } } public override Symbol ContainingSymbol { get { return null; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray.Create<Location>(_declaringSyntax.GetLocation()); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray.Create<SyntaxReference>(_declaringSyntax); } } internal override void EnsureAllConstraintsAreResolved() { } internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress) { return ImmutableArray<TypeWithAnnotations>.Empty; } internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress) { return ImmutableArray<NamedTypeSymbol>.Empty; } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress) { // Constraints are not checked in crefs, so this should never be examined. throw ExceptionUtilities.Unreachable; } internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress) { // Constraints are not checked in crefs, so this should never be examined. throw ExceptionUtilities.Unreachable; } public override bool IsImplicitlyDeclared { get { return false; } } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/VisualStudio/Core/Def/Implementation/Remote/VisualStudioRemoteHostClientProvider.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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.ServiceBroker; using Roslyn.Utilities; using VSThreading = Microsoft.VisualStudio.Threading; namespace Microsoft.VisualStudio.LanguageServices.Remote { internal sealed class VisualStudioRemoteHostClientProvider : IRemoteHostClientProvider { [ExportWorkspaceServiceFactory(typeof(IRemoteHostClientProvider), WorkspaceKind.Host), Shared] internal sealed class Factory : IWorkspaceServiceFactory { private readonly IAsyncServiceProvider _vsServiceProvider; private readonly AsynchronousOperationListenerProvider _listenerProvider; private readonly RemoteServiceCallbackDispatcherRegistry _callbackDispatchers; private readonly IThreadingContext _threadingContext; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory( SVsServiceProvider vsServiceProvider, AsynchronousOperationListenerProvider listenerProvider, IThreadingContext threadingContext, [ImportMany] IEnumerable<Lazy<IRemoteServiceCallbackDispatcher, RemoteServiceCallbackDispatcherRegistry.ExportMetadata>> callbackDispatchers) { _vsServiceProvider = (IAsyncServiceProvider)vsServiceProvider; _listenerProvider = listenerProvider; _threadingContext = threadingContext; _callbackDispatchers = new RemoteServiceCallbackDispatcherRegistry(callbackDispatchers); } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { // We don't want to bring up the OOP process in a VS cloud environment client instance // Avoids proffering brokered services on the client instance. if (!RemoteHostOptions.IsUsingServiceHubOutOfProcess(workspaceServices) || workspaceServices.Workspace is not VisualStudioWorkspace || workspaceServices.GetRequiredService<IWorkspaceContextService>().IsCloudEnvironmentClient()) { // Run code in the current process return new DefaultRemoteHostClientProvider(); } return new VisualStudioRemoteHostClientProvider(workspaceServices, _vsServiceProvider, _threadingContext, _listenerProvider, _callbackDispatchers); } } private readonly HostWorkspaceServices _services; private readonly VSThreading.AsyncLazy<RemoteHostClient?> _lazyClient; private readonly IAsyncServiceProvider _vsServiceProvider; private readonly AsynchronousOperationListenerProvider _listenerProvider; private readonly RemoteServiceCallbackDispatcherRegistry _callbackDispatchers; private VisualStudioRemoteHostClientProvider( HostWorkspaceServices services, IAsyncServiceProvider vsServiceProvider, IThreadingContext threadingContext, AsynchronousOperationListenerProvider listenerProvider, RemoteServiceCallbackDispatcherRegistry callbackDispatchers) { _services = services; _vsServiceProvider = vsServiceProvider; _listenerProvider = listenerProvider; _callbackDispatchers = callbackDispatchers; // using VS AsyncLazy here since Roslyn's is not compatible with JTF. // Our ServiceBroker services may be invoked by other VS components under JTF. _lazyClient = new VSThreading.AsyncLazy<RemoteHostClient?>(CreateHostClientAsync, threadingContext.JoinableTaskFactory); } private async Task<RemoteHostClient?> CreateHostClientAsync() { try { var brokeredServiceContainer = await _vsServiceProvider.GetServiceAsync<SVsBrokeredServiceContainer, IBrokeredServiceContainer>().ConfigureAwait(false); var serviceBroker = brokeredServiceContainer.GetFullAccessServiceBroker(); // VS AsyncLazy does not currently support cancellation: var client = await ServiceHubRemoteHostClient.CreateAsync(_services, _listenerProvider, serviceBroker, _callbackDispatchers, CancellationToken.None).ConfigureAwait(false); // proffer in-proc brokered services: _ = brokeredServiceContainer.Proffer(SolutionAssetProvider.ServiceDescriptor, (_, _, _, _) => ValueTaskFactory.FromResult<object?>(new SolutionAssetProvider(_services))); return client; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { return null; } } public Task<RemoteHostClient?> TryGetRemoteHostClientAsync(CancellationToken cancellationToken) => _lazyClient.GetValueAsync(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. using System; using System.Collections.Generic; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.ServiceBroker; using Roslyn.Utilities; using VSThreading = Microsoft.VisualStudio.Threading; namespace Microsoft.VisualStudio.LanguageServices.Remote { internal sealed class VisualStudioRemoteHostClientProvider : IRemoteHostClientProvider { [ExportWorkspaceServiceFactory(typeof(IRemoteHostClientProvider), WorkspaceKind.Host), Shared] internal sealed class Factory : IWorkspaceServiceFactory { private readonly IAsyncServiceProvider _vsServiceProvider; private readonly AsynchronousOperationListenerProvider _listenerProvider; private readonly RemoteServiceCallbackDispatcherRegistry _callbackDispatchers; private readonly IThreadingContext _threadingContext; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory( SVsServiceProvider vsServiceProvider, AsynchronousOperationListenerProvider listenerProvider, IThreadingContext threadingContext, [ImportMany] IEnumerable<Lazy<IRemoteServiceCallbackDispatcher, RemoteServiceCallbackDispatcherRegistry.ExportMetadata>> callbackDispatchers) { _vsServiceProvider = (IAsyncServiceProvider)vsServiceProvider; _listenerProvider = listenerProvider; _threadingContext = threadingContext; _callbackDispatchers = new RemoteServiceCallbackDispatcherRegistry(callbackDispatchers); } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { // We don't want to bring up the OOP process in a VS cloud environment client instance // Avoids proffering brokered services on the client instance. if (!RemoteHostOptions.IsUsingServiceHubOutOfProcess(workspaceServices) || workspaceServices.Workspace is not VisualStudioWorkspace || workspaceServices.GetRequiredService<IWorkspaceContextService>().IsCloudEnvironmentClient()) { // Run code in the current process return new DefaultRemoteHostClientProvider(); } return new VisualStudioRemoteHostClientProvider(workspaceServices, _vsServiceProvider, _threadingContext, _listenerProvider, _callbackDispatchers); } } private readonly HostWorkspaceServices _services; private readonly VSThreading.AsyncLazy<RemoteHostClient?> _lazyClient; private readonly IAsyncServiceProvider _vsServiceProvider; private readonly AsynchronousOperationListenerProvider _listenerProvider; private readonly RemoteServiceCallbackDispatcherRegistry _callbackDispatchers; private VisualStudioRemoteHostClientProvider( HostWorkspaceServices services, IAsyncServiceProvider vsServiceProvider, IThreadingContext threadingContext, AsynchronousOperationListenerProvider listenerProvider, RemoteServiceCallbackDispatcherRegistry callbackDispatchers) { _services = services; _vsServiceProvider = vsServiceProvider; _listenerProvider = listenerProvider; _callbackDispatchers = callbackDispatchers; // using VS AsyncLazy here since Roslyn's is not compatible with JTF. // Our ServiceBroker services may be invoked by other VS components under JTF. _lazyClient = new VSThreading.AsyncLazy<RemoteHostClient?>(CreateHostClientAsync, threadingContext.JoinableTaskFactory); } private async Task<RemoteHostClient?> CreateHostClientAsync() { try { var brokeredServiceContainer = await _vsServiceProvider.GetServiceAsync<SVsBrokeredServiceContainer, IBrokeredServiceContainer>().ConfigureAwait(false); var serviceBroker = brokeredServiceContainer.GetFullAccessServiceBroker(); // VS AsyncLazy does not currently support cancellation: var client = await ServiceHubRemoteHostClient.CreateAsync(_services, _listenerProvider, serviceBroker, _callbackDispatchers, CancellationToken.None).ConfigureAwait(false); // proffer in-proc brokered services: _ = brokeredServiceContainer.Proffer(SolutionAssetProvider.ServiceDescriptor, (_, _, _, _) => ValueTaskFactory.FromResult<object?>(new SolutionAssetProvider(_services))); return client; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { return null; } } public Task<RemoteHostClient?> TryGetRemoteHostClientAsync(CancellationToken cancellationToken) => _lazyClient.GetValueAsync(cancellationToken); } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/EditorFeatures/CSharpTest/AddFileBanner/AddFileBannerTests.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.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.AddFileBanner; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddFileBanner { public partial class AddFileBannerTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpAddFileBannerCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestBanner1() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>// This is the banner using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMultiLineBanner1() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner // It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>// This is the banner // It goes over multiple lines using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner // It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestSingleLineDocCommentBanner() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>/// This is the banner /// It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>/// This is the banner /// It goes over multiple lines using System; class Program1 { static void Main() { } } </Document> <Document>/// This is the banner /// It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestMultiLineDocCommentBanner() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>/** This is the banner * It goes over multiple lines */ class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>/** This is the banner * It goes over multiple lines */ using System; class Program1 { static void Main() { } } </Document> <Document>/** This is the banner * It goes over multiple lines */ class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMissingWhenAlreadyThere() { await TestMissingAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]// I already have a banner using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner class Program2 { } </Document> </Project> </Workspace>"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [InlineData("", 1)] [InlineData("file_header_template =", 1)] [InlineData("file_header_template = unset", 1)] [InlineData("file_header_template = defined file header", 0)] public async Task TestMissingWhenHandledByAnalyzer(string fileHeaderTemplate, int expectedActionCount) { var initialMarkup = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""/0/Test0.cs"">[||]using System; class Program1 {{ static void Main() {{ }} }} </Document> <Document FilePath=""/0/Test1.cs"">/// This is the banner /// It goes over multiple lines class Program2 {{ }} </Document> <AnalyzerConfigDocument FilePath=""/.editorconfig""> root = true [*] {fileHeaderTemplate} </AnalyzerConfigDocument> </Project> </Workspace>"; await TestActionCountAsync(initialMarkup, expectedActionCount); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMissingIfOtherFileDoesNotHaveBanner() { await TestMissingAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||] using System; class Program1 { static void Main() { } } </Document> <Document> class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMissingIfOtherFileIsAutoGenerated() { await TestMissingAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||] using System; class Program1 { static void Main() { } } </Document> <Document>// &lt;autogenerated /&gt; class Program2 { } </Document> </Project> </Workspace>"); } [WorkItem(32792, "https://github.com/dotnet/roslyn/issues/32792")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestUpdateFileNameInComment() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">// This is the banner in Bar.cs // It goes over multiple lines. This line has Baz.cs // The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">// This is the banner in Goo.cs // It goes over multiple lines. This line has Baz.cs // The last line includes Goo.cs using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">// This is the banner in Bar.cs // It goes over multiple lines. This line has Baz.cs // The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>"); } [WorkItem(32792, "https://github.com/dotnet/roslyn/issues/32792")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestUpdateFileNameInComment2() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/* This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">/* This is the banner in Goo.cs It goes over multiple lines. This line has Baz.cs The last line includes Goo.cs */ using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/* This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestUpdateFileNameInComment3() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/** This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">/** This is the banner in Goo.cs It goes over multiple lines. This line has Baz.cs The last line includes Goo.cs */ using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/** This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestUpdateFileNameInComment4() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/// This is the banner in Bar.cs /// It goes over multiple lines. This line has Baz.cs /// The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">/// This is the banner in Goo.cs /// It goes over multiple lines. This line has Baz.cs /// The last line includes Goo.cs using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/// This is the banner in Bar.cs /// It goes over multiple lines. This line has Baz.cs /// The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>"); } } }
// Licensed to the .NET Foundation under one or more 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.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.AddFileBanner; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddFileBanner { public partial class AddFileBannerTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpAddFileBannerCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestBanner1() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>// This is the banner using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMultiLineBanner1() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner // It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>// This is the banner // It goes over multiple lines using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner // It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestSingleLineDocCommentBanner() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>/// This is the banner /// It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>/// This is the banner /// It goes over multiple lines using System; class Program1 { static void Main() { } } </Document> <Document>/// This is the banner /// It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestMultiLineDocCommentBanner() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>/** This is the banner * It goes over multiple lines */ class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>/** This is the banner * It goes over multiple lines */ using System; class Program1 { static void Main() { } } </Document> <Document>/** This is the banner * It goes over multiple lines */ class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMissingWhenAlreadyThere() { await TestMissingAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]// I already have a banner using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner class Program2 { } </Document> </Project> </Workspace>"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [InlineData("", 1)] [InlineData("file_header_template =", 1)] [InlineData("file_header_template = unset", 1)] [InlineData("file_header_template = defined file header", 0)] public async Task TestMissingWhenHandledByAnalyzer(string fileHeaderTemplate, int expectedActionCount) { var initialMarkup = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""/0/Test0.cs"">[||]using System; class Program1 {{ static void Main() {{ }} }} </Document> <Document FilePath=""/0/Test1.cs"">/// This is the banner /// It goes over multiple lines class Program2 {{ }} </Document> <AnalyzerConfigDocument FilePath=""/.editorconfig""> root = true [*] {fileHeaderTemplate} </AnalyzerConfigDocument> </Project> </Workspace>"; await TestActionCountAsync(initialMarkup, expectedActionCount); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMissingIfOtherFileDoesNotHaveBanner() { await TestMissingAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||] using System; class Program1 { static void Main() { } } </Document> <Document> class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMissingIfOtherFileIsAutoGenerated() { await TestMissingAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||] using System; class Program1 { static void Main() { } } </Document> <Document>// &lt;autogenerated /&gt; class Program2 { } </Document> </Project> </Workspace>"); } [WorkItem(32792, "https://github.com/dotnet/roslyn/issues/32792")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestUpdateFileNameInComment() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">// This is the banner in Bar.cs // It goes over multiple lines. This line has Baz.cs // The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">// This is the banner in Goo.cs // It goes over multiple lines. This line has Baz.cs // The last line includes Goo.cs using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">// This is the banner in Bar.cs // It goes over multiple lines. This line has Baz.cs // The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>"); } [WorkItem(32792, "https://github.com/dotnet/roslyn/issues/32792")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestUpdateFileNameInComment2() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/* This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">/* This is the banner in Goo.cs It goes over multiple lines. This line has Baz.cs The last line includes Goo.cs */ using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/* This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestUpdateFileNameInComment3() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/** This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">/** This is the banner in Goo.cs It goes over multiple lines. This line has Baz.cs The last line includes Goo.cs */ using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/** This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestUpdateFileNameInComment4() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/// This is the banner in Bar.cs /// It goes over multiple lines. This line has Baz.cs /// The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">/// This is the banner in Goo.cs /// It goes over multiple lines. This line has Baz.cs /// The last line includes Goo.cs using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/// This is the banner in Bar.cs /// It goes over multiple lines. This line has Baz.cs /// The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>"); } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationResultEnumContext.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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.CallStack; namespace Microsoft.VisualStudio.Debugger.Evaluation { public class DkmEvaluationResultEnumContext : DkmDataContainer { public readonly int Count; public readonly DkmInspectionContext InspectionContext; internal DkmEvaluationResultEnumContext(int count, DkmInspectionContext inspectionContext) { this.Count = count; this.InspectionContext = inspectionContext; } public static DkmEvaluationResultEnumContext Create(int Count, DkmStackWalkFrame StackFrame, DkmInspectionContext InspectionContext, DkmDataItem DataItem) { var enumContext = new DkmEvaluationResultEnumContext(Count, InspectionContext); if (DataItem != null) { enumContext.SetDataItem(DkmDataCreationDisposition.CreateNew, DataItem); } return enumContext; } public void GetItems(DkmWorkList workList, int startIndex, int count, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine) { InspectionContext.InspectionSession.InvokeResultProvider( this, MethodId.GetItems, r => { r.GetItems(this, workList, startIndex, count, completionRoutine); return (object)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. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.CallStack; namespace Microsoft.VisualStudio.Debugger.Evaluation { public class DkmEvaluationResultEnumContext : DkmDataContainer { public readonly int Count; public readonly DkmInspectionContext InspectionContext; internal DkmEvaluationResultEnumContext(int count, DkmInspectionContext inspectionContext) { this.Count = count; this.InspectionContext = inspectionContext; } public static DkmEvaluationResultEnumContext Create(int Count, DkmStackWalkFrame StackFrame, DkmInspectionContext InspectionContext, DkmDataItem DataItem) { var enumContext = new DkmEvaluationResultEnumContext(Count, InspectionContext); if (DataItem != null) { enumContext.SetDataItem(DkmDataCreationDisposition.CreateNew, DataItem); } return enumContext; } public void GetItems(DkmWorkList workList, int startIndex, int count, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine) { InspectionContext.InspectionSession.InvokeResultProvider( this, MethodId.GetItems, r => { r.GetItems(this, workList, startIndex, count, completionRoutine); return (object)null; }); } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Builder.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.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; namespace Roslyn.Utilities { internal partial class BKTree { private class Builder { // The number of edges we pre-allocate space for for each node in _compactEdges. // // To make the comments simpler below, i'll use '4' as a synonym for CompactEdgeAllocationSize. // '4' simply reads better and makes it clearer what's going on. private const int CompactEdgeAllocationSize = 4; // Instead of producing a char[] for each string we're building a node for, we instead // have one long char[] with all the chracters of each string concatenated. i.e. // "goo" "bar" and "baz" becomes { f, o, o, b, a, r, b, a, z }. Then in _wordSpans // we have the text spans for each of those words in this array. This gives us only // two allocations instead of as many allocations as the number of strings we have. // // Once we are done building, we pass this to the BKTree and its nodes also state the // span of this array that corresponds to the word they were created for. This works // well as other dependent facilities (like EditDistance) can work on sub-arrays without // any problems. private readonly char[] _concatenatedLowerCaseWords; private readonly TextSpan[] _wordSpans; // Note: while building a BKTree we have to store children with parents, keyed by the // edit distance between the two. Naive implementations might store a list or dictionary // of children along with each node. However, this would be very inefficient and would // put an enormous amount of memory pressure on the system. // // Emperical data for a nice large assembly like mscorlib gives us the following // information: // // Unique-Words (ignoring case): 9662 // // For each unique word we need a node in the BKTree. If we stored a list or dictionary // with each node, that would be 10s of thousands of objects created that would then // just have to be GCed. That's a lot of garbage pressure we'd like to avoid. // // Now if we look at all those nodes, we can see the following information about how many // children each has. // // Edge counts: // 0 5560 // 1 1884 // 2 887 // 3 527 // 4 322 // 5 200 // 6 114 // 7 69 // 8 47 // 9 20 // 10 8 // 11 10 // 12 7 // 13 4 // 15 1 // 16 1 // 54 1 // // // i.e. The number of nodes with edge-counts less than or equal to four is: 5560+1884+887+527+322=9180. // This is 95% of the total number of edges we are adding. Looking at many other dlls // we found that this ratio stays true across the board. i.e. with all dlls, 95% of nodes // have 4 or less edges. // // So, to optimize things, we pre-alloc a single array with space for 4 edges for each // node we're going to add. Each node then gets that much space to store edge information. // If it needs more than that space, then we have a fall-over dictionary that it can store // information in. // // Once building is complete, the GC only needs to deallocate this single array and the // spillover dictionaries. // // This approach produces 1/20th the amount of garbage while building the tree. // // Each node at index i has its edges in this array in the range [4*i, 4*i + 4); private readonly Edge[] _compactEdges; private readonly BuilderNode[] _builderNodes; public Builder(IEnumerable<ReadOnlyMemory<char>> values) { // TODO(cyrusn): Properly handle unicode normalization here. var distinctValues = values.Where(v => v.Length > 0).Distinct(StringSliceComparer.OrdinalIgnoreCase).ToArray(); var charCount = values.Sum(v => v.Length); _concatenatedLowerCaseWords = new char[charCount]; _wordSpans = new TextSpan[distinctValues.Length]; var characterIndex = 0; for (var i = 0; i < distinctValues.Length; i++) { var value = distinctValues[i]; _wordSpans[i] = new TextSpan(characterIndex, value.Length); foreach (var ch in value.Span) { _concatenatedLowerCaseWords[characterIndex] = CaseInsensitiveComparison.ToLower(ch); characterIndex++; } } // We will have one node for each string value that we are adding. _builderNodes = new BuilderNode[distinctValues.Length]; _compactEdges = new Edge[distinctValues.Length * CompactEdgeAllocationSize]; } internal BKTree Create() { for (var i = 0; i < _wordSpans.Length; i++) { Add(_wordSpans[i], insertionIndex: i); } var nodes = ImmutableArray.CreateBuilder<Node>(_builderNodes.Length); // There will be one less edge in the graph than nodes. Each node (except for the // root) will have a single edge pointing to it. var edges = ImmutableArray.CreateBuilder<Edge>(Math.Max(0, _builderNodes.Length - 1)); BuildArrays(nodes, edges); return new BKTree(_concatenatedLowerCaseWords, nodes.MoveToImmutable(), edges.MoveToImmutable()); } private void BuildArrays(ImmutableArray<Node>.Builder nodes, ImmutableArray<Edge>.Builder edges) { var currentEdgeIndex = 0; for (var i = 0; i < _builderNodes.Length; i++) { var builderNode = _builderNodes[i]; var edgeCount = builderNode.EdgeCount; nodes.Add(new Node(builderNode.CharacterSpan, edgeCount, currentEdgeIndex)); if (edgeCount > 0) { // First, copy any edges that are in the compact array. var start = i * CompactEdgeAllocationSize; var end = start + Math.Min(edgeCount, CompactEdgeAllocationSize); for (var j = start; j < end; j++) { edges.Add(_compactEdges[j]); } // Then, if we've spilled over any edges, copy them as well. var spilledEdges = builderNode.SpilloverEdges; if (spilledEdges != null) { Debug.Assert(spilledEdges.Count == (edgeCount - CompactEdgeAllocationSize)); foreach (var (distance, childIndex) in spilledEdges) edges.Add(new Edge(distance, childIndex)); } } currentEdgeIndex += edgeCount; } Debug.Assert(currentEdgeIndex == edges.Capacity); Debug.Assert(currentEdgeIndex == edges.Count); } private void Add(TextSpan characterSpan, int insertionIndex) { if (insertionIndex == 0) { _builderNodes[insertionIndex] = new BuilderNode(characterSpan); return; } var currentNodeIndex = 0; while (true) { var currentNode = _builderNodes[currentNodeIndex]; // Determine the edit distance between these two words. Note: we do not use // a threshold here as we need the actual edit distance so we can actually // determine what edge to make or walk. var editDistance = EditDistance.GetEditDistance( _concatenatedLowerCaseWords.AsSpan(currentNode.CharacterSpan.Start, currentNode.CharacterSpan.Length), _concatenatedLowerCaseWords.AsSpan(characterSpan.Start, characterSpan.Length)); if (editDistance == 0) { // This should never happen. We dedupe all items before proceeding to the 'Add' step. // So the edit distance should always be non-zero. throw new InvalidOperationException(); } if (TryGetChildIndex(currentNode, currentNodeIndex, editDistance, out var childNodeIndex)) { // Edit distances collide. Move to this child and add this word to it. currentNodeIndex = childNodeIndex; continue; } // found the node we want to add the child node to. AddChildNode(characterSpan, insertionIndex, currentNode.EdgeCount, currentNodeIndex, editDistance); return; } } private void AddChildNode( TextSpan characterSpan, int insertionIndex, int currentNodeEdgeCount, int currentNodeIndex, int editDistance) { // The node as 'currentNodeIndex' doesn't have an edge with this edit distance. // Three cases to handle: // 1) there are less than 4 edges. We simply place the edge into the correct // location in compactEdges // 2) there are 4 edges. We need to make the spillover dictionary and then add // the new edge into that. // 3) there are more than 4 edges. Just put the new edge in the spillover // dictionary. if (currentNodeEdgeCount < CompactEdgeAllocationSize) { _compactEdges[currentNodeIndex * CompactEdgeAllocationSize + currentNodeEdgeCount] = new Edge(editDistance, insertionIndex); } else { ref var node = ref _builderNodes[currentNodeIndex]; // When we hit 4 elements, we need to allocate the spillover dictionary to // place the extra edges. if (currentNodeEdgeCount == CompactEdgeAllocationSize) { RoslynDebug.Assert(node.SpilloverEdges is null); var spilloverEdges = new Dictionary<int, int>(); node.SpilloverEdges = spilloverEdges; } else { RoslynDebug.AssertNotNull(node.SpilloverEdges); } node.SpilloverEdges.Add(editDistance, insertionIndex); } _builderNodes[currentNodeIndex].EdgeCount++; _builderNodes[insertionIndex] = new BuilderNode(characterSpan); return; } private bool TryGetChildIndex(BuilderNode currentNode, int currentNodeIndex, int editDistance, out int childIndex) { // linearly scan the children we have to see if there is one with this edit distance. var start = currentNodeIndex * CompactEdgeAllocationSize; var end = start + Math.Min(currentNode.EdgeCount, CompactEdgeAllocationSize); for (var i = start; i < end; i++) { if (_compactEdges[i].EditDistance == editDistance) { childIndex = _compactEdges[i].ChildNodeIndex; return true; } } // If we've spilled over any edges, check there as well if (currentNode.SpilloverEdges != null) { // Can't use the compact array. Have to use the spillover dictionary instead. Debug.Assert(currentNode.SpilloverEdges.Count == (currentNode.EdgeCount - CompactEdgeAllocationSize)); return currentNode.SpilloverEdges.TryGetValue(editDistance, out childIndex); } childIndex = -1; return false; } private struct BuilderNode { public readonly TextSpan CharacterSpan; public int EdgeCount; public Dictionary<int, int>? SpilloverEdges; public BuilderNode(TextSpan characterSpan) : this() => this.CharacterSpan = characterSpan; } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; namespace Roslyn.Utilities { internal partial class BKTree { private class Builder { // The number of edges we pre-allocate space for for each node in _compactEdges. // // To make the comments simpler below, i'll use '4' as a synonym for CompactEdgeAllocationSize. // '4' simply reads better and makes it clearer what's going on. private const int CompactEdgeAllocationSize = 4; // Instead of producing a char[] for each string we're building a node for, we instead // have one long char[] with all the chracters of each string concatenated. i.e. // "goo" "bar" and "baz" becomes { f, o, o, b, a, r, b, a, z }. Then in _wordSpans // we have the text spans for each of those words in this array. This gives us only // two allocations instead of as many allocations as the number of strings we have. // // Once we are done building, we pass this to the BKTree and its nodes also state the // span of this array that corresponds to the word they were created for. This works // well as other dependent facilities (like EditDistance) can work on sub-arrays without // any problems. private readonly char[] _concatenatedLowerCaseWords; private readonly TextSpan[] _wordSpans; // Note: while building a BKTree we have to store children with parents, keyed by the // edit distance between the two. Naive implementations might store a list or dictionary // of children along with each node. However, this would be very inefficient and would // put an enormous amount of memory pressure on the system. // // Emperical data for a nice large assembly like mscorlib gives us the following // information: // // Unique-Words (ignoring case): 9662 // // For each unique word we need a node in the BKTree. If we stored a list or dictionary // with each node, that would be 10s of thousands of objects created that would then // just have to be GCed. That's a lot of garbage pressure we'd like to avoid. // // Now if we look at all those nodes, we can see the following information about how many // children each has. // // Edge counts: // 0 5560 // 1 1884 // 2 887 // 3 527 // 4 322 // 5 200 // 6 114 // 7 69 // 8 47 // 9 20 // 10 8 // 11 10 // 12 7 // 13 4 // 15 1 // 16 1 // 54 1 // // // i.e. The number of nodes with edge-counts less than or equal to four is: 5560+1884+887+527+322=9180. // This is 95% of the total number of edges we are adding. Looking at many other dlls // we found that this ratio stays true across the board. i.e. with all dlls, 95% of nodes // have 4 or less edges. // // So, to optimize things, we pre-alloc a single array with space for 4 edges for each // node we're going to add. Each node then gets that much space to store edge information. // If it needs more than that space, then we have a fall-over dictionary that it can store // information in. // // Once building is complete, the GC only needs to deallocate this single array and the // spillover dictionaries. // // This approach produces 1/20th the amount of garbage while building the tree. // // Each node at index i has its edges in this array in the range [4*i, 4*i + 4); private readonly Edge[] _compactEdges; private readonly BuilderNode[] _builderNodes; public Builder(IEnumerable<ReadOnlyMemory<char>> values) { // TODO(cyrusn): Properly handle unicode normalization here. var distinctValues = values.Where(v => v.Length > 0).Distinct(StringSliceComparer.OrdinalIgnoreCase).ToArray(); var charCount = values.Sum(v => v.Length); _concatenatedLowerCaseWords = new char[charCount]; _wordSpans = new TextSpan[distinctValues.Length]; var characterIndex = 0; for (var i = 0; i < distinctValues.Length; i++) { var value = distinctValues[i]; _wordSpans[i] = new TextSpan(characterIndex, value.Length); foreach (var ch in value.Span) { _concatenatedLowerCaseWords[characterIndex] = CaseInsensitiveComparison.ToLower(ch); characterIndex++; } } // We will have one node for each string value that we are adding. _builderNodes = new BuilderNode[distinctValues.Length]; _compactEdges = new Edge[distinctValues.Length * CompactEdgeAllocationSize]; } internal BKTree Create() { for (var i = 0; i < _wordSpans.Length; i++) { Add(_wordSpans[i], insertionIndex: i); } var nodes = ImmutableArray.CreateBuilder<Node>(_builderNodes.Length); // There will be one less edge in the graph than nodes. Each node (except for the // root) will have a single edge pointing to it. var edges = ImmutableArray.CreateBuilder<Edge>(Math.Max(0, _builderNodes.Length - 1)); BuildArrays(nodes, edges); return new BKTree(_concatenatedLowerCaseWords, nodes.MoveToImmutable(), edges.MoveToImmutable()); } private void BuildArrays(ImmutableArray<Node>.Builder nodes, ImmutableArray<Edge>.Builder edges) { var currentEdgeIndex = 0; for (var i = 0; i < _builderNodes.Length; i++) { var builderNode = _builderNodes[i]; var edgeCount = builderNode.EdgeCount; nodes.Add(new Node(builderNode.CharacterSpan, edgeCount, currentEdgeIndex)); if (edgeCount > 0) { // First, copy any edges that are in the compact array. var start = i * CompactEdgeAllocationSize; var end = start + Math.Min(edgeCount, CompactEdgeAllocationSize); for (var j = start; j < end; j++) { edges.Add(_compactEdges[j]); } // Then, if we've spilled over any edges, copy them as well. var spilledEdges = builderNode.SpilloverEdges; if (spilledEdges != null) { Debug.Assert(spilledEdges.Count == (edgeCount - CompactEdgeAllocationSize)); foreach (var (distance, childIndex) in spilledEdges) edges.Add(new Edge(distance, childIndex)); } } currentEdgeIndex += edgeCount; } Debug.Assert(currentEdgeIndex == edges.Capacity); Debug.Assert(currentEdgeIndex == edges.Count); } private void Add(TextSpan characterSpan, int insertionIndex) { if (insertionIndex == 0) { _builderNodes[insertionIndex] = new BuilderNode(characterSpan); return; } var currentNodeIndex = 0; while (true) { var currentNode = _builderNodes[currentNodeIndex]; // Determine the edit distance between these two words. Note: we do not use // a threshold here as we need the actual edit distance so we can actually // determine what edge to make or walk. var editDistance = EditDistance.GetEditDistance( _concatenatedLowerCaseWords.AsSpan(currentNode.CharacterSpan.Start, currentNode.CharacterSpan.Length), _concatenatedLowerCaseWords.AsSpan(characterSpan.Start, characterSpan.Length)); if (editDistance == 0) { // This should never happen. We dedupe all items before proceeding to the 'Add' step. // So the edit distance should always be non-zero. throw new InvalidOperationException(); } if (TryGetChildIndex(currentNode, currentNodeIndex, editDistance, out var childNodeIndex)) { // Edit distances collide. Move to this child and add this word to it. currentNodeIndex = childNodeIndex; continue; } // found the node we want to add the child node to. AddChildNode(characterSpan, insertionIndex, currentNode.EdgeCount, currentNodeIndex, editDistance); return; } } private void AddChildNode( TextSpan characterSpan, int insertionIndex, int currentNodeEdgeCount, int currentNodeIndex, int editDistance) { // The node as 'currentNodeIndex' doesn't have an edge with this edit distance. // Three cases to handle: // 1) there are less than 4 edges. We simply place the edge into the correct // location in compactEdges // 2) there are 4 edges. We need to make the spillover dictionary and then add // the new edge into that. // 3) there are more than 4 edges. Just put the new edge in the spillover // dictionary. if (currentNodeEdgeCount < CompactEdgeAllocationSize) { _compactEdges[currentNodeIndex * CompactEdgeAllocationSize + currentNodeEdgeCount] = new Edge(editDistance, insertionIndex); } else { ref var node = ref _builderNodes[currentNodeIndex]; // When we hit 4 elements, we need to allocate the spillover dictionary to // place the extra edges. if (currentNodeEdgeCount == CompactEdgeAllocationSize) { RoslynDebug.Assert(node.SpilloverEdges is null); var spilloverEdges = new Dictionary<int, int>(); node.SpilloverEdges = spilloverEdges; } else { RoslynDebug.AssertNotNull(node.SpilloverEdges); } node.SpilloverEdges.Add(editDistance, insertionIndex); } _builderNodes[currentNodeIndex].EdgeCount++; _builderNodes[insertionIndex] = new BuilderNode(characterSpan); return; } private bool TryGetChildIndex(BuilderNode currentNode, int currentNodeIndex, int editDistance, out int childIndex) { // linearly scan the children we have to see if there is one with this edit distance. var start = currentNodeIndex * CompactEdgeAllocationSize; var end = start + Math.Min(currentNode.EdgeCount, CompactEdgeAllocationSize); for (var i = start; i < end; i++) { if (_compactEdges[i].EditDistance == editDistance) { childIndex = _compactEdges[i].ChildNodeIndex; return true; } } // If we've spilled over any edges, check there as well if (currentNode.SpilloverEdges != null) { // Can't use the compact array. Have to use the spillover dictionary instead. Debug.Assert(currentNode.SpilloverEdges.Count == (currentNode.EdgeCount - CompactEdgeAllocationSize)); return currentNode.SpilloverEdges.TryGetValue(editDistance, out childIndex); } childIndex = -1; return false; } private struct BuilderNode { public readonly TextSpan CharacterSpan; public int EdgeCount; public Dictionary<int, int>? SpilloverEdges; public BuilderNode(TextSpan characterSpan) : this() => this.CharacterSpan = characterSpan; } } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpAsAndNullCheckTests.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.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UsePatternMatching; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternMatching { public partial class CSharpAsAndNullCheckTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public CSharpAsAndNullCheckTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpAsAndNullCheckDiagnosticAnalyzer(), new CSharpAsAndNullCheckCodeFixProvider()); [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] [InlineData("x != null", "o is string x")] [InlineData("null != x", "o is string x")] [InlineData("(object)x != null", "o is string x")] [InlineData("null != (object)x", "o is string x")] [InlineData("x is object", "o is string x")] [InlineData("x == null", "!(o is string x)")] [InlineData("null == x", "!(o is string x)")] [InlineData("(object)x == null", "!(o is string x)")] [InlineData("null == (object)x", "!(o is string x)")] [InlineData("x is null", "!(o is string x)")] [InlineData("(x = o as string) != null", "o is string x")] [InlineData("null != (x = o as string)", "o is string x")] [InlineData("(x = o as string) is object", "o is string x")] [InlineData("(x = o as string) == null", "!(o is string x)")] [InlineData("null == (x = o as string)", "!(o is string x)")] [InlineData("(x = o as string) is null", "!(o is string x)")] [InlineData("x == null", "o is not string x", LanguageVersion.CSharp9)] public async Task InlineTypeCheck1(string input, string output, LanguageVersion version = LanguageVersion.CSharp8) { await TestStatement($"if ({input}) {{ }}", $"if ({output}) {{ }}", version); await TestStatement($"var y = {input};", $"var y = {output};", version); await TestStatement($"return {input};", $"return {output};", version); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] [InlineData("(x = o as string) != null", "o is string x")] [InlineData("null != (x = o as string)", "o is string x")] [InlineData("(x = o as string) is object", "o is string x")] [InlineData("(x = o as string) == null", "!(o is string x)")] [InlineData("null == (x = o as string)", "!(o is string x)")] public async Task InlineTypeCheck2(string input, string output) => await TestStatement($"while ({input}) {{ }}", $"while ({output}) {{ }}"); private async Task TestStatement(string input, string output, LanguageVersion version = LanguageVersion.CSharp8) { await TestInRegularAndScript1Async( $@"class C {{ void M(object o) {{ [|var|] x = o as string; {input} }} }}", $@"class C {{ void M(object o) {{ {output} }} }}", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(version))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingInCSharp6() { await TestMissingAsync( @"class C { void M() { [|var|] x = o as string; if (x != null) { } } }", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingInWrongName() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|var|] y = o as string; if (x != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestInSwitchSection() { await TestInRegularAndScript1Async( @"class C { void M() { switch (o) { default: [|var|] x = o as string; if (x != null) { } } } }", @"class C { void M() { switch (o) { default: if (o is string x) { } } } }"); } [WorkItem(33345, "https://github.com/dotnet/roslyn/issues/33345")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestRemoveNewLinesInSwitchStatement() { await TestInRegularAndScript1Async( @"class C { void M() { switch (o) { default: [|var|] x = o as string; //a comment if (x != null) { } } } }", @"class C { void M() { switch (o) { default: //a comment if (o is string x) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingOnNonDeclaration() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|y|] = o as string; if (x != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] [WorkItem(25237, "https://github.com/dotnet/roslyn/issues/25237")] public async Task TestMissingOnReturnStatement() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|return;|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingOnIsExpression() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|var|] x = o is string; if (x != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task InlineTypeCheckComplexExpression1() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = (o ? z : w) as string; if (x != null) { } } }", @"class C { void M() { if ((o ? z : w) is string x) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestInlineTypeCheckWithElse() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; if (null != x) { } else { } } }", @"class C { void M() { if (o is string x) { } else { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestComments1() { await TestInRegularAndScript1Async( @"class C { void M() { // prefix comment [|var|] x = o as string; if (x != null) { } } }", @"class C { void M() { // prefix comment if (o is string x) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestComments2() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; // suffix comment if (x != null) { } } }", @"class C { void M() { // suffix comment if (o is string x) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestComments3() { await TestInRegularAndScript1Async( @"class C { void M() { // prefix comment [|var|] x = o as string; // suffix comment if (x != null) { } } }", @"class C { void M() { // prefix comment // suffix comment if (o is string x) { } } }"); } [WorkItem(33345, "https://github.com/dotnet/roslyn/issues/33345")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestRemoveNewLines() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; //suffix comment if (x != null) { } } }", @"class C { void M() { //suffix comment if (o is string x) { } } }"); } [WorkItem(33345, "https://github.com/dotnet/roslyn/issues/33345")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestRemoveNewLinesWhereBlankLineIsNotEmpty() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; //suffix comment if (x != null) { } } }", @"class C { void M() { //suffix comment if (o is string x) { } } }"); } [WorkItem(33345, "https://github.com/dotnet/roslyn/issues/33345")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestRemoveNewLines2() { await TestInRegularAndScript1Async( @"class C { void M() { int a = 0; [|var|] x = o as string; //suffix comment if (x != null) { } } }", @"class C { void M() { int a = 0; //suffix comment if (o is string x) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task InlineTypeCheckComplexCondition1() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; if (x != null ? 0 : 1) { } } }", @"class C { void M() { if (o is string x ? 0 : 1) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task InlineTypeCheckComplexCondition2() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; if ((x != null)) { } } }", @"class C { void M() { if ((o is string x)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task InlineTypeCheckComplexCondition3() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; if (x != null && x.Length > 0) { } } }", @"class C { void M() { if (o is string x && x.Length > 0) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDefiniteAssignment1() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|var|] x = o as string; if (x != null && x.Length > 0) { } else if (x != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDefiniteAssignment2() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|var|] x = o as string; if (x != null && x.Length > 0) { } Console.WriteLine(x); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDefiniteAssignment3() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; if (x != null && x.Length > 0) { } x = null; Console.WriteLine(x); } }", @"class C { void M() { if (o is string x && x.Length > 0) { } x = null; Console.WriteLine(x); } }"); } [WorkItem(21097, "https://github.com/dotnet/roslyn/issues/21097")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDefiniteAssignment4() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object o) { [|var|] s = o as string; if (s != null) { } else { if (o is int?) s = null; s.ToString(); } } }"); } [WorkItem(24286, "https://github.com/dotnet/roslyn/issues/24286")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDefiniteAssignment5() { await TestMissingInRegularAndScriptAsync( @"public class Test { public void TestIt(object o1, object o2) { [|var|] test = o1 as Test; if (test != null || o2 != null) { var o3 = test ?? o2; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDefiniteAssignment6() { await TestMissingInRegularAndScriptAsync( @"class C { string Use(string x) => x; void M() { [|var|] x = o as string; if (x != null && x.Length > 0) { } Console.WriteLine(x = Use(x)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDefiniteAssignment7() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|var|] x = o as string; if (x != null && x.Length > 0) { } Console.WriteLine(x); x = ""writeAfter""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] [WorkItem(28821, "https://github.com/dotnet/roslyn/issues/28821")] public async Task TestDefiniteAssignment8() { await TestMissingInRegularAndScriptAsync( @"class Program { static void Goo(System.Activator bar) { } static void Main(string[] args) { var a = new object(); [|var|] b = a as System.Activator; if ((b == null) && false) { } else { Goo(b); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] [WorkItem(28866, "https://github.com/dotnet/roslyn/issues/28866")] public async Task TestWrittenExpressionBeforeNullCheck() { await TestMissingInRegularAndScriptAsync( @"class Goo { object Data { get; set; } void DoGoo() { [|var|] oldData = this.Data as string; Data = null; if (oldData != null) { // Do something } } }"); } [WorkItem(15957, "https://github.com/dotnet/roslyn/issues/15957")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestTrivia1() { await TestInRegularAndScript1Async( @"class C { void M(object y) { if (y != null) { } [|var|] x = o as string; if (x != null) { } } }", @"class C { void M(object y) { if (y != null) { } if (o is string x) { } } }"); } [WorkItem(17129, "https://github.com/dotnet/roslyn/issues/17129")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestTrivia2() { await TestInRegularAndScript1Async( @"using System; namespace N { class Program { public static void Main() { object o = null; int i = 0; [|var|] s = o as string; if (s != null && i == 0 && i == 1 && i == 2 && i == 3 && i == 4 && i == 5) { Console.WriteLine(); } } } }", @"using System; namespace N { class Program { public static void Main() { object o = null; int i = 0; if (o is string s && i == 0 && i == 1 && i == 2 && i == 3 && i == 4 && i == 5) { Console.WriteLine(); } } } }"); } [WorkItem(17122, "https://github.com/dotnet/roslyn/issues/17122")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingOnNullableType() { await TestMissingInRegularAndScriptAsync( @"using System; namespace N { class Program { public static void Main() { object o = null; [|var|] i = o as int?; if (i != null) Console.WriteLine(i); } } }"); } [WorkItem(18053, "https://github.com/dotnet/roslyn/issues/18053")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingWhenTypesDoNotMatch() { await TestMissingInRegularAndScriptAsync( @"class SyntaxNode { public SyntaxNode Parent; } class BaseParameterListSyntax : SyntaxNode { } class ParameterSyntax : SyntaxNode { } public static class C { static void M(ParameterSyntax parameter) { [|SyntaxNode|] parent = parameter.Parent as BaseParameterListSyntax; if (parent != null) { parent = parent.Parent; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingOnWhileNoInline() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object o) { [|string|] x = o as string; while (x != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestWhileDefiniteAssignment1() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object o) { [|string|] x; while ((x = o as string) != null) { } var readAfterWhile = x; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestWhileDefiniteAssignment2() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object o) { [|string|] x; while ((x = o as string) != null) { } x = ""writeAfterWhile""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestWhileDefiniteAssignment3() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object o) { [|string|] x; x = ""writeBeforeWhile""; while ((x = o as string) != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestWhileDefiniteAssignment4() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object o) { [|string|] x = null; var readBeforeWhile = x; while ((x = o as string) != null) { } } }"); } [WorkItem(23504, "https://github.com/dotnet/roslyn/issues/23504")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task DoNotChangeOriginalFormatting1() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { object obj = ""test""; [|var|] str = obj as string; var title = str != null ? str : ""; } }", @"class Program { static void Main(string[] args) { object obj = ""test""; var title = obj is string str ? str : ""; } }"); } [WorkItem(23504, "https://github.com/dotnet/roslyn/issues/23504")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task DoNotChangeOriginalFormatting2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { object obj = ""test""; [|var|] str = obj as string; var title = str != null ? str : ""; } }", @"class Program { static void Main(string[] args) { object obj = ""test""; var title = obj is string str ? str : ""; } }"); } [WorkItem(21172, "https://github.com/dotnet/roslyn/issues/21172")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingWithDynamic() { await TestMissingAsync( @"class C { void M(object o) { [|var|] x = o as dynamic; if (x != null) { } } }"); } [WorkItem(21551, "https://github.com/dotnet/roslyn/issues/21551")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestOverloadedUserOperator() { await TestMissingAsync( @"class C { public static void Main() { object o = new C(); [|var|] c = o as C; if (c != null) System.Console.WriteLine(); } public static bool operator ==(C c1, C c2) => false; public static bool operator !=(C c1, C c2) => false; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestNegativeDefiniteAssignment1() { await TestInRegularAndScript1Async( @"class C { string M(object o) { [|var|] x = o as string; if (x == null) return null; return x; } }", @"class C { string M(object o) { if (!(o is string x)) return null; return x; } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestNegativeDefiniteAssignment2() { await TestInRegularAndScript1Async( @"class C { string M(object o, bool b) { [|var|] x = o as string; if (((object)x == null) || b) { return null; } else { return x; } } }", @"class C { string M(object o, bool b) { if ((!(o is string x)) || b) { return null; } else { return x; } } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] [WorkItem(25993, "https://github.com/dotnet/roslyn/issues/25993")] public async Task TestEmbeddedStatement1() { await TestInRegularAndScript1Async( @"class C { void M(object e) { var fe = e as C; [|var|] ae = e as C; if (fe != null) { M(fe); // fe is used } else if (ae != null) { M(ae); // ae is used } } }", @"class C { void M(object e) { var fe = e as C; if (fe != null) { M(fe); // fe is used } else if (e is C ae) { M(ae); // ae is used } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] [WorkItem(25993, "https://github.com/dotnet/roslyn/issues/25993")] public async Task TestEmbeddedStatement2() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { var fe = e as C; [|var|] ae = e as C; if (fe != null) { M(ae); // ae is used } else if (ae != null) { M(ae); // ae is used } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestUseBeforeDeclaration() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|var|] c = e as C; { { var x1 = c; if (c != null) { } } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestPossiblyUnassigned() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|var|] c = e as C; { { if (c != null) { } var x2 = c; } // out of scope var x3 = c; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestOutOfScope() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|var|] c = e as C; { { if (c != null) { } } // out of scope var x3 = c; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDeclarationOnOuterBlock() { await TestInRegularAndScript1Async( @"class C { void M(object e) { [|var|] c = e as C; { { if (c != null) { } } } } }", @"class C { void M(object e) { { { if (e is C c) { } } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestConditionalExpression() { await TestInRegularAndScript1Async( @"class C { void M(object e) { [|var|] c = e as C; M(c != null ? c : null); } }", @"class C { void M(object e) { M(e is C c ? c : null); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestConditionalExpression_OppositeBranch() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|var|] c = e as C; M(c != null ? c : null, c); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_NoInlineTypeCheck() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|var|] c = e as C; for (;(c)!=null;) {} } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_InlineTypeCheck() { await TestInRegularAndScript1Async( @"class C { void M(object e) { [|C|] c; for (; !((c = e as C)==null);) { } } }", @"class C { void M(object e) { for (; !(!(e is C c));) { } } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_InScope() { await TestInRegularAndScript1Async( @"class C { void M(object e) { [|C|] c = null; for (; !((c = e as C)==null);) { M(c); } } }", @"class C { void M(object e) { for (; !(!(e is C c));) { M(c); } } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_NotAssignedBeforeAccess() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|C|] c = null; for (; ((c = e as C)==null);) { if (b) c = null; M(c); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_AssignedBeforeAccess() { await TestInRegularAndScript1Async( @"class C { void M(object e, bool b) { [|C|] c = null; for (; (c = e as C)==null;) { if (b) c = null; else c = null; M(c); } } }", @"class C { void M(object e, bool b) { for (; !(e is C c);) { if (b) c = null; else c = null; M(c); } } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_MultipleDeclarators() { await TestInRegularAndScript1Async( @"class C { void M(object e) { [|C|] c = null, x = null; for (; !((c = e as C)==null);) { M(c); } } }", @"class C { void M(object e) { C x = null; for (; !(!(e is C c));) { M(c); } } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_UseBeforeDeclaration() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|C|] c = null, x = c; for (; !((c = e as C)==null);) { M(c); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_Initializer() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|C|] c; for (var i = !((c = e as C)==null); i != null; ) { M(c); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestLocalFunction() { await TestInRegularAndScript1Async( @"class C { void M(object e) { [||]var c = e as C; C F() => c == null ? null : c; } }", @"class C { void M(object e) { C F() => !(e is C c) ? null : c; } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestLocalFunction_UseOutOfScope() { await TestMissingInRegularAndScriptAsync( @"class C { C M(object e) { [||]var c = e as C; C F() => c == null ? null : c; return c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestExpressionLambda() { await TestInRegularAndScript1Async( @"class C { void M(object e) { [||]var c = e as C; System.Func<C> f = () => c == null ? null : c; } }", @"class C { void M(object e) { System.Func<C> f = () => !(e is C c) ? null : c; } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestExpressionLambda_UseOutOfScope() { await TestMissingInRegularAndScriptAsync( @"class C { C M(object e) { [||]var c = e as C; System.Func<C> f = () => c == null ? null : c; return c; } }"); } [WorkItem(31388, "https://github.com/dotnet/roslyn/issues/31388")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestUseBetweenAssignmentAndIfCondition() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object o) { [|var|] c = o as C; M2(c != null); if (c == null) { return; } } void M2(bool b) { } }"); } [WorkItem(40007, "https://github.com/dotnet/roslyn/issues/40007")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestSpaceAfterGenericType() { await TestInRegularAndScript1Async( @"#nullable enable using System.Collections.Generic; class Program { static void Goo<TKey, TValue>(object items) { [|var|] itemsAsDictionary = items as IDictionary<TKey, TValue>; SortedDictionary<TKey, TValue>? dictionary = null; if (itemsAsDictionary != null) { dictionary = new SortedDictionary<TKey, TValue>(); } return dictionary; } }", @"#nullable enable using System.Collections.Generic; class Program { static void Goo<TKey, TValue>(object items) { SortedDictionary<TKey, TValue>? dictionary = null; if (items is IDictionary<TKey, TValue> itemsAsDictionary) { dictionary = new SortedDictionary<TKey, TValue>(); } return dictionary; } }"); } [WorkItem(45596, "https://github.com/dotnet/roslyn/issues/45596")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingInUsingDeclaration() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { using [|var|] x = o as IDisposable; if (x != null) { } } }"); } [WorkItem(45596, "https://github.com/dotnet/roslyn/issues/45596")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingInUsingStatement() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { using ([|var|] x = o as IDisposable) { if (x != 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UsePatternMatching; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternMatching { public partial class CSharpAsAndNullCheckTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public CSharpAsAndNullCheckTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpAsAndNullCheckDiagnosticAnalyzer(), new CSharpAsAndNullCheckCodeFixProvider()); [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] [InlineData("x != null", "o is string x")] [InlineData("null != x", "o is string x")] [InlineData("(object)x != null", "o is string x")] [InlineData("null != (object)x", "o is string x")] [InlineData("x is object", "o is string x")] [InlineData("x == null", "!(o is string x)")] [InlineData("null == x", "!(o is string x)")] [InlineData("(object)x == null", "!(o is string x)")] [InlineData("null == (object)x", "!(o is string x)")] [InlineData("x is null", "!(o is string x)")] [InlineData("(x = o as string) != null", "o is string x")] [InlineData("null != (x = o as string)", "o is string x")] [InlineData("(x = o as string) is object", "o is string x")] [InlineData("(x = o as string) == null", "!(o is string x)")] [InlineData("null == (x = o as string)", "!(o is string x)")] [InlineData("(x = o as string) is null", "!(o is string x)")] [InlineData("x == null", "o is not string x", LanguageVersion.CSharp9)] public async Task InlineTypeCheck1(string input, string output, LanguageVersion version = LanguageVersion.CSharp8) { await TestStatement($"if ({input}) {{ }}", $"if ({output}) {{ }}", version); await TestStatement($"var y = {input};", $"var y = {output};", version); await TestStatement($"return {input};", $"return {output};", version); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] [InlineData("(x = o as string) != null", "o is string x")] [InlineData("null != (x = o as string)", "o is string x")] [InlineData("(x = o as string) is object", "o is string x")] [InlineData("(x = o as string) == null", "!(o is string x)")] [InlineData("null == (x = o as string)", "!(o is string x)")] public async Task InlineTypeCheck2(string input, string output) => await TestStatement($"while ({input}) {{ }}", $"while ({output}) {{ }}"); private async Task TestStatement(string input, string output, LanguageVersion version = LanguageVersion.CSharp8) { await TestInRegularAndScript1Async( $@"class C {{ void M(object o) {{ [|var|] x = o as string; {input} }} }}", $@"class C {{ void M(object o) {{ {output} }} }}", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(version))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingInCSharp6() { await TestMissingAsync( @"class C { void M() { [|var|] x = o as string; if (x != null) { } } }", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingInWrongName() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|var|] y = o as string; if (x != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestInSwitchSection() { await TestInRegularAndScript1Async( @"class C { void M() { switch (o) { default: [|var|] x = o as string; if (x != null) { } } } }", @"class C { void M() { switch (o) { default: if (o is string x) { } } } }"); } [WorkItem(33345, "https://github.com/dotnet/roslyn/issues/33345")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestRemoveNewLinesInSwitchStatement() { await TestInRegularAndScript1Async( @"class C { void M() { switch (o) { default: [|var|] x = o as string; //a comment if (x != null) { } } } }", @"class C { void M() { switch (o) { default: //a comment if (o is string x) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingOnNonDeclaration() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|y|] = o as string; if (x != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] [WorkItem(25237, "https://github.com/dotnet/roslyn/issues/25237")] public async Task TestMissingOnReturnStatement() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|return;|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingOnIsExpression() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|var|] x = o is string; if (x != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task InlineTypeCheckComplexExpression1() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = (o ? z : w) as string; if (x != null) { } } }", @"class C { void M() { if ((o ? z : w) is string x) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestInlineTypeCheckWithElse() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; if (null != x) { } else { } } }", @"class C { void M() { if (o is string x) { } else { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestComments1() { await TestInRegularAndScript1Async( @"class C { void M() { // prefix comment [|var|] x = o as string; if (x != null) { } } }", @"class C { void M() { // prefix comment if (o is string x) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestComments2() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; // suffix comment if (x != null) { } } }", @"class C { void M() { // suffix comment if (o is string x) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestComments3() { await TestInRegularAndScript1Async( @"class C { void M() { // prefix comment [|var|] x = o as string; // suffix comment if (x != null) { } } }", @"class C { void M() { // prefix comment // suffix comment if (o is string x) { } } }"); } [WorkItem(33345, "https://github.com/dotnet/roslyn/issues/33345")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestRemoveNewLines() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; //suffix comment if (x != null) { } } }", @"class C { void M() { //suffix comment if (o is string x) { } } }"); } [WorkItem(33345, "https://github.com/dotnet/roslyn/issues/33345")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestRemoveNewLinesWhereBlankLineIsNotEmpty() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; //suffix comment if (x != null) { } } }", @"class C { void M() { //suffix comment if (o is string x) { } } }"); } [WorkItem(33345, "https://github.com/dotnet/roslyn/issues/33345")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestRemoveNewLines2() { await TestInRegularAndScript1Async( @"class C { void M() { int a = 0; [|var|] x = o as string; //suffix comment if (x != null) { } } }", @"class C { void M() { int a = 0; //suffix comment if (o is string x) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task InlineTypeCheckComplexCondition1() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; if (x != null ? 0 : 1) { } } }", @"class C { void M() { if (o is string x ? 0 : 1) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task InlineTypeCheckComplexCondition2() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; if ((x != null)) { } } }", @"class C { void M() { if ((o is string x)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task InlineTypeCheckComplexCondition3() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; if (x != null && x.Length > 0) { } } }", @"class C { void M() { if (o is string x && x.Length > 0) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDefiniteAssignment1() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|var|] x = o as string; if (x != null && x.Length > 0) { } else if (x != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDefiniteAssignment2() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|var|] x = o as string; if (x != null && x.Length > 0) { } Console.WriteLine(x); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDefiniteAssignment3() { await TestInRegularAndScript1Async( @"class C { void M() { [|var|] x = o as string; if (x != null && x.Length > 0) { } x = null; Console.WriteLine(x); } }", @"class C { void M() { if (o is string x && x.Length > 0) { } x = null; Console.WriteLine(x); } }"); } [WorkItem(21097, "https://github.com/dotnet/roslyn/issues/21097")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDefiniteAssignment4() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object o) { [|var|] s = o as string; if (s != null) { } else { if (o is int?) s = null; s.ToString(); } } }"); } [WorkItem(24286, "https://github.com/dotnet/roslyn/issues/24286")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDefiniteAssignment5() { await TestMissingInRegularAndScriptAsync( @"public class Test { public void TestIt(object o1, object o2) { [|var|] test = o1 as Test; if (test != null || o2 != null) { var o3 = test ?? o2; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDefiniteAssignment6() { await TestMissingInRegularAndScriptAsync( @"class C { string Use(string x) => x; void M() { [|var|] x = o as string; if (x != null && x.Length > 0) { } Console.WriteLine(x = Use(x)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDefiniteAssignment7() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|var|] x = o as string; if (x != null && x.Length > 0) { } Console.WriteLine(x); x = ""writeAfter""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] [WorkItem(28821, "https://github.com/dotnet/roslyn/issues/28821")] public async Task TestDefiniteAssignment8() { await TestMissingInRegularAndScriptAsync( @"class Program { static void Goo(System.Activator bar) { } static void Main(string[] args) { var a = new object(); [|var|] b = a as System.Activator; if ((b == null) && false) { } else { Goo(b); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] [WorkItem(28866, "https://github.com/dotnet/roslyn/issues/28866")] public async Task TestWrittenExpressionBeforeNullCheck() { await TestMissingInRegularAndScriptAsync( @"class Goo { object Data { get; set; } void DoGoo() { [|var|] oldData = this.Data as string; Data = null; if (oldData != null) { // Do something } } }"); } [WorkItem(15957, "https://github.com/dotnet/roslyn/issues/15957")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestTrivia1() { await TestInRegularAndScript1Async( @"class C { void M(object y) { if (y != null) { } [|var|] x = o as string; if (x != null) { } } }", @"class C { void M(object y) { if (y != null) { } if (o is string x) { } } }"); } [WorkItem(17129, "https://github.com/dotnet/roslyn/issues/17129")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestTrivia2() { await TestInRegularAndScript1Async( @"using System; namespace N { class Program { public static void Main() { object o = null; int i = 0; [|var|] s = o as string; if (s != null && i == 0 && i == 1 && i == 2 && i == 3 && i == 4 && i == 5) { Console.WriteLine(); } } } }", @"using System; namespace N { class Program { public static void Main() { object o = null; int i = 0; if (o is string s && i == 0 && i == 1 && i == 2 && i == 3 && i == 4 && i == 5) { Console.WriteLine(); } } } }"); } [WorkItem(17122, "https://github.com/dotnet/roslyn/issues/17122")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingOnNullableType() { await TestMissingInRegularAndScriptAsync( @"using System; namespace N { class Program { public static void Main() { object o = null; [|var|] i = o as int?; if (i != null) Console.WriteLine(i); } } }"); } [WorkItem(18053, "https://github.com/dotnet/roslyn/issues/18053")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingWhenTypesDoNotMatch() { await TestMissingInRegularAndScriptAsync( @"class SyntaxNode { public SyntaxNode Parent; } class BaseParameterListSyntax : SyntaxNode { } class ParameterSyntax : SyntaxNode { } public static class C { static void M(ParameterSyntax parameter) { [|SyntaxNode|] parent = parameter.Parent as BaseParameterListSyntax; if (parent != null) { parent = parent.Parent; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingOnWhileNoInline() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object o) { [|string|] x = o as string; while (x != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestWhileDefiniteAssignment1() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object o) { [|string|] x; while ((x = o as string) != null) { } var readAfterWhile = x; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestWhileDefiniteAssignment2() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object o) { [|string|] x; while ((x = o as string) != null) { } x = ""writeAfterWhile""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestWhileDefiniteAssignment3() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object o) { [|string|] x; x = ""writeBeforeWhile""; while ((x = o as string) != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestWhileDefiniteAssignment4() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object o) { [|string|] x = null; var readBeforeWhile = x; while ((x = o as string) != null) { } } }"); } [WorkItem(23504, "https://github.com/dotnet/roslyn/issues/23504")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task DoNotChangeOriginalFormatting1() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { object obj = ""test""; [|var|] str = obj as string; var title = str != null ? str : ""; } }", @"class Program { static void Main(string[] args) { object obj = ""test""; var title = obj is string str ? str : ""; } }"); } [WorkItem(23504, "https://github.com/dotnet/roslyn/issues/23504")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task DoNotChangeOriginalFormatting2() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { object obj = ""test""; [|var|] str = obj as string; var title = str != null ? str : ""; } }", @"class Program { static void Main(string[] args) { object obj = ""test""; var title = obj is string str ? str : ""; } }"); } [WorkItem(21172, "https://github.com/dotnet/roslyn/issues/21172")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingWithDynamic() { await TestMissingAsync( @"class C { void M(object o) { [|var|] x = o as dynamic; if (x != null) { } } }"); } [WorkItem(21551, "https://github.com/dotnet/roslyn/issues/21551")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestOverloadedUserOperator() { await TestMissingAsync( @"class C { public static void Main() { object o = new C(); [|var|] c = o as C; if (c != null) System.Console.WriteLine(); } public static bool operator ==(C c1, C c2) => false; public static bool operator !=(C c1, C c2) => false; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestNegativeDefiniteAssignment1() { await TestInRegularAndScript1Async( @"class C { string M(object o) { [|var|] x = o as string; if (x == null) return null; return x; } }", @"class C { string M(object o) { if (!(o is string x)) return null; return x; } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestNegativeDefiniteAssignment2() { await TestInRegularAndScript1Async( @"class C { string M(object o, bool b) { [|var|] x = o as string; if (((object)x == null) || b) { return null; } else { return x; } } }", @"class C { string M(object o, bool b) { if ((!(o is string x)) || b) { return null; } else { return x; } } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] [WorkItem(25993, "https://github.com/dotnet/roslyn/issues/25993")] public async Task TestEmbeddedStatement1() { await TestInRegularAndScript1Async( @"class C { void M(object e) { var fe = e as C; [|var|] ae = e as C; if (fe != null) { M(fe); // fe is used } else if (ae != null) { M(ae); // ae is used } } }", @"class C { void M(object e) { var fe = e as C; if (fe != null) { M(fe); // fe is used } else if (e is C ae) { M(ae); // ae is used } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] [WorkItem(25993, "https://github.com/dotnet/roslyn/issues/25993")] public async Task TestEmbeddedStatement2() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { var fe = e as C; [|var|] ae = e as C; if (fe != null) { M(ae); // ae is used } else if (ae != null) { M(ae); // ae is used } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestUseBeforeDeclaration() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|var|] c = e as C; { { var x1 = c; if (c != null) { } } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestPossiblyUnassigned() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|var|] c = e as C; { { if (c != null) { } var x2 = c; } // out of scope var x3 = c; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestOutOfScope() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|var|] c = e as C; { { if (c != null) { } } // out of scope var x3 = c; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestDeclarationOnOuterBlock() { await TestInRegularAndScript1Async( @"class C { void M(object e) { [|var|] c = e as C; { { if (c != null) { } } } } }", @"class C { void M(object e) { { { if (e is C c) { } } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestConditionalExpression() { await TestInRegularAndScript1Async( @"class C { void M(object e) { [|var|] c = e as C; M(c != null ? c : null); } }", @"class C { void M(object e) { M(e is C c ? c : null); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestConditionalExpression_OppositeBranch() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|var|] c = e as C; M(c != null ? c : null, c); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_NoInlineTypeCheck() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|var|] c = e as C; for (;(c)!=null;) {} } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_InlineTypeCheck() { await TestInRegularAndScript1Async( @"class C { void M(object e) { [|C|] c; for (; !((c = e as C)==null);) { } } }", @"class C { void M(object e) { for (; !(!(e is C c));) { } } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_InScope() { await TestInRegularAndScript1Async( @"class C { void M(object e) { [|C|] c = null; for (; !((c = e as C)==null);) { M(c); } } }", @"class C { void M(object e) { for (; !(!(e is C c));) { M(c); } } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_NotAssignedBeforeAccess() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|C|] c = null; for (; ((c = e as C)==null);) { if (b) c = null; M(c); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_AssignedBeforeAccess() { await TestInRegularAndScript1Async( @"class C { void M(object e, bool b) { [|C|] c = null; for (; (c = e as C)==null;) { if (b) c = null; else c = null; M(c); } } }", @"class C { void M(object e, bool b) { for (; !(e is C c);) { if (b) c = null; else c = null; M(c); } } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_MultipleDeclarators() { await TestInRegularAndScript1Async( @"class C { void M(object e) { [|C|] c = null, x = null; for (; !((c = e as C)==null);) { M(c); } } }", @"class C { void M(object e) { C x = null; for (; !(!(e is C c));) { M(c); } } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_UseBeforeDeclaration() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|C|] c = null, x = c; for (; !((c = e as C)==null);) { M(c); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestForStatement_Initializer() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object e) { [|C|] c; for (var i = !((c = e as C)==null); i != null; ) { M(c); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestLocalFunction() { await TestInRegularAndScript1Async( @"class C { void M(object e) { [||]var c = e as C; C F() => c == null ? null : c; } }", @"class C { void M(object e) { C F() => !(e is C c) ? null : c; } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestLocalFunction_UseOutOfScope() { await TestMissingInRegularAndScriptAsync( @"class C { C M(object e) { [||]var c = e as C; C F() => c == null ? null : c; return c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestExpressionLambda() { await TestInRegularAndScript1Async( @"class C { void M(object e) { [||]var c = e as C; System.Func<C> f = () => c == null ? null : c; } }", @"class C { void M(object e) { System.Func<C> f = () => !(e is C c) ? null : c; } }", parameters: new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestExpressionLambda_UseOutOfScope() { await TestMissingInRegularAndScriptAsync( @"class C { C M(object e) { [||]var c = e as C; System.Func<C> f = () => c == null ? null : c; return c; } }"); } [WorkItem(31388, "https://github.com/dotnet/roslyn/issues/31388")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestUseBetweenAssignmentAndIfCondition() { await TestMissingInRegularAndScriptAsync( @"class C { void M(object o) { [|var|] c = o as C; M2(c != null); if (c == null) { return; } } void M2(bool b) { } }"); } [WorkItem(40007, "https://github.com/dotnet/roslyn/issues/40007")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestSpaceAfterGenericType() { await TestInRegularAndScript1Async( @"#nullable enable using System.Collections.Generic; class Program { static void Goo<TKey, TValue>(object items) { [|var|] itemsAsDictionary = items as IDictionary<TKey, TValue>; SortedDictionary<TKey, TValue>? dictionary = null; if (itemsAsDictionary != null) { dictionary = new SortedDictionary<TKey, TValue>(); } return dictionary; } }", @"#nullable enable using System.Collections.Generic; class Program { static void Goo<TKey, TValue>(object items) { SortedDictionary<TKey, TValue>? dictionary = null; if (items is IDictionary<TKey, TValue> itemsAsDictionary) { dictionary = new SortedDictionary<TKey, TValue>(); } return dictionary; } }"); } [WorkItem(45596, "https://github.com/dotnet/roslyn/issues/45596")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingInUsingDeclaration() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { using [|var|] x = o as IDisposable; if (x != null) { } } }"); } [WorkItem(45596, "https://github.com/dotnet/roslyn/issues/45596")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)] public async Task TestMissingInUsingStatement() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { using ([|var|] x = o as IDisposable) { if (x != null) { } } } }"); } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Compilers/CSharp/Test/Semantic/Semantics/NameCollisionTests.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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; // The way the specification describes, and the way the native compiler reports name // collision errors is inconsistent and confusing. In Roslyn we will implement // the following more rational behaviors: // // ------------------ // // These two error messages are to be reworded: // // CS0135: (ERR_NameIllegallyOverrides) // // Original: 'X' conflicts with the declaration 'C.X' // // New: A local, parameter or range variable named 'X' cannot be declared in this scope // because that name is used in an enclosing local scope to refer to 'C.X'. // // CS0136: (ERR_LocalIllegallyOverrides) // // Original: A local variable named 'X' cannot be declared in this scope // because it would give a different meaning to 'X', which is // already used in a 'parent or current' / 'child' // scope to denote something else // // New: A local or parameter named 'X' cannot be declared in this scope // because that name is used in an enclosing local scope to define // a local or parameter. // // Note now the error messages are now nicely parallel, and much more clear about // precisely which rule has been violated. // // The rules for what error to report in each name collision scenario are as follows: // // --------------------------- // // Errors for simple names being used to refer to a member in one place and a declared // entity in another: // // CS0135: (ERR_NameIllegallyOverrides) // A local, parameter or range variable cannot be named 'X' because // that name is used in an enclosing local scope to refer to 'C.X'. // // Reported *only* when there is a local variable, local constant, lambda parameter or range variable // that would change the meaning of a *simple name* in an *expression* in an enclosing declaration // space to refer to a member, namespace, type, type parameter etc. Report it on the *inner* usage, // never the "outer" usage. eg: // // class C { int x; void M() { int y = x; { int x = y; } } } // // --------------------------- // // Errors for a local being used before it is defined: // // CS0841: (ERR_VariableUsedBeforeDeclaration) // Cannot use local variable 'X' before it is declared // // Reported when a local variable is used before it is declared, and the offending // usage was probably not intended to refer to a field. eg: // // class C { void M() { int y = x; int x; } } // // CS0844: (ERR_VariableUsedBeforeDeclarationAndHidesField) // Cannot use local variable 'X' before it is declared. The // declaration of the local variable hides the field 'C.X'. // // Reported if the offending usage might have been intended to refer to a field, eg: // // class C { int x; void M() { int y = x; int x; } } // // --------------------------- // // Errors for two of the same identifier being used to declare two different // things in overlapping or identical declaration spaces: // // CS0100: (ERR_DuplicateParamName) // The parameter name 'x' is a duplicate // // Reported when one parameter list contains two identically-named parameters. Eg: // // void M(int x, int x) {} or (x, x)=>{} // // CS0128: (ERR_LocalDuplicate) // A local variable named 'x' is already defined in this scope // // Reported *only* when there are two local variables or constants defined in the // *exact* same declaration space with the same name. eg: // // void M() { int x; int x; } // // CS0136: (ERR_LocalIllegallyOverrides) // New: A local or parameter named 'X' cannot be declared in this scope // because that name is used in an enclosing local scope to define // a local or parameter. // // Reported *only* when there is a local variable, local constant or lambda parameter // but NOT range variable that shadows a local variable, local constant, formal parameter, // range variable, or lambda parameter that was declared in an enclosing local declaration space. Again, // report it on the inner usage. eg: // // void M() { int y; { int y; } } // // CS0412: (ERR_LocalSameNameAsTypeParam) // 'X': a parameter or local variable cannot have the same name as a method type parameter // // Reported *only* when a local variable, local constant, formal parameter or lambda parameter // has the same name as a method type parameter. eg: // // void M<X>(){ int X; } // // CS1948: (ERR_QueryRangeVariableSameAsTypeParam) // The range variable 'X' cannot have the same name as a method type parameter // // Reported *only* when a range variable has the same name as a method type parameter. eg: // // void M<X>(){ var q = from X in z select X; } // // CS1930: (ERR_QueryDuplicateRangeVariable) // The range variable 'x' has already been declared // // Reported *only* if a range variable shadows another range variable that is in scope. eg: // // from x in y from x in z select q // // CS1931: (ERR_QueryRangeVariableOverrides) // The range variable 'x' conflicts with a previous declaration of 'x' // // Reported when there is a range variable that shadows a non-range variable from an // enclosing scope. eg: // // int x; var y = from x in q select m; // namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class NameCollisionTests : CompilingTestBase { [Fact] public void TestNamesFromTypeAndExpressionContextsDontCollide() { var source = @" using name1 = System.Exception; namespace Namespace { using name3 = System.Type; class Class { Class(name2 other1, name1 other2) { name3 other3 = typeof(name1); if (typeof(name1) != typeof(name2) || typeof(name2) is name3 || typeof(name1) is name3) { foreach (var name1 in ""string"") { for (var name2 = 1; name2 > --name2; name2++) { int name3 = name2; } } } else { name2 name1 = null, name2 = name1; name3 name3 = typeof(name2); } } } } class name2 { }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestLocalAndLabelDontCollide() { var source = @" using System; namespace Namespace { using name1 = System.Type; class Class { Class(name1 name1) { goto name2; name2: Console.WriteLine(); var name2 = new name2(); goto name1; name1: Console.WriteLine(); } } } class name2 { }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLabelWithLabel() { var source = @" using System; namespace Namespace { using name1 = System.Type; class Class { Class(name1 name1) { goto name1; name1: Console.WriteLine(); { goto name1; name1: Console.WriteLine(); var name2 = new name2(); goto name2; name2: Console.WriteLine(); } goto name2; name2: Console.WriteLine(); } internal int Property { set { goto name1; name1: Console.WriteLine(); Action lambda1 = () => { Action lambda2 = () => { goto name1; name1: Console.WriteLine(); var name2 = new name2(); goto name2; name2: Console.WriteLine(); }; goto name2; name2: Console.WriteLine(); }; } } } } class name2 { }"; CreateCompilation(source).VerifyDiagnostics( // (14,13): error CS0158: The label 'name1' shadows another label by the same name in a contained scope // name1: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name1").WithArguments("name1"), // (17,13): error CS0158: The label 'name2' shadows another label by the same name in a contained scope // name2: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name2").WithArguments("name2"), // (34,21): error CS0158: The label 'name1' shadows another label by the same name in a contained scope // name1: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name1").WithArguments("name1"), // (37,21): error CS0158: The label 'name2' shadows another label by the same name in a contained scope // name2: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name2").WithArguments("name2")); } [Fact] public void TestCollisionOfLocalWithTypeOrMethodOrProperty_LegalCases() { var source = @" using System; namespace name1 { class Class { void name1() { { name1(); } { int name1 = name1 = 1; } foreach(var name1 in ""string"") ; } } } class name2 { Action lambda = () => { { int name2 = name2 = 2; Console.WriteLine(name3); } { int name3 = name3 = 3; } }; static int name3 { get { return 4; } } }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithType() { var source = @" using name1 = System.Console; class Class { Class() { { name1.WriteLine(); // Legal name2.Equals(null, null); // Legal } { int name1 = (name1 = 1), name2 = name2 = 2; // Legal -- strange, but legal } { name1.WriteLine(); name2.Equals(null, null); { int name1 = 3, name2 = name1; // 0135 on name1, name2 // Native compiler reports 0136 here; Roslyn reports 0135. } } } } class name2 { }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithMethodOrProperty() { var source = @" using System; namespace name1 { class Class { void name1() { name1(); { name1(); } { int name1 = name1 = 1; // 0135: Roslyn reports 0135, native reports 0136. } foreach (var name1 in ""string"") ; // 0135: Roslyn reports 0135, native reports 0136. } Action lambda = () => { { int name2 = name2 = 2; // 0135: conflicts with usage of name2 as the static property below. // Roslyn reports this here; native compiler reports it below. Console.WriteLine(name2); } Console.WriteLine(name2); // Native compiler reports 0135 here; Roslyn reports it above. }; static int name2 { get { return 3; } } } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void TestCollisionOfDelegateWithConst() { var source = @"class A { delegate void D(); static void Goo() { } class B { const int Goo = 123; static void Main() { Goo(); Bar(Goo); } static void Main2() { Bar(Goo); Goo(); } static void Bar(int x) { } static void Bar(D x) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithTypeParameter() { var source = @" class Class<name1, name2> { void Method<name3, name4>(name1 other1, name4 name4) // 0412 on name4 { { int name3 = 10; // 0412 on name3 System.Console.WriteLine(name3); // Eliminate warning foreach (var name2 in ""string"") { for (var name1 = 1; name1 <= name1++; name1++) // legal; name1 conflicts with a class type parameter which is not in the local variable decl space name1 = name2.GetHashCode(); } } { name1 other2 = typeof(name1) is name1 ? other1 : other1; // no error; all the name1's refer to the type, not the local. int name1 = (name1 = 2), name2 = name2 = 3; // legal; name1 conflicts with a class type parameter which is not in the local variable decl space foreach (var name3 in ""string"") // 0412 on name3 { System.Console.WriteLine(name3); // Eliminate warning for (var name4 = 4; ; ) // 0412 on name4 { name1 = name2.GetHashCode(); System.Console.WriteLine(name4); // Eliminate warning } } try {} catch(System.Exception name3) // 0412 on name3 { System.Console.WriteLine(name3); } } } }"; CreateCompilation(source).VerifyDiagnostics( // (4,51): error CS0412: 'name4': a parameter or local variable cannot have the same name as a method type parameter // void Method<name3, name4>(name1 other1, name4 name4) // 0412 on name4 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name4").WithArguments("name4").WithLocation(4, 51), // (7,17): error CS0412: 'name3': a parameter or local variable cannot have the same name as a method type parameter // int name3 = 10; // 0412 on name3 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name3").WithArguments("name3").WithLocation(7, 17), // (18,26): error CS0412: 'name3': a parameter or local variable cannot have the same name as a method type parameter // foreach (var name3 in "string") // 0412 on name3 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name3").WithArguments("name3").WithLocation(18, 26), // (21,26): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (var name4 = 4; ; ) // 0412 on name4 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4"), // (28,36): error CS0412: 'name3': a parameter or local variable cannot have the same name as a method type parameter // catch(System.Exception name3) // 0412 on name3 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name3").WithArguments("name3")); } [Fact] public void TestCollisionOfLocalWithField_LegalCases() { var source = @" partial class Derived : Base { private Derived() { this.name1 = 1; long name1 = this.name1; if (true) { name1 = this.name1 = name1; name2 = this.name2 = name2 + name1; } { while (name1 == 1) { long name2 = 2; name1 = name2; } do { long name2 = 3; name1 = name2; name1 = this.name1; } while (name1 != 1); } } } class Base { public long name2 = name1; private static int name1 = 4; } partial class Derived { internal long name1 = 5; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithField1() { var source = @" class Derived : Base { static long name1 = 1; static Derived() { while(name1 == 2) { int name1 = 3, other = name1, name2 = other; // 0135 on name1 and name2 // Native reports 0136 on name1 here and 0135 on name2 below. } do { } while (name2 == 4); // Native reports 0135 on name2 here; Roslyn reports it above. } } class Base { protected static long name2 = 5; }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithField2() { var source = @" class Class { public static int M() { return 1; } internal int Property { set { for (int i = 0; i < int.MaxValue; ++i) { if (i == 0) { int other = M(), name = M(), name = other; // 0128, 0135 } else { { int name = M(); name = M(); // 0135 } } } for (int i = 0; i > int.MinValue; ++i) { { i += 1; } } name = M(); } } private const int x = 123; private void M1(int x = x) {} // UNDONE: Native and Roslyn compilers both allow this; should they? private void M2(int y = x) { int x = M(); // UNDONE: Native and Roslyn compilers both allow this; should they? } private long other = 0, name = 6; }"; CreateCompilation(source).VerifyDiagnostics( // (13,50): error CS0128: A local variable named 'name' is already defined in this scope // int other = M(), name = M(), name = other; // 0128, 0135 Diagnostic(ErrorCode.ERR_LocalDuplicate, "name").WithArguments("name"), // (37,18): warning CS0414: The field 'Class.other' is assigned but its value is never used // private long other = 0, name = 6; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "other").WithArguments("Class.other") ); } [Fact] public void TestCollisionInsideFieldDeclaration() { // A close reading of the spec would indicate that this is not an error because the // offending simple name 'x' does not appear in any local variable declaration space. // A field initializer is not a declaration space. However, it seems plausible // that we want to report the error here. The native compiler does so as well. var source = @" class Class { private static int M() { return 1; } private static int x = 123; private static int z = x + ((System.Func<int>)( ()=>{ int x = M(); return x; } ))(); }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithField_PartialType() { var source = @" partial struct PartialStruct { private void Method() { if (true) { { int name = 1, other = name; } } name = 2; // Native compiler reports 0135 here; Roslyn no longer reports 0135. } } partial struct PartialStruct { internal long name; }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal_LegalCases1() { var source = @" partial class Derived : Base { private string Property { get { if (true) { int name = (name = 1); name += name; } { { int name = 2; name -= name; } } for(long name = 3; name <= 4; ++name) name += 5; foreach(var name in ""string"") { name.ToString(); } return this.name; } } } class Base { public string name = null; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal_LegalCases2() { var source = @" using System; using System.Linq; partial class Derived : Base { private string Property { get { // http://blogs.msdn.com/b/ericlippert/archive/2009/11/02/simple-names-are-not-so-simple.aspx foreach (var name in from name in ""string"" orderby name select name) Console.WriteLine(name); return this.name; } } } class Base { public string name = null; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal_LegalCases3() { var source = @" using System; using System.Linq; partial class Derived : Base { private string Property { get { // http://blogs.msdn.com/b/ericlippert/archive/2009/11/02/simple-names-are-not-so-simple.aspx foreach(var name in ""string"".OrderBy(name => name).Select(name => name)) { Console.WriteLine(name); } return this.name; } } } class Base { public string name = null; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal() { var source = @" class Class { public Class() { long name1 = 1; System.Console.WriteLine(name1); // Eliminate unused warning. name4 = name6; // 0841 on name4; used before declared. 0103 on name6; not defined in this context if (true) { { int other1 = 2, name1 = other1, name2 = name1; // 0136 on name1; already used in parent scope to mean something else. } // Native compiler reports 0136 on 'long name2' below; Roslyn reports it on 'int ... name2' here and 'var name2' below { if (true) { for (long name1 = this.name2; name1 >= --name1; name1++) // 0136 on name1; { name1.ToString(); name5.ToString(); // 0841: name5 is used before the declaration string name6 = ""string""; } } foreach (var name2 in ""string"") name2.ToString(); // 0136: Native reports this on 'long name2' below; Roslyn reports it here, and above. } string @name3 = ""string"", other2 = name3, name3 = other2; // 0128: name3 is defined twice. long @name2 = 3; System.Console.WriteLine(@name2); // eliminated unused warning. // Native compiler reports 0136 on 'long name2' here; Roslyn reports it on 'int ... name2' above. } string name4 = ""string"", name5 = name4; name6 = name3; // 0103 on both name6 and name3; not defined in this context. } public long name2 = 4; }"; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0841: Cannot use local variable 'name4' before it is declared // name4 = name6; // 0841 on name4; used before declared. 0103 on name6; not defined in this context Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name4").WithArguments("name4").WithLocation(7, 9), // (7,17): error CS0103: The name 'name6' does not exist in the current context // name4 = name6; // 0841 on name4; used before declared. 0103 on name6; not defined in this context Diagnostic(ErrorCode.ERR_NameNotInContext, "name6").WithArguments("name6").WithLocation(7, 17), // (11,33): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int other1 = 2, name1 = other1, name2 = name1; // 0136 on name1; already used in parent scope to mean something else. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(11, 33), // (11,49): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int other1 = 2, name1 = other1, name2 = name1; // 0136 on name1; already used in parent scope to mean something else. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(11, 49), // (16,31): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (long name1 = this.name2; name1 >= --name1; name1++) // 0136 on name1; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(16, 31), // (18,43): error CS0841: Cannot use local variable 'name5' before it is declared // name1.ToString(); name5.ToString(); // 0841: name5 is used before the declaration Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name5").WithArguments("name5").WithLocation(18, 43), // (22,30): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") name2.ToString(); // 0136: Native reports this on 'long name2' below; Roslyn reports it here, and above. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(22, 30), // (24,55): error CS0128: A local variable named 'name3' is already defined in this scope // string @name3 = "string", other2 = name3, name3 = other2; // 0128: name3 is defined twice. Diagnostic(ErrorCode.ERR_LocalDuplicate, "name3").WithArguments("name3").WithLocation(24, 55), // (29,9): error CS0103: The name 'name6' does not exist in the current context // name6 = name3; // 0103 on both name6 and name3; not defined in this context. Diagnostic(ErrorCode.ERR_NameNotInContext, "name6").WithArguments("name6").WithLocation(29, 9), // (29,17): error CS0103: The name 'name3' does not exist in the current context // name6 = name3; // 0103 on both name6 and name3; not defined in this context. Diagnostic(ErrorCode.ERR_NameNotInContext, "name3").WithArguments("name3").WithLocation(29, 17), // (19,32): warning CS0219: The variable 'name6' is assigned but its value is never used // string name6 = "string"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name6").WithArguments("name6").WithLocation(19, 32) ); } [Fact] public void TestCollisionOfLocalWithParam() { var source = @" using System; class Class { public Func<int, int, int> Method(int name1, int name2) { foreach (var name1 in ""string"") // 0136 { foreach (var name2 in ""string"") // 0136 { int name1 = name2.GetHashCode(); // 0136 } } Action<int> lambda = (name3) => { int name1 = 1; // 0136 if(name1 == 2) { name2 = name3 = name1; } else { int name2 = 3; // 0136 System.Console.WriteLine(name2); { int name3 = 2; // 0136 System.Console.WriteLine(name3); } } }; return (name1, name2) => name1; // 0136 on both name1 and name2 } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,22): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name1 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(7, 22), // (9,26): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(9, 26), // (11,21): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = name2.GetHashCode(); // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(11, 21), // (17,17): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = 1; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(17, 17), // (24,21): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name2 = 3; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(24, 21), // (27,25): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 2; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 25), // (32,17): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return (name1, name2) => name1; // 0136 on both name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(32, 17), // (32,24): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return (name1, name2) => name1; // 0136 on both name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(32, 24) ); CreateCompilation(source).VerifyDiagnostics( // (7,22): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name1 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(7, 22), // (9,26): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(9, 26), // (11,21): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = name2.GetHashCode(); // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(11, 21), // (27,25): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 2; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 25) ); } [Fact] public void TestCollisionOfParamWithParam() { var source = @" using System; class Class { public static void Method(int name1, int name2, int name2) // 0100 on name2 { Action<int, int> lambda = (other, name3) => { Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 { }; }; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (5,57): error CS0100: The parameter name 'name2' is a duplicate // public static void Method(int name1, int name2, int name2) // 0100 on name2 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name2").WithArguments("name2").WithLocation(5, 57), // (9,56): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(9, 56), // (9,70): error CS0100: The parameter name 'name4' is a duplicate // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name4").WithArguments("name4").WithLocation(9, 70), // (9,77): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(9, 77) ); CreateCompilation(source).VerifyDiagnostics( // (5,57): error CS0100: The parameter name 'name2' is a duplicate // public static void Method(int name1, int name2, int name2) // 0100 on name2 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name2").WithArguments("name2").WithLocation(5, 57), // (9,70): error CS0100: The parameter name 'name4' is a duplicate // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name4").WithArguments("name4").WithLocation(9, 70) ); } [WorkItem(930252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930252")] [Fact] public void TestCollisionOfParamWithParam1() { var source = @" class Program { delegate int D(int x, int y); static void X() { D d1 = (int x, int x) => { return 1; }; D d2 = (x, x) => { return 1; }; } }"; CreateCompilation(source).VerifyDiagnostics( // (7,28): error CS0100: The parameter name 'x' is a duplicate // D d1 = (int x, int x) => { return 1; }; Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x").WithLocation(7, 28), // (8,20): error CS0100: The parameter name 'x' is a duplicate // D d2 = (x, x) => { return 1; }; Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x").WithLocation(8, 20) ); } [Fact] public void TestCollisionInsideLambda_LegalCases() { var source = @" using System; partial class Class { private string Property { set { this. Method((name1) => { name1 = string.Empty; for (int name2 = name2 = 1; ; ) ; }). Method((name1) => name1.ToString()). Method((name1) => { foreach (var name2 in string.Empty) ; return name1; }); } } Class Method(Action<string> name1) { return null; } Class Method(Func<string, string> name1) { return null; } }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideLambda1() { var source = @" using System; class Derived : Base { static int M() { return 1; } static long name1 = 1; Action lambda = () => { name1 = 2; { int name1 = 3, other = name1, name2 = other; // 0135: on name1 and name2. // Native compiler reports 0136 here on name1 and 0135 on name2 below. // Roslyn reports them both as 0135 here. } name2 = 4; // Native compiler reports 0135 here; Roslyn reports above. int name3 = M(); { { name3 = 6; } if (true) { int name3 = M(); // 0136: Native compiler says 0135, Roslyn says 0136. The conflict is with the other local. } } }; Action anonMethod = delegate() { name1 = 8; if (true) { int name1 = 9, other = name1, name2 = other; // 0135: on name1, name2 // Native compiler reports 0136 on name1, Roslyn reports 0135. // Native compiler reports 0135 on name2 below, Roslyn reports it here. } { foreach (var name3 in ""string"") name3.ToString(); // 0136: Native compiler reports 0136 below, Roslyn reports it here. } name2 = 10; // Native compiler reports 0135 here; Roslyn reports it above. int name3 = M(); }; } class Base { protected static long name2 = 12; }"; CreateCompilation(source).VerifyDiagnostics( // (24,21): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = M(); // 0136: Native compiler says 0135, Roslyn says 0136. The conflict is with the other local. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(24, 21), // (39,26): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name3 in "string") name3.ToString(); // 0136: Native compiler reports 0136 below, Roslyn reports it here. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(39, 26), // (6,17): warning CS0414: The field 'Derived.name1' is assigned but its value is never used // static long name1 = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "name1").WithArguments("Derived.name1").WithLocation(6, 17) ); } [Fact] public void TestCollisionInsideLambda2() { var source = @" using System; class Class { void Method(Action lambda) { } void Method() { const long name1 = 1; System.Console.WriteLine(name1); // Eliminate warning. Method(() => { Console.WriteLine(name1); { const int name1 = 2; // 0136 int other = name1, name2 = other; // 0136: Native compiler reports this on 'const long name' below; Roslyn reports it here. } name2 = 3; // 0841: local used before declared const int name3 = 4; { { Console.WriteLine(name3); } if (true) { const int name3 = 5; // 0136 Console.WriteLine(name3); } } }); Method(delegate() { Console.WriteLine(name1); if (true) { const int name1 = 6, other = name1, name2 = other; // 0136 on name1 and name2 Console.WriteLine(name1 + other + name2); } // Roslyn reports 0136 on name2 above; native compiler reports it on 'const long name2' below. { foreach (var name3 in ""string"") name3.ToString(); // 0136: Roslyn reports this here, native reports it below. } Console.WriteLine(name2); // 0814: local used before declared const int name3 = 7; // Native compiler reports 0136 here, Roslyn reports it on 'var name3' above. Console.WriteLine(name3); // eliminate warning }); const long name2 = 8; // Native compiler reports 0136 here; Roslyn reports it on both offending nested decls above. Console.WriteLine(name2); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (15,27): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = 2; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(15, 27), // (16,36): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int other = name1, name2 = other; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(16, 36), // (18,13): error CS0841: Cannot use local variable 'name2' before it is declared // name2 = 3; // 0841: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(18, 13), // (27,31): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name3 = 5; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 31), // (38,27): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = 6, other = name1, name2 = other; // 0136 on name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(38, 27), // (38,53): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = 6, other = name1, name2 = other; // 0136 on name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(38, 53), // (42,30): error CS0841: Cannot use local variable 'name3' before it is declared // foreach (var name3 in ""string"") name3.ToString(); // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(42, 30), // (44,31): error CS0841: Cannot use local variable 'name2' before it is declared // Console.WriteLine(name2); // 0814: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(44, 31)); CreateCompilation(source).VerifyDiagnostics( // (18,13): error CS0841: Cannot use local variable 'name2' before it is declared // name2 = 3; // 0841: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(18, 13), // (27,31): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name3 = 5; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 31), // (42,30): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name3 in "string") name3.ToString(); // 0136: Roslyn reports this here, native reports it below. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(42, 30), // (44,31): error CS0841: Cannot use local variable 'name2' before it is declared // Console.WriteLine(name2); // 0814: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(44, 31)); } [Fact] public void TestCollisionInsideOperator() { var source = @" using System; class Class { static long name1 = 1; public static Class operator +(Class name1, Class other) { var lambda = (Action)(() => { const int name1 = @name2; // 0136 on name1 because it conflicts with parameter if (true) { int name2 = name1; // 0135 because name2 conflicts with usage of name2 as Class.name2 above Console.WriteLine(name2); } }); return other; } const int name2 = 2; public static void Other() { Console.WriteLine(name1); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (10,23): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = @name2; // 0136 on name1 because it conflicts with parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(10, 23)); CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideIndexer() { var source = @" class Class { static long name1 = 1; public int this[int name1] { get { foreach (var name2 in ""string"") { foreach (var name2 in ""string"") // 0136 on name2 { int name1 = name2.GetHashCode(); // 0136 on name1 } } return name1; } } static long name2 = name1 + name2; }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (11,30): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") // 0136 on name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2"), // (13,25): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = name2.GetHashCode(); // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1")); } [Fact] public void TestCollisionInsideFor1() { var source = @" class Class { void Method1(int name4 = 1, params int[] name5) { for (int name1 = 2; name1 <= name1++; ++name1) { foreach (var name2 in ""string"") { for (name1 = 3; ; ) { break; } for (int name2 = name1; name2 <= name2++; ++name2) // 0136 on name2 { int name3 = 4, name4 = 5, name5 = 6; // 0136 on name3, name4 and name5 // Native compiler reports 0136 on name3 below, Roslyn reports it above. System.Console.WriteLine(name3 + name4 + name5); // Eliminate warning } } foreach (var name1 in ""string"") ; // 0136 on name1 } int name3 = 7; // Native compiler reports 0136 on name3 here; Roslyn reports it above. System.Console.WriteLine(name3); // Eliminate warning } }"; CreateCompilation(source).VerifyDiagnostics( // (11,26): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (int name2 = name1; name2 <= name2++; ++name2) // 0136 on name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(11, 26), // (13,25): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 4, name4 = 5, name5 = 6; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(13, 25), // (13,36): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 4, name4 = 5, name5 = 6; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4").WithLocation(13, 36), // (13,47): error CS0136: A local or parameter named 'name5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 4, name4 = 5, name5 = 6; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name5").WithArguments("name5").WithLocation(13, 47), // (13,47): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name1 in ""string"") ; // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(18, 26)); } [Fact] public void TestCollisionInsideFor2() { var source = @" using System.Linq; using System.Collections; partial class Class { private string Property { get { for (var name = from name in ""string"" orderby name select name; name != null; ) ; // 1931 for (IEnumerable name = null; name == from name in ""string"" orderby name select name; ) ; // 1931 for (IEnumerable name = null; name == null; name = from name in ""string"" orderby name select name ) ; // 1931 return string.Empty; } } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (11,51): warning CS8848: Operator 'from' cannot be used here due to precedence. Use parentheses to disambiguate. // for (IEnumerable name = null; name == from name in "string" orderby name select name; ) ; // 1931 Diagnostic(ErrorCode.WRN_PrecedenceInversion, @"from name in ""string""").WithArguments("from").WithLocation(11, 51), // (10,34): error CS1931: The range variable 'name' conflicts with a previous declaration of 'name' // for (var name = from name in "string" orderby name select name; name != null; ) ; // 1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "name").WithArguments("name").WithLocation(10, 34), // (11,56): error CS1931: The range variable 'name' conflicts with a previous declaration of 'name' // for (IEnumerable name = null; name == from name in "string" orderby name select name; ) ; // 1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "name").WithArguments("name").WithLocation(11, 56), // (12,69): error CS1931: The range variable 'name' conflicts with a previous declaration of 'name' // for (IEnumerable name = null; name == null; name = from name in "string" orderby name select name ) ; // 1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "name").WithArguments("name").WithLocation(12, 69)); } [WorkItem(792744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792744")] [Fact] public void TestCollisionInsideForeach() { var source = @" class Class { static int y = 1; static void Main(string[] args) { foreach (var y in new[] {new { y = y }}){ } //End } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideUsing() { var source = @" class Class : System.IDisposable { public void Dispose() {} int[] name3 = {}; void Method1(Class name2 = null) { using (var name1 = new Class()) { int other = (name3[0]); } using (var name1 = new Class()) { var other = name3[0].ToString(); using (var name3 = new Class()) // 0135 because name3 above refers to this.name3 { int name1 = 2; // 0136 on name1 } } using (var name2 = new Class()) // 0136 on name2. { int name1 = 2; int other = (name3[0]); } using (name2 = new Class()) { int name1 = 2; int other = (name3[0]); } } }"; CreateCompilation(source).VerifyDiagnostics( // (17,21): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = 2; // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(17, 21), // (17,21): warning CS0219: The variable 'name1' is assigned but its value is never used // int name1 = 2; // 0136 on name1 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name1").WithArguments("name1").WithLocation(17, 21), // (20,20): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var name2 = new Class()) // 0136 on name2. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(20, 20), // (22,17): warning CS0219: The variable 'name1' is assigned but its value is never used // int name1 = 2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name1").WithArguments("name1").WithLocation(22, 17), // (27,17): warning CS0219: The variable 'name1' is assigned but its value is never used // int name1 = 2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name1").WithArguments("name1").WithLocation(27, 17) ); } [Fact] public void TestCollisionInsideLock() { var source = @" using System; class Class { const int[] name = null; void Method1() { lock (name) { } { lock (string.Empty) { const int name = 0; // 0135 because name above means 'this.name'. Console.WriteLine(name); } } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideSwitch() { var source = @" class Class { int M() { return 1; } int name1 = 1; void Method1() { switch (name1) { case name1: break; // 0844: use of 'int name1' below before it is declared -- surprising error, but correct. Also notes that local name1 hides field. case 2: int name1 = 2; // 0135: because 'name1' above means 'this.name1'. Native compiler reports 0136, Roslyn reports 0135. var name2 = 3; System.Console.WriteLine(name1 + name2); break; case 3: name2 = M(); // Not a use-before-declaration error; name2 is defined above var name2 = M(); // 0128 on name2; switch sections share the same declaration space for (int name3 = 5; ; ) { System.Console.WriteLine(name2 + name3); break; } int name4 = 6; System.Console.WriteLine(name4); break; case 4: name1 = 2; for (int name3 = 7; ; ) { System.Console.WriteLine(name3); break; } switch (name1) { case 1: int name4 = 8, name5 = 9; // 0136 on name4, name5 // Native compiler reports error 0136 on `name5 = 11` below; Roslyn reports it here. System.Console.WriteLine(name4 + name5); break; } for (int name6 = 10; ; ) // 0136 on name6; Native compiler reports 0136 on name6 below. { System.Console.WriteLine(name6);} default: int name5 = 11, name6 = 12; // Native compiler reports 0136 on name5 and name6. Roslyn reports them above. System.Console.WriteLine(name5 + name6); break; } } }"; CreateCompilation(source).VerifyDiagnostics( // (10,18): error CS0844: Cannot use local variable 'name1' before it is declared. The declaration of the local variable hides the field 'Class.name1'. // case name1: break; // 0844: use of 'int name1' below before it is declared -- surprising error, but correct. Also notes that local name1 hides field. Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, "name1").WithArguments("name1", "Class.name1").WithLocation(10, 18), // (18,21): error CS0128: A local variable named 'name2' is already defined in this scope // var name2 = M(); // 0128 on name2; switch sections share the same declaration space Diagnostic(ErrorCode.ERR_LocalDuplicate, "name2").WithArguments("name2").WithLocation(18, 21), // (31,29): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name4 = 8, name5 = 9; // 0136 on name4, name5 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4").WithLocation(31, 29), // (31,40): error CS0136: A local or parameter named 'name5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name4 = 8, name5 = 9; // 0136 on name4, name5 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name5").WithArguments("name5").WithLocation(31, 40), // (36,26): error CS0136: A local or parameter named 'name6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (int name6 = 10; ; ) // 0136 on name6; Native compiler reports 0136 on name6 below. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name6").WithArguments("name6").WithLocation(36, 26) ); } [Fact] public void TestCollisionInsideTryCatch_LegalCases() { var source = @" using System; class Derived : Base { static long name1 = 1; static Derived() { { try { Console.WriteLine(name1); } catch (ArgumentException name1) { Console.WriteLine(name1.Message); } catch (Exception name1) { Console.WriteLine(name1.Message); } } { Console.WriteLine(name1); try { var name4 = string.Empty; try { name2 = 3; string name5 = string.Empty; name5.ToString(); name4.ToString(); } catch (Exception name2) { Console.WriteLine(name2.Message); string name5 = string.Empty; name5.ToString(); name4.ToString(); } } catch (Exception other) { var name4 = string.Empty; Console.WriteLine(name4.ToString()); name2 = 4; Console.WriteLine(other.Message); } } } } class Base { protected static long name2 = 5; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideTryCatch() { var source = @" using System; class Derived : Base { static long name1 = 1; static Derived() { { Console.WriteLine(name1); try { Console.WriteLine(name1); } catch (ArgumentException name1) { Console.WriteLine(name1.Message); } catch (Exception name2) { Console.WriteLine(name2.Message); } Console.WriteLine(name2); } { try { var name4 = string.Empty; Console.WriteLine(name1); } catch (Exception name1) { System.Console.WriteLine(name1.Message); var name5 = string.Empty; try { } catch (Exception name1) // 0136 on name1 { var name5 = string.Empty; // 0136 on name5 System.Console.WriteLine(name1.Message); } } var name4 = string.Empty; // Native reports 0136 here; } } } class Base { protected static long name2 = 2; }"; CreateCompilation(source).VerifyDiagnostics( // (27,21): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var name4 = string.Empty; // 0136: Roslyn reports this here; native reports it below. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4").WithLocation(27, 21), // (38,34): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch (Exception name1) // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(38, 34), // (40,25): error CS0136: A local or parameter named 'name5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var name5 = string.Empty; // 0136 on name5 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name5").WithArguments("name5").WithLocation(40, 25) ); } [Fact] public void DifferentArities() { var source = @" public class C<T> { public static U G<U>(U x) { return x; } void M() { int G = 10; G<int>(G); int C = 5; C<string>.G(C); } }"; CompileAndVerify(source).VerifyDiagnostics(); } [WorkItem(10556, "DevDiv_Projects/Roslyn")] [Fact] public void TestCollisionInsideQuery_LegalCases() { var source = @" using System.Linq; using System.Collections.Generic; partial class Class { private string Property { set { var other1 = from int name1 in ""string"" select name1; { var query1 = from name1 in ""string"" select name1; var query2 = from name1 in ""string"" select name1; this.Method(from name1 in ""string"" select name1).Method(from name1 in ""string"" select name1); } other1 = from int name1 in ""string"" select name2; { var query1 = from name1 in ""string"" let name2 = 1 select name1; var query2 = from name2 in ""string"" select name2; this.Method(from other2 in ""string"" from name2 in ""string"" select other2).Method(from name1 in ""string"" group name1 by name1 into name2 select name2); Method(from name1 in ""string"" group name1 by name1.ToString() into name1 select name1); } } } int name2 = 2; Class Method(IEnumerable<char> name1) { return null; } Class Method(object name1) { return null; } }"; CompileAndVerify(source).VerifyDiagnostics(); } [WorkItem(543045, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543045")] [Fact] public void TestCollisionInsideQuery() { var source = @" using System; using System.Linq; using System.Collections.Generic; partial class Class { private string Property { set { Console.WriteLine(name1); { var query1 = from name1 in string.Empty // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select name1; var query2 = from other in string.Empty let name1 = 1 // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select other; this.Method(from other in string.Empty from name1 in string.Empty // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select other).Method(from other in string.Empty group other by other.ToString() into name1 // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select name1); } { var query1 = from name2 in string.Empty let name2 = 2 // 1930 select name2; this.Method(from name2 in string.Empty from name2 in name1.ToString() // 1930 select name2); } } } int name1 = 3; Class Method(IEnumerable<char> name1) { return null; } Class Method(object name1) { return null; } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (26,34): error CS1930: The range variable 'name2' has already been declared // let name2 = 2 // 1930 Diagnostic(ErrorCode.ERR_QueryDuplicateRangeVariable, "name2").WithArguments("name2").WithLocation(26, 34), // (29,34): error CS1930: The range variable 'name2' has already been declared // from name2 in name1.ToString() // 1930 Diagnostic(ErrorCode.ERR_QueryDuplicateRangeVariable, "name2").WithArguments("name2").WithLocation(29, 34) ); } [Fact] public void TestCollisionInsideQuery_TypeParameter() { var source = @" using System.Linq; public class Class { void Method<T, U>() { { var q = from T in """" let U = T select T; } } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (7,26): error CS1948: The range variable 'T' cannot have the same name as a method type parameter // var q = from T in "" Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "T").WithArguments("T"), // (8,25): error CS1948: The range variable 'U' cannot have the same name as a method type parameter // let U = T Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "U").WithArguments("U")); } [WorkItem(542088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542088")] [Fact] public void LocalCollidesWithGenericType() { var source = @" public class C { public static int G<T>(int x) { return x; } public static void Main() { int G = 10; G<int>(G); } }"; CompileAndVerify(source).VerifyDiagnostics(); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void BindingOrderCollisions01() { var source = @"using System; class A { static long M(Action<long> act) { return 0; } static void What1() { int x1; { int y1 = M(x1 => { }); } } static void What2() { { int y2 = M(x2 => { }); } int x2; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (10,24): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(10, 24), // (10,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x1 => { })").WithArguments("long", "int").WithLocation(10, 22), // (8,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(8, 13), // (16,24): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(16, 24), // (16,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x2 => { })").WithArguments("long", "int").WithLocation(16, 22), // (18,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(18, 13) ); CreateCompilation(source).VerifyDiagnostics( // (10,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x1 => { })").WithArguments("long", "int").WithLocation(10, 22), // (8,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(8, 13), // (16,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x2 => { })").WithArguments("long", "int").WithLocation(16, 22), // (18,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(18, 13) ); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void BindingOrderCollisions02() { var source = @"using System; class A { static double M(Action<double> act) { return 0; } static long M(Action<long> act) { return 0; } static void What1() { int x1; { int y1 = M(x1 => { }); } } static void What2() { { int y2 = M(x2 => { }); } int x2; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (11,24): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(11, 24), // (11,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(11, 22), // (9,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(9, 13), // (17,24): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(17, 24), // (17,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(17, 22), // (19,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(19, 13) ); CreateCompilation(source).VerifyDiagnostics( // (11,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(11, 22), // (9,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(9, 13), // (17,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(17, 22), // (19,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(19, 13) ); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void BindingOrderCollisions03() { var source = @"using System; class Outer { static void Main(string[] args) { } public static int M() { return 1; } class Inner { public static int M = 2; void F1() { int x1 = M; Action a = () => { int x2 = M(); }; } void F2() { Action a = () => { int x2 = M(); }; int x1 = M; } void F3() { int x1 = M(); Action a = () => { int x2 = M; }; } void F4() { Action a = () => { int x2 = M; }; int x1 = M(); } } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(835569, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835569")] [Fact] public void CollisionWithSameWhenError() { var source = @" using System; using System.Reflection; class Program { static void Main() { Console.WriteLine(string.Join < Assembly(Environment.NewLine, Assembly.GetEntryAssembly().GetReferencedAssemblies())); } } "; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "Assembly").WithArguments("System.Reflection.Assembly").WithLocation(9, 41) ); } [Fact(Skip = "https://roslyn.codeplex.com/workitem/450")] [WorkItem(879811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879811")] public void Bug879811_1() { const string source = @" using static Static<string>; using static Static<int>; public static class Static<T> { public class Nested { public void M() { } } } class D { static void Main(string[] args) { var c = new Nested(); c.M(); } }"; CreateCompilation(source).VerifyDiagnostics( // (17,21): error CS0104: 'Nested' is an ambiguous reference between 'Static<int>.Nested' and 'Static<string>.Nested' // var c = new Nested(); Diagnostic(ErrorCode.ERR_AmbigContext, "Nested").WithArguments("Nested", "Static<int>.Nested", "Static<string>.Nested").WithLocation(17, 21)); } [Fact] [WorkItem(879811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879811")] public void Bug879811_2() { const string source = @" using static Static<string>; using static Static<System.String>; public static class Static<T> { public class Nested { public void M() { } } } class D { static void Main() { var c = new Nested(); } }"; CreateCompilation(source).VerifyDiagnostics( // (3,7): warning CS0105: The using directive for 'Static<string>' appeared previously in this namespace // using Static<System.String>; Diagnostic(ErrorCode.WRN_DuplicateUsing, "Static<System.String>").WithArguments("Static<string>").WithLocation(3, 14), // (3,1): hidden CS8019: Unnecessary using directive. // using Static<System.String>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Static<System.String>;").WithLocation(3, 1)); } [Fact] [WorkItem(879811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879811")] public void Bug879811_3() { const string source = @" using static Static<string>; public static class Static<T> { public class Nested { public void M() { } } } namespace N { using static Static<int>; class D { static void Main() { Static<int>.Nested c = new Nested(); } } }"; CreateCompilation(source).VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using Static<string>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Static<string>;").WithLocation(2, 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 Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; // The way the specification describes, and the way the native compiler reports name // collision errors is inconsistent and confusing. In Roslyn we will implement // the following more rational behaviors: // // ------------------ // // These two error messages are to be reworded: // // CS0135: (ERR_NameIllegallyOverrides) // // Original: 'X' conflicts with the declaration 'C.X' // // New: A local, parameter or range variable named 'X' cannot be declared in this scope // because that name is used in an enclosing local scope to refer to 'C.X'. // // CS0136: (ERR_LocalIllegallyOverrides) // // Original: A local variable named 'X' cannot be declared in this scope // because it would give a different meaning to 'X', which is // already used in a 'parent or current' / 'child' // scope to denote something else // // New: A local or parameter named 'X' cannot be declared in this scope // because that name is used in an enclosing local scope to define // a local or parameter. // // Note now the error messages are now nicely parallel, and much more clear about // precisely which rule has been violated. // // The rules for what error to report in each name collision scenario are as follows: // // --------------------------- // // Errors for simple names being used to refer to a member in one place and a declared // entity in another: // // CS0135: (ERR_NameIllegallyOverrides) // A local, parameter or range variable cannot be named 'X' because // that name is used in an enclosing local scope to refer to 'C.X'. // // Reported *only* when there is a local variable, local constant, lambda parameter or range variable // that would change the meaning of a *simple name* in an *expression* in an enclosing declaration // space to refer to a member, namespace, type, type parameter etc. Report it on the *inner* usage, // never the "outer" usage. eg: // // class C { int x; void M() { int y = x; { int x = y; } } } // // --------------------------- // // Errors for a local being used before it is defined: // // CS0841: (ERR_VariableUsedBeforeDeclaration) // Cannot use local variable 'X' before it is declared // // Reported when a local variable is used before it is declared, and the offending // usage was probably not intended to refer to a field. eg: // // class C { void M() { int y = x; int x; } } // // CS0844: (ERR_VariableUsedBeforeDeclarationAndHidesField) // Cannot use local variable 'X' before it is declared. The // declaration of the local variable hides the field 'C.X'. // // Reported if the offending usage might have been intended to refer to a field, eg: // // class C { int x; void M() { int y = x; int x; } } // // --------------------------- // // Errors for two of the same identifier being used to declare two different // things in overlapping or identical declaration spaces: // // CS0100: (ERR_DuplicateParamName) // The parameter name 'x' is a duplicate // // Reported when one parameter list contains two identically-named parameters. Eg: // // void M(int x, int x) {} or (x, x)=>{} // // CS0128: (ERR_LocalDuplicate) // A local variable named 'x' is already defined in this scope // // Reported *only* when there are two local variables or constants defined in the // *exact* same declaration space with the same name. eg: // // void M() { int x; int x; } // // CS0136: (ERR_LocalIllegallyOverrides) // New: A local or parameter named 'X' cannot be declared in this scope // because that name is used in an enclosing local scope to define // a local or parameter. // // Reported *only* when there is a local variable, local constant or lambda parameter // but NOT range variable that shadows a local variable, local constant, formal parameter, // range variable, or lambda parameter that was declared in an enclosing local declaration space. Again, // report it on the inner usage. eg: // // void M() { int y; { int y; } } // // CS0412: (ERR_LocalSameNameAsTypeParam) // 'X': a parameter or local variable cannot have the same name as a method type parameter // // Reported *only* when a local variable, local constant, formal parameter or lambda parameter // has the same name as a method type parameter. eg: // // void M<X>(){ int X; } // // CS1948: (ERR_QueryRangeVariableSameAsTypeParam) // The range variable 'X' cannot have the same name as a method type parameter // // Reported *only* when a range variable has the same name as a method type parameter. eg: // // void M<X>(){ var q = from X in z select X; } // // CS1930: (ERR_QueryDuplicateRangeVariable) // The range variable 'x' has already been declared // // Reported *only* if a range variable shadows another range variable that is in scope. eg: // // from x in y from x in z select q // // CS1931: (ERR_QueryRangeVariableOverrides) // The range variable 'x' conflicts with a previous declaration of 'x' // // Reported when there is a range variable that shadows a non-range variable from an // enclosing scope. eg: // // int x; var y = from x in q select m; // namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class NameCollisionTests : CompilingTestBase { [Fact] public void TestNamesFromTypeAndExpressionContextsDontCollide() { var source = @" using name1 = System.Exception; namespace Namespace { using name3 = System.Type; class Class { Class(name2 other1, name1 other2) { name3 other3 = typeof(name1); if (typeof(name1) != typeof(name2) || typeof(name2) is name3 || typeof(name1) is name3) { foreach (var name1 in ""string"") { for (var name2 = 1; name2 > --name2; name2++) { int name3 = name2; } } } else { name2 name1 = null, name2 = name1; name3 name3 = typeof(name2); } } } } class name2 { }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestLocalAndLabelDontCollide() { var source = @" using System; namespace Namespace { using name1 = System.Type; class Class { Class(name1 name1) { goto name2; name2: Console.WriteLine(); var name2 = new name2(); goto name1; name1: Console.WriteLine(); } } } class name2 { }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLabelWithLabel() { var source = @" using System; namespace Namespace { using name1 = System.Type; class Class { Class(name1 name1) { goto name1; name1: Console.WriteLine(); { goto name1; name1: Console.WriteLine(); var name2 = new name2(); goto name2; name2: Console.WriteLine(); } goto name2; name2: Console.WriteLine(); } internal int Property { set { goto name1; name1: Console.WriteLine(); Action lambda1 = () => { Action lambda2 = () => { goto name1; name1: Console.WriteLine(); var name2 = new name2(); goto name2; name2: Console.WriteLine(); }; goto name2; name2: Console.WriteLine(); }; } } } } class name2 { }"; CreateCompilation(source).VerifyDiagnostics( // (14,13): error CS0158: The label 'name1' shadows another label by the same name in a contained scope // name1: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name1").WithArguments("name1"), // (17,13): error CS0158: The label 'name2' shadows another label by the same name in a contained scope // name2: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name2").WithArguments("name2"), // (34,21): error CS0158: The label 'name1' shadows another label by the same name in a contained scope // name1: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name1").WithArguments("name1"), // (37,21): error CS0158: The label 'name2' shadows another label by the same name in a contained scope // name2: Console.WriteLine(); Diagnostic(ErrorCode.ERR_LabelShadow, "name2").WithArguments("name2")); } [Fact] public void TestCollisionOfLocalWithTypeOrMethodOrProperty_LegalCases() { var source = @" using System; namespace name1 { class Class { void name1() { { name1(); } { int name1 = name1 = 1; } foreach(var name1 in ""string"") ; } } } class name2 { Action lambda = () => { { int name2 = name2 = 2; Console.WriteLine(name3); } { int name3 = name3 = 3; } }; static int name3 { get { return 4; } } }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithType() { var source = @" using name1 = System.Console; class Class { Class() { { name1.WriteLine(); // Legal name2.Equals(null, null); // Legal } { int name1 = (name1 = 1), name2 = name2 = 2; // Legal -- strange, but legal } { name1.WriteLine(); name2.Equals(null, null); { int name1 = 3, name2 = name1; // 0135 on name1, name2 // Native compiler reports 0136 here; Roslyn reports 0135. } } } } class name2 { }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithMethodOrProperty() { var source = @" using System; namespace name1 { class Class { void name1() { name1(); { name1(); } { int name1 = name1 = 1; // 0135: Roslyn reports 0135, native reports 0136. } foreach (var name1 in ""string"") ; // 0135: Roslyn reports 0135, native reports 0136. } Action lambda = () => { { int name2 = name2 = 2; // 0135: conflicts with usage of name2 as the static property below. // Roslyn reports this here; native compiler reports it below. Console.WriteLine(name2); } Console.WriteLine(name2); // Native compiler reports 0135 here; Roslyn reports it above. }; static int name2 { get { return 3; } } } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void TestCollisionOfDelegateWithConst() { var source = @"class A { delegate void D(); static void Goo() { } class B { const int Goo = 123; static void Main() { Goo(); Bar(Goo); } static void Main2() { Bar(Goo); Goo(); } static void Bar(int x) { } static void Bar(D x) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithTypeParameter() { var source = @" class Class<name1, name2> { void Method<name3, name4>(name1 other1, name4 name4) // 0412 on name4 { { int name3 = 10; // 0412 on name3 System.Console.WriteLine(name3); // Eliminate warning foreach (var name2 in ""string"") { for (var name1 = 1; name1 <= name1++; name1++) // legal; name1 conflicts with a class type parameter which is not in the local variable decl space name1 = name2.GetHashCode(); } } { name1 other2 = typeof(name1) is name1 ? other1 : other1; // no error; all the name1's refer to the type, not the local. int name1 = (name1 = 2), name2 = name2 = 3; // legal; name1 conflicts with a class type parameter which is not in the local variable decl space foreach (var name3 in ""string"") // 0412 on name3 { System.Console.WriteLine(name3); // Eliminate warning for (var name4 = 4; ; ) // 0412 on name4 { name1 = name2.GetHashCode(); System.Console.WriteLine(name4); // Eliminate warning } } try {} catch(System.Exception name3) // 0412 on name3 { System.Console.WriteLine(name3); } } } }"; CreateCompilation(source).VerifyDiagnostics( // (4,51): error CS0412: 'name4': a parameter or local variable cannot have the same name as a method type parameter // void Method<name3, name4>(name1 other1, name4 name4) // 0412 on name4 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name4").WithArguments("name4").WithLocation(4, 51), // (7,17): error CS0412: 'name3': a parameter or local variable cannot have the same name as a method type parameter // int name3 = 10; // 0412 on name3 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name3").WithArguments("name3").WithLocation(7, 17), // (18,26): error CS0412: 'name3': a parameter or local variable cannot have the same name as a method type parameter // foreach (var name3 in "string") // 0412 on name3 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name3").WithArguments("name3").WithLocation(18, 26), // (21,26): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (var name4 = 4; ; ) // 0412 on name4 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4"), // (28,36): error CS0412: 'name3': a parameter or local variable cannot have the same name as a method type parameter // catch(System.Exception name3) // 0412 on name3 Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "name3").WithArguments("name3")); } [Fact] public void TestCollisionOfLocalWithField_LegalCases() { var source = @" partial class Derived : Base { private Derived() { this.name1 = 1; long name1 = this.name1; if (true) { name1 = this.name1 = name1; name2 = this.name2 = name2 + name1; } { while (name1 == 1) { long name2 = 2; name1 = name2; } do { long name2 = 3; name1 = name2; name1 = this.name1; } while (name1 != 1); } } } class Base { public long name2 = name1; private static int name1 = 4; } partial class Derived { internal long name1 = 5; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithField1() { var source = @" class Derived : Base { static long name1 = 1; static Derived() { while(name1 == 2) { int name1 = 3, other = name1, name2 = other; // 0135 on name1 and name2 // Native reports 0136 on name1 here and 0135 on name2 below. } do { } while (name2 == 4); // Native reports 0135 on name2 here; Roslyn reports it above. } } class Base { protected static long name2 = 5; }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithField2() { var source = @" class Class { public static int M() { return 1; } internal int Property { set { for (int i = 0; i < int.MaxValue; ++i) { if (i == 0) { int other = M(), name = M(), name = other; // 0128, 0135 } else { { int name = M(); name = M(); // 0135 } } } for (int i = 0; i > int.MinValue; ++i) { { i += 1; } } name = M(); } } private const int x = 123; private void M1(int x = x) {} // UNDONE: Native and Roslyn compilers both allow this; should they? private void M2(int y = x) { int x = M(); // UNDONE: Native and Roslyn compilers both allow this; should they? } private long other = 0, name = 6; }"; CreateCompilation(source).VerifyDiagnostics( // (13,50): error CS0128: A local variable named 'name' is already defined in this scope // int other = M(), name = M(), name = other; // 0128, 0135 Diagnostic(ErrorCode.ERR_LocalDuplicate, "name").WithArguments("name"), // (37,18): warning CS0414: The field 'Class.other' is assigned but its value is never used // private long other = 0, name = 6; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "other").WithArguments("Class.other") ); } [Fact] public void TestCollisionInsideFieldDeclaration() { // A close reading of the spec would indicate that this is not an error because the // offending simple name 'x' does not appear in any local variable declaration space. // A field initializer is not a declaration space. However, it seems plausible // that we want to report the error here. The native compiler does so as well. var source = @" class Class { private static int M() { return 1; } private static int x = 123; private static int z = x + ((System.Func<int>)( ()=>{ int x = M(); return x; } ))(); }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithField_PartialType() { var source = @" partial struct PartialStruct { private void Method() { if (true) { { int name = 1, other = name; } } name = 2; // Native compiler reports 0135 here; Roslyn no longer reports 0135. } } partial struct PartialStruct { internal long name; }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal_LegalCases1() { var source = @" partial class Derived : Base { private string Property { get { if (true) { int name = (name = 1); name += name; } { { int name = 2; name -= name; } } for(long name = 3; name <= 4; ++name) name += 5; foreach(var name in ""string"") { name.ToString(); } return this.name; } } } class Base { public string name = null; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal_LegalCases2() { var source = @" using System; using System.Linq; partial class Derived : Base { private string Property { get { // http://blogs.msdn.com/b/ericlippert/archive/2009/11/02/simple-names-are-not-so-simple.aspx foreach (var name in from name in ""string"" orderby name select name) Console.WriteLine(name); return this.name; } } } class Base { public string name = null; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal_LegalCases3() { var source = @" using System; using System.Linq; partial class Derived : Base { private string Property { get { // http://blogs.msdn.com/b/ericlippert/archive/2009/11/02/simple-names-are-not-so-simple.aspx foreach(var name in ""string"".OrderBy(name => name).Select(name => name)) { Console.WriteLine(name); } return this.name; } } } class Base { public string name = null; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionOfLocalWithLocal() { var source = @" class Class { public Class() { long name1 = 1; System.Console.WriteLine(name1); // Eliminate unused warning. name4 = name6; // 0841 on name4; used before declared. 0103 on name6; not defined in this context if (true) { { int other1 = 2, name1 = other1, name2 = name1; // 0136 on name1; already used in parent scope to mean something else. } // Native compiler reports 0136 on 'long name2' below; Roslyn reports it on 'int ... name2' here and 'var name2' below { if (true) { for (long name1 = this.name2; name1 >= --name1; name1++) // 0136 on name1; { name1.ToString(); name5.ToString(); // 0841: name5 is used before the declaration string name6 = ""string""; } } foreach (var name2 in ""string"") name2.ToString(); // 0136: Native reports this on 'long name2' below; Roslyn reports it here, and above. } string @name3 = ""string"", other2 = name3, name3 = other2; // 0128: name3 is defined twice. long @name2 = 3; System.Console.WriteLine(@name2); // eliminated unused warning. // Native compiler reports 0136 on 'long name2' here; Roslyn reports it on 'int ... name2' above. } string name4 = ""string"", name5 = name4; name6 = name3; // 0103 on both name6 and name3; not defined in this context. } public long name2 = 4; }"; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0841: Cannot use local variable 'name4' before it is declared // name4 = name6; // 0841 on name4; used before declared. 0103 on name6; not defined in this context Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name4").WithArguments("name4").WithLocation(7, 9), // (7,17): error CS0103: The name 'name6' does not exist in the current context // name4 = name6; // 0841 on name4; used before declared. 0103 on name6; not defined in this context Diagnostic(ErrorCode.ERR_NameNotInContext, "name6").WithArguments("name6").WithLocation(7, 17), // (11,33): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int other1 = 2, name1 = other1, name2 = name1; // 0136 on name1; already used in parent scope to mean something else. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(11, 33), // (11,49): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int other1 = 2, name1 = other1, name2 = name1; // 0136 on name1; already used in parent scope to mean something else. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(11, 49), // (16,31): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (long name1 = this.name2; name1 >= --name1; name1++) // 0136 on name1; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(16, 31), // (18,43): error CS0841: Cannot use local variable 'name5' before it is declared // name1.ToString(); name5.ToString(); // 0841: name5 is used before the declaration Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name5").WithArguments("name5").WithLocation(18, 43), // (22,30): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") name2.ToString(); // 0136: Native reports this on 'long name2' below; Roslyn reports it here, and above. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(22, 30), // (24,55): error CS0128: A local variable named 'name3' is already defined in this scope // string @name3 = "string", other2 = name3, name3 = other2; // 0128: name3 is defined twice. Diagnostic(ErrorCode.ERR_LocalDuplicate, "name3").WithArguments("name3").WithLocation(24, 55), // (29,9): error CS0103: The name 'name6' does not exist in the current context // name6 = name3; // 0103 on both name6 and name3; not defined in this context. Diagnostic(ErrorCode.ERR_NameNotInContext, "name6").WithArguments("name6").WithLocation(29, 9), // (29,17): error CS0103: The name 'name3' does not exist in the current context // name6 = name3; // 0103 on both name6 and name3; not defined in this context. Diagnostic(ErrorCode.ERR_NameNotInContext, "name3").WithArguments("name3").WithLocation(29, 17), // (19,32): warning CS0219: The variable 'name6' is assigned but its value is never used // string name6 = "string"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name6").WithArguments("name6").WithLocation(19, 32) ); } [Fact] public void TestCollisionOfLocalWithParam() { var source = @" using System; class Class { public Func<int, int, int> Method(int name1, int name2) { foreach (var name1 in ""string"") // 0136 { foreach (var name2 in ""string"") // 0136 { int name1 = name2.GetHashCode(); // 0136 } } Action<int> lambda = (name3) => { int name1 = 1; // 0136 if(name1 == 2) { name2 = name3 = name1; } else { int name2 = 3; // 0136 System.Console.WriteLine(name2); { int name3 = 2; // 0136 System.Console.WriteLine(name3); } } }; return (name1, name2) => name1; // 0136 on both name1 and name2 } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,22): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name1 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(7, 22), // (9,26): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(9, 26), // (11,21): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = name2.GetHashCode(); // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(11, 21), // (17,17): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = 1; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(17, 17), // (24,21): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name2 = 3; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(24, 21), // (27,25): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 2; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 25), // (32,17): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return (name1, name2) => name1; // 0136 on both name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(32, 17), // (32,24): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return (name1, name2) => name1; // 0136 on both name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(32, 24) ); CreateCompilation(source).VerifyDiagnostics( // (7,22): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name1 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(7, 22), // (9,26): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(9, 26), // (11,21): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = name2.GetHashCode(); // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(11, 21), // (27,25): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 2; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 25) ); } [Fact] public void TestCollisionOfParamWithParam() { var source = @" using System; class Class { public static void Method(int name1, int name2, int name2) // 0100 on name2 { Action<int, int> lambda = (other, name3) => { Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 { }; }; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (5,57): error CS0100: The parameter name 'name2' is a duplicate // public static void Method(int name1, int name2, int name2) // 0100 on name2 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name2").WithArguments("name2").WithLocation(5, 57), // (9,56): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(9, 56), // (9,70): error CS0100: The parameter name 'name4' is a duplicate // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name4").WithArguments("name4").WithLocation(9, 70), // (9,77): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(9, 77) ); CreateCompilation(source).VerifyDiagnostics( // (5,57): error CS0100: The parameter name 'name2' is a duplicate // public static void Method(int name1, int name2, int name2) // 0100 on name2 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name2").WithArguments("name2").WithLocation(5, 57), // (9,70): error CS0100: The parameter name 'name4' is a duplicate // Action<int, int, int, int> nestedLambda = (name1, name4, name4, name3) => // 0100 on name4, 0136 on name1 and name3 Diagnostic(ErrorCode.ERR_DuplicateParamName, "name4").WithArguments("name4").WithLocation(9, 70) ); } [WorkItem(930252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930252")] [Fact] public void TestCollisionOfParamWithParam1() { var source = @" class Program { delegate int D(int x, int y); static void X() { D d1 = (int x, int x) => { return 1; }; D d2 = (x, x) => { return 1; }; } }"; CreateCompilation(source).VerifyDiagnostics( // (7,28): error CS0100: The parameter name 'x' is a duplicate // D d1 = (int x, int x) => { return 1; }; Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x").WithLocation(7, 28), // (8,20): error CS0100: The parameter name 'x' is a duplicate // D d2 = (x, x) => { return 1; }; Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x").WithLocation(8, 20) ); } [Fact] public void TestCollisionInsideLambda_LegalCases() { var source = @" using System; partial class Class { private string Property { set { this. Method((name1) => { name1 = string.Empty; for (int name2 = name2 = 1; ; ) ; }). Method((name1) => name1.ToString()). Method((name1) => { foreach (var name2 in string.Empty) ; return name1; }); } } Class Method(Action<string> name1) { return null; } Class Method(Func<string, string> name1) { return null; } }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideLambda1() { var source = @" using System; class Derived : Base { static int M() { return 1; } static long name1 = 1; Action lambda = () => { name1 = 2; { int name1 = 3, other = name1, name2 = other; // 0135: on name1 and name2. // Native compiler reports 0136 here on name1 and 0135 on name2 below. // Roslyn reports them both as 0135 here. } name2 = 4; // Native compiler reports 0135 here; Roslyn reports above. int name3 = M(); { { name3 = 6; } if (true) { int name3 = M(); // 0136: Native compiler says 0135, Roslyn says 0136. The conflict is with the other local. } } }; Action anonMethod = delegate() { name1 = 8; if (true) { int name1 = 9, other = name1, name2 = other; // 0135: on name1, name2 // Native compiler reports 0136 on name1, Roslyn reports 0135. // Native compiler reports 0135 on name2 below, Roslyn reports it here. } { foreach (var name3 in ""string"") name3.ToString(); // 0136: Native compiler reports 0136 below, Roslyn reports it here. } name2 = 10; // Native compiler reports 0135 here; Roslyn reports it above. int name3 = M(); }; } class Base { protected static long name2 = 12; }"; CreateCompilation(source).VerifyDiagnostics( // (24,21): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = M(); // 0136: Native compiler says 0135, Roslyn says 0136. The conflict is with the other local. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(24, 21), // (39,26): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name3 in "string") name3.ToString(); // 0136: Native compiler reports 0136 below, Roslyn reports it here. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(39, 26), // (6,17): warning CS0414: The field 'Derived.name1' is assigned but its value is never used // static long name1 = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "name1").WithArguments("Derived.name1").WithLocation(6, 17) ); } [Fact] public void TestCollisionInsideLambda2() { var source = @" using System; class Class { void Method(Action lambda) { } void Method() { const long name1 = 1; System.Console.WriteLine(name1); // Eliminate warning. Method(() => { Console.WriteLine(name1); { const int name1 = 2; // 0136 int other = name1, name2 = other; // 0136: Native compiler reports this on 'const long name' below; Roslyn reports it here. } name2 = 3; // 0841: local used before declared const int name3 = 4; { { Console.WriteLine(name3); } if (true) { const int name3 = 5; // 0136 Console.WriteLine(name3); } } }); Method(delegate() { Console.WriteLine(name1); if (true) { const int name1 = 6, other = name1, name2 = other; // 0136 on name1 and name2 Console.WriteLine(name1 + other + name2); } // Roslyn reports 0136 on name2 above; native compiler reports it on 'const long name2' below. { foreach (var name3 in ""string"") name3.ToString(); // 0136: Roslyn reports this here, native reports it below. } Console.WriteLine(name2); // 0814: local used before declared const int name3 = 7; // Native compiler reports 0136 here, Roslyn reports it on 'var name3' above. Console.WriteLine(name3); // eliminate warning }); const long name2 = 8; // Native compiler reports 0136 here; Roslyn reports it on both offending nested decls above. Console.WriteLine(name2); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (15,27): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = 2; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(15, 27), // (16,36): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int other = name1, name2 = other; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(16, 36), // (18,13): error CS0841: Cannot use local variable 'name2' before it is declared // name2 = 3; // 0841: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(18, 13), // (27,31): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name3 = 5; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 31), // (38,27): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = 6, other = name1, name2 = other; // 0136 on name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(38, 27), // (38,53): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = 6, other = name1, name2 = other; // 0136 on name1 and name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(38, 53), // (42,30): error CS0841: Cannot use local variable 'name3' before it is declared // foreach (var name3 in ""string"") name3.ToString(); // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(42, 30), // (44,31): error CS0841: Cannot use local variable 'name2' before it is declared // Console.WriteLine(name2); // 0814: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(44, 31)); CreateCompilation(source).VerifyDiagnostics( // (18,13): error CS0841: Cannot use local variable 'name2' before it is declared // name2 = 3; // 0841: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(18, 13), // (27,31): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name3 = 5; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(27, 31), // (42,30): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name3 in "string") name3.ToString(); // 0136: Roslyn reports this here, native reports it below. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(42, 30), // (44,31): error CS0841: Cannot use local variable 'name2' before it is declared // Console.WriteLine(name2); // 0814: local used before declared Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "name2").WithArguments("name2").WithLocation(44, 31)); } [Fact] public void TestCollisionInsideOperator() { var source = @" using System; class Class { static long name1 = 1; public static Class operator +(Class name1, Class other) { var lambda = (Action)(() => { const int name1 = @name2; // 0136 on name1 because it conflicts with parameter if (true) { int name2 = name1; // 0135 because name2 conflicts with usage of name2 as Class.name2 above Console.WriteLine(name2); } }); return other; } const int name2 = 2; public static void Other() { Console.WriteLine(name1); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (10,23): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // const int name1 = @name2; // 0136 on name1 because it conflicts with parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(10, 23)); CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideIndexer() { var source = @" class Class { static long name1 = 1; public int this[int name1] { get { foreach (var name2 in ""string"") { foreach (var name2 in ""string"") // 0136 on name2 { int name1 = name2.GetHashCode(); // 0136 on name1 } } return name1; } } static long name2 = name1 + name2; }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (11,30): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name2 in "string") // 0136 on name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2"), // (13,25): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = name2.GetHashCode(); // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1")); } [Fact] public void TestCollisionInsideFor1() { var source = @" class Class { void Method1(int name4 = 1, params int[] name5) { for (int name1 = 2; name1 <= name1++; ++name1) { foreach (var name2 in ""string"") { for (name1 = 3; ; ) { break; } for (int name2 = name1; name2 <= name2++; ++name2) // 0136 on name2 { int name3 = 4, name4 = 5, name5 = 6; // 0136 on name3, name4 and name5 // Native compiler reports 0136 on name3 below, Roslyn reports it above. System.Console.WriteLine(name3 + name4 + name5); // Eliminate warning } } foreach (var name1 in ""string"") ; // 0136 on name1 } int name3 = 7; // Native compiler reports 0136 on name3 here; Roslyn reports it above. System.Console.WriteLine(name3); // Eliminate warning } }"; CreateCompilation(source).VerifyDiagnostics( // (11,26): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (int name2 = name1; name2 <= name2++; ++name2) // 0136 on name2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(11, 26), // (13,25): error CS0136: A local or parameter named 'name3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 4, name4 = 5, name5 = 6; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name3").WithArguments("name3").WithLocation(13, 25), // (13,36): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 4, name4 = 5, name5 = 6; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4").WithLocation(13, 36), // (13,47): error CS0136: A local or parameter named 'name5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name3 = 4, name4 = 5, name5 = 6; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name5").WithArguments("name5").WithLocation(13, 47), // (13,47): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var name1 in ""string"") ; // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(18, 26)); } [Fact] public void TestCollisionInsideFor2() { var source = @" using System.Linq; using System.Collections; partial class Class { private string Property { get { for (var name = from name in ""string"" orderby name select name; name != null; ) ; // 1931 for (IEnumerable name = null; name == from name in ""string"" orderby name select name; ) ; // 1931 for (IEnumerable name = null; name == null; name = from name in ""string"" orderby name select name ) ; // 1931 return string.Empty; } } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (11,51): warning CS8848: Operator 'from' cannot be used here due to precedence. Use parentheses to disambiguate. // for (IEnumerable name = null; name == from name in "string" orderby name select name; ) ; // 1931 Diagnostic(ErrorCode.WRN_PrecedenceInversion, @"from name in ""string""").WithArguments("from").WithLocation(11, 51), // (10,34): error CS1931: The range variable 'name' conflicts with a previous declaration of 'name' // for (var name = from name in "string" orderby name select name; name != null; ) ; // 1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "name").WithArguments("name").WithLocation(10, 34), // (11,56): error CS1931: The range variable 'name' conflicts with a previous declaration of 'name' // for (IEnumerable name = null; name == from name in "string" orderby name select name; ) ; // 1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "name").WithArguments("name").WithLocation(11, 56), // (12,69): error CS1931: The range variable 'name' conflicts with a previous declaration of 'name' // for (IEnumerable name = null; name == null; name = from name in "string" orderby name select name ) ; // 1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "name").WithArguments("name").WithLocation(12, 69)); } [WorkItem(792744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792744")] [Fact] public void TestCollisionInsideForeach() { var source = @" class Class { static int y = 1; static void Main(string[] args) { foreach (var y in new[] {new { y = y }}){ } //End } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideUsing() { var source = @" class Class : System.IDisposable { public void Dispose() {} int[] name3 = {}; void Method1(Class name2 = null) { using (var name1 = new Class()) { int other = (name3[0]); } using (var name1 = new Class()) { var other = name3[0].ToString(); using (var name3 = new Class()) // 0135 because name3 above refers to this.name3 { int name1 = 2; // 0136 on name1 } } using (var name2 = new Class()) // 0136 on name2. { int name1 = 2; int other = (name3[0]); } using (name2 = new Class()) { int name1 = 2; int other = (name3[0]); } } }"; CreateCompilation(source).VerifyDiagnostics( // (17,21): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name1 = 2; // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(17, 21), // (17,21): warning CS0219: The variable 'name1' is assigned but its value is never used // int name1 = 2; // 0136 on name1 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name1").WithArguments("name1").WithLocation(17, 21), // (20,20): error CS0136: A local or parameter named 'name2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var name2 = new Class()) // 0136 on name2. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name2").WithArguments("name2").WithLocation(20, 20), // (22,17): warning CS0219: The variable 'name1' is assigned but its value is never used // int name1 = 2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name1").WithArguments("name1").WithLocation(22, 17), // (27,17): warning CS0219: The variable 'name1' is assigned but its value is never used // int name1 = 2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "name1").WithArguments("name1").WithLocation(27, 17) ); } [Fact] public void TestCollisionInsideLock() { var source = @" using System; class Class { const int[] name = null; void Method1() { lock (name) { } { lock (string.Empty) { const int name = 0; // 0135 because name above means 'this.name'. Console.WriteLine(name); } } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideSwitch() { var source = @" class Class { int M() { return 1; } int name1 = 1; void Method1() { switch (name1) { case name1: break; // 0844: use of 'int name1' below before it is declared -- surprising error, but correct. Also notes that local name1 hides field. case 2: int name1 = 2; // 0135: because 'name1' above means 'this.name1'. Native compiler reports 0136, Roslyn reports 0135. var name2 = 3; System.Console.WriteLine(name1 + name2); break; case 3: name2 = M(); // Not a use-before-declaration error; name2 is defined above var name2 = M(); // 0128 on name2; switch sections share the same declaration space for (int name3 = 5; ; ) { System.Console.WriteLine(name2 + name3); break; } int name4 = 6; System.Console.WriteLine(name4); break; case 4: name1 = 2; for (int name3 = 7; ; ) { System.Console.WriteLine(name3); break; } switch (name1) { case 1: int name4 = 8, name5 = 9; // 0136 on name4, name5 // Native compiler reports error 0136 on `name5 = 11` below; Roslyn reports it here. System.Console.WriteLine(name4 + name5); break; } for (int name6 = 10; ; ) // 0136 on name6; Native compiler reports 0136 on name6 below. { System.Console.WriteLine(name6);} default: int name5 = 11, name6 = 12; // Native compiler reports 0136 on name5 and name6. Roslyn reports them above. System.Console.WriteLine(name5 + name6); break; } } }"; CreateCompilation(source).VerifyDiagnostics( // (10,18): error CS0844: Cannot use local variable 'name1' before it is declared. The declaration of the local variable hides the field 'Class.name1'. // case name1: break; // 0844: use of 'int name1' below before it is declared -- surprising error, but correct. Also notes that local name1 hides field. Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, "name1").WithArguments("name1", "Class.name1").WithLocation(10, 18), // (18,21): error CS0128: A local variable named 'name2' is already defined in this scope // var name2 = M(); // 0128 on name2; switch sections share the same declaration space Diagnostic(ErrorCode.ERR_LocalDuplicate, "name2").WithArguments("name2").WithLocation(18, 21), // (31,29): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name4 = 8, name5 = 9; // 0136 on name4, name5 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4").WithLocation(31, 29), // (31,40): error CS0136: A local or parameter named 'name5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int name4 = 8, name5 = 9; // 0136 on name4, name5 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name5").WithArguments("name5").WithLocation(31, 40), // (36,26): error CS0136: A local or parameter named 'name6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (int name6 = 10; ; ) // 0136 on name6; Native compiler reports 0136 on name6 below. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name6").WithArguments("name6").WithLocation(36, 26) ); } [Fact] public void TestCollisionInsideTryCatch_LegalCases() { var source = @" using System; class Derived : Base { static long name1 = 1; static Derived() { { try { Console.WriteLine(name1); } catch (ArgumentException name1) { Console.WriteLine(name1.Message); } catch (Exception name1) { Console.WriteLine(name1.Message); } } { Console.WriteLine(name1); try { var name4 = string.Empty; try { name2 = 3; string name5 = string.Empty; name5.ToString(); name4.ToString(); } catch (Exception name2) { Console.WriteLine(name2.Message); string name5 = string.Empty; name5.ToString(); name4.ToString(); } } catch (Exception other) { var name4 = string.Empty; Console.WriteLine(name4.ToString()); name2 = 4; Console.WriteLine(other.Message); } } } } class Base { protected static long name2 = 5; }"; CompileAndVerify(source).VerifyDiagnostics(); } [Fact] public void TestCollisionInsideTryCatch() { var source = @" using System; class Derived : Base { static long name1 = 1; static Derived() { { Console.WriteLine(name1); try { Console.WriteLine(name1); } catch (ArgumentException name1) { Console.WriteLine(name1.Message); } catch (Exception name2) { Console.WriteLine(name2.Message); } Console.WriteLine(name2); } { try { var name4 = string.Empty; Console.WriteLine(name1); } catch (Exception name1) { System.Console.WriteLine(name1.Message); var name5 = string.Empty; try { } catch (Exception name1) // 0136 on name1 { var name5 = string.Empty; // 0136 on name5 System.Console.WriteLine(name1.Message); } } var name4 = string.Empty; // Native reports 0136 here; } } } class Base { protected static long name2 = 2; }"; CreateCompilation(source).VerifyDiagnostics( // (27,21): error CS0136: A local or parameter named 'name4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var name4 = string.Empty; // 0136: Roslyn reports this here; native reports it below. Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name4").WithArguments("name4").WithLocation(27, 21), // (38,34): error CS0136: A local or parameter named 'name1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch (Exception name1) // 0136 on name1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name1").WithArguments("name1").WithLocation(38, 34), // (40,25): error CS0136: A local or parameter named 'name5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var name5 = string.Empty; // 0136 on name5 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "name5").WithArguments("name5").WithLocation(40, 25) ); } [Fact] public void DifferentArities() { var source = @" public class C<T> { public static U G<U>(U x) { return x; } void M() { int G = 10; G<int>(G); int C = 5; C<string>.G(C); } }"; CompileAndVerify(source).VerifyDiagnostics(); } [WorkItem(10556, "DevDiv_Projects/Roslyn")] [Fact] public void TestCollisionInsideQuery_LegalCases() { var source = @" using System.Linq; using System.Collections.Generic; partial class Class { private string Property { set { var other1 = from int name1 in ""string"" select name1; { var query1 = from name1 in ""string"" select name1; var query2 = from name1 in ""string"" select name1; this.Method(from name1 in ""string"" select name1).Method(from name1 in ""string"" select name1); } other1 = from int name1 in ""string"" select name2; { var query1 = from name1 in ""string"" let name2 = 1 select name1; var query2 = from name2 in ""string"" select name2; this.Method(from other2 in ""string"" from name2 in ""string"" select other2).Method(from name1 in ""string"" group name1 by name1 into name2 select name2); Method(from name1 in ""string"" group name1 by name1.ToString() into name1 select name1); } } } int name2 = 2; Class Method(IEnumerable<char> name1) { return null; } Class Method(object name1) { return null; } }"; CompileAndVerify(source).VerifyDiagnostics(); } [WorkItem(543045, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543045")] [Fact] public void TestCollisionInsideQuery() { var source = @" using System; using System.Linq; using System.Collections.Generic; partial class Class { private string Property { set { Console.WriteLine(name1); { var query1 = from name1 in string.Empty // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select name1; var query2 = from other in string.Empty let name1 = 1 // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select other; this.Method(from other in string.Empty from name1 in string.Empty // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select other).Method(from other in string.Empty group other by other.ToString() into name1 // 1931 -- UNDONE change to 0135 because name1 above refers to Class.name1 select name1); } { var query1 = from name2 in string.Empty let name2 = 2 // 1930 select name2; this.Method(from name2 in string.Empty from name2 in name1.ToString() // 1930 select name2); } } } int name1 = 3; Class Method(IEnumerable<char> name1) { return null; } Class Method(object name1) { return null; } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (26,34): error CS1930: The range variable 'name2' has already been declared // let name2 = 2 // 1930 Diagnostic(ErrorCode.ERR_QueryDuplicateRangeVariable, "name2").WithArguments("name2").WithLocation(26, 34), // (29,34): error CS1930: The range variable 'name2' has already been declared // from name2 in name1.ToString() // 1930 Diagnostic(ErrorCode.ERR_QueryDuplicateRangeVariable, "name2").WithArguments("name2").WithLocation(29, 34) ); } [Fact] public void TestCollisionInsideQuery_TypeParameter() { var source = @" using System.Linq; public class Class { void Method<T, U>() { { var q = from T in """" let U = T select T; } } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (7,26): error CS1948: The range variable 'T' cannot have the same name as a method type parameter // var q = from T in "" Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "T").WithArguments("T"), // (8,25): error CS1948: The range variable 'U' cannot have the same name as a method type parameter // let U = T Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "U").WithArguments("U")); } [WorkItem(542088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542088")] [Fact] public void LocalCollidesWithGenericType() { var source = @" public class C { public static int G<T>(int x) { return x; } public static void Main() { int G = 10; G<int>(G); } }"; CompileAndVerify(source).VerifyDiagnostics(); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void BindingOrderCollisions01() { var source = @"using System; class A { static long M(Action<long> act) { return 0; } static void What1() { int x1; { int y1 = M(x1 => { }); } } static void What2() { { int y2 = M(x2 => { }); } int x2; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (10,24): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(10, 24), // (10,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x1 => { })").WithArguments("long", "int").WithLocation(10, 22), // (8,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(8, 13), // (16,24): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(16, 24), // (16,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x2 => { })").WithArguments("long", "int").WithLocation(16, 22), // (18,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(18, 13) ); CreateCompilation(source).VerifyDiagnostics( // (10,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x1 => { })").WithArguments("long", "int").WithLocation(10, 22), // (8,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(8, 13), // (16,22): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M(x2 => { })").WithArguments("long", "int").WithLocation(16, 22), // (18,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(18, 13) ); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void BindingOrderCollisions02() { var source = @"using System; class A { static double M(Action<double> act) { return 0; } static long M(Action<long> act) { return 0; } static void What1() { int x1; { int y1 = M(x1 => { }); } } static void What2() { { int y2 = M(x2 => { }); } int x2; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (11,24): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(11, 24), // (11,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(11, 22), // (9,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(9, 13), // (17,24): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(17, 24), // (17,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(17, 22), // (19,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(19, 13) ); CreateCompilation(source).VerifyDiagnostics( // (11,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y1 = M(x1 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(11, 22), // (9,13): warning CS0168: The variable 'x1' is declared but never used // int x1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(9, 13), // (17,22): error CS0121: The call is ambiguous between the following methods or properties: 'A.M(Action<double>)' and 'A.M(Action<long>)' // int y2 = M(x2 => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("A.M(System.Action<double>)", "A.M(System.Action<long>)").WithLocation(17, 22), // (19,13): warning CS0168: The variable 'x2' is declared but never used // int x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(19, 13) ); } [WorkItem(542039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542039")] [Fact] public void BindingOrderCollisions03() { var source = @"using System; class Outer { static void Main(string[] args) { } public static int M() { return 1; } class Inner { public static int M = 2; void F1() { int x1 = M; Action a = () => { int x2 = M(); }; } void F2() { Action a = () => { int x2 = M(); }; int x1 = M; } void F3() { int x1 = M(); Action a = () => { int x2 = M; }; } void F4() { Action a = () => { int x2 = M; }; int x1 = M(); } } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(835569, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835569")] [Fact] public void CollisionWithSameWhenError() { var source = @" using System; using System.Reflection; class Program { static void Main() { Console.WriteLine(string.Join < Assembly(Environment.NewLine, Assembly.GetEntryAssembly().GetReferencedAssemblies())); } } "; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "Assembly").WithArguments("System.Reflection.Assembly").WithLocation(9, 41) ); } [Fact(Skip = "https://roslyn.codeplex.com/workitem/450")] [WorkItem(879811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879811")] public void Bug879811_1() { const string source = @" using static Static<string>; using static Static<int>; public static class Static<T> { public class Nested { public void M() { } } } class D { static void Main(string[] args) { var c = new Nested(); c.M(); } }"; CreateCompilation(source).VerifyDiagnostics( // (17,21): error CS0104: 'Nested' is an ambiguous reference between 'Static<int>.Nested' and 'Static<string>.Nested' // var c = new Nested(); Diagnostic(ErrorCode.ERR_AmbigContext, "Nested").WithArguments("Nested", "Static<int>.Nested", "Static<string>.Nested").WithLocation(17, 21)); } [Fact] [WorkItem(879811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879811")] public void Bug879811_2() { const string source = @" using static Static<string>; using static Static<System.String>; public static class Static<T> { public class Nested { public void M() { } } } class D { static void Main() { var c = new Nested(); } }"; CreateCompilation(source).VerifyDiagnostics( // (3,7): warning CS0105: The using directive for 'Static<string>' appeared previously in this namespace // using Static<System.String>; Diagnostic(ErrorCode.WRN_DuplicateUsing, "Static<System.String>").WithArguments("Static<string>").WithLocation(3, 14), // (3,1): hidden CS8019: Unnecessary using directive. // using Static<System.String>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Static<System.String>;").WithLocation(3, 1)); } [Fact] [WorkItem(879811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/879811")] public void Bug879811_3() { const string source = @" using static Static<string>; public static class Static<T> { public class Nested { public void M() { } } } namespace N { using static Static<int>; class D { static void Main() { Static<int>.Nested c = new Nested(); } } }"; CreateCompilation(source).VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using Static<string>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Static<string>;").WithLocation(2, 1)); } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/VisualStudio/LiveShare/Impl/Client/Projects/IRemoteProjectInfoProvider.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Projects { internal interface IRemoteProjectInfoProvider { Task<ImmutableArray<ProjectInfo>> GetRemoteProjectInfosAsync(CancellationToken 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.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Projects { internal interface IRemoteProjectInfoProvider { Task<ImmutableArray<ProjectInfo>> GetRemoteProjectInfosAsync(CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Compilers/CSharp/Portable/Symbols/LexicalSortKey.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.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A structure used to lexically order symbols. For performance, it's important that this be /// a STRUCTURE, and be able to be returned from a symbol without doing any additional allocations (even /// if nothing is cached yet). /// </summary> internal struct LexicalSortKey { private int _treeOrdinal; private int _position; // If -1, symbols is in metadata or otherwise not in source public int TreeOrdinal { get { return _treeOrdinal; } } // Offset of location within the tree. Doesn't need to exactly that span returns by Locations, just // be good enough to sort. In order word, we don't need to go to extra work to return the location of the identifier, // just some syntax location is fine. // // Negative value indicates that the structure was not initialized yet, is used for lazy // initializations only along with LexicalSortKey.NotInitialized public int Position { get { return _position; } } public static readonly LexicalSortKey NotInSource = new LexicalSortKey() { _treeOrdinal = -1, _position = 0 }; public static readonly LexicalSortKey NotInitialized = new LexicalSortKey() { _treeOrdinal = -1, _position = -1 }; // Put other synthesized members right before synthesized constructors. public static LexicalSortKey GetSynthesizedMemberKey(int offset) => new LexicalSortKey() { _treeOrdinal = int.MaxValue, _position = int.MaxValue - 2 - offset }; // Dev12 compiler adds synthetic constructors to the child list after adding all other members. // Methods are emitted in the children order, but synthetic cctors would be deferred // until later when it is known if they can be optimized or not. // As a result the last emitted method tokens are synthetic ctor and then synthetic cctor (if not optimized) // Since it is not too hard, we will try keeping the same order just to be easy on metadata diffing tools and such. public static readonly LexicalSortKey SynthesizedCtor = new LexicalSortKey() { _treeOrdinal = int.MaxValue, _position = int.MaxValue - 1 }; public static readonly LexicalSortKey SynthesizedCCtor = new LexicalSortKey() { _treeOrdinal = int.MaxValue, _position = int.MaxValue }; private LexicalSortKey(int treeOrdinal, int position) { Debug.Assert(position >= 0); Debug.Assert(treeOrdinal >= 0); _treeOrdinal = treeOrdinal; _position = position; } private LexicalSortKey(SyntaxTree tree, int position, CSharpCompilation compilation) : this(tree == null ? -1 : compilation.GetSyntaxTreeOrdinal(tree), position) { } public LexicalSortKey(SyntaxReference syntaxRef, CSharpCompilation compilation) : this(syntaxRef.SyntaxTree, syntaxRef.Span.Start, compilation) { } // WARNING: Only use this if the location is obtainable without allocating it (even if cached later). E.g., only // if the location object is stored in the constructor of the symbol. public LexicalSortKey(Location location, CSharpCompilation compilation) : this((SyntaxTree)location.SourceTree, location.SourceSpan.Start, compilation) { } // WARNING: Only use this if the node is obtainable without allocating it (even if cached later). E.g., only // if the node is stored in the constructor of the symbol. In particular, do not call this on the result of a GetSyntax() // call on a SyntaxReference. public LexicalSortKey(CSharpSyntaxNode node, CSharpCompilation compilation) : this(node.SyntaxTree, node.SpanStart, compilation) { } // WARNING: Only use this if the token is obtainable without allocating it (even if cached later). E.g., only // if the node is stored in the constructor of the symbol. In particular, do not call this on the result of a GetSyntax() // call on a SyntaxReference. public LexicalSortKey(SyntaxToken token, CSharpCompilation compilation) : this((SyntaxTree)token.SyntaxTree, token.SpanStart, compilation) { } /// <summary> /// Compare two lexical sort keys in a compilation. /// </summary> public static int Compare(LexicalSortKey xSortKey, LexicalSortKey ySortKey) { int comparison; if (xSortKey.TreeOrdinal != ySortKey.TreeOrdinal) { if (xSortKey.TreeOrdinal < 0) { return 1; } else if (ySortKey.TreeOrdinal < 0) { return -1; } comparison = xSortKey.TreeOrdinal - ySortKey.TreeOrdinal; Debug.Assert(comparison != 0); return comparison; } return xSortKey.Position - ySortKey.Position; } public static LexicalSortKey First(LexicalSortKey xSortKey, LexicalSortKey ySortKey) { int comparison = Compare(xSortKey, ySortKey); return comparison > 0 ? ySortKey : xSortKey; } public bool IsInitialized { get { return Volatile.Read(ref _position) >= 0; } } public void SetFrom(LexicalSortKey other) { Debug.Assert(other.IsInitialized); _treeOrdinal = other._treeOrdinal; Volatile.Write(ref _position, other._position); } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A structure used to lexically order symbols. For performance, it's important that this be /// a STRUCTURE, and be able to be returned from a symbol without doing any additional allocations (even /// if nothing is cached yet). /// </summary> internal struct LexicalSortKey { private int _treeOrdinal; private int _position; // If -1, symbols is in metadata or otherwise not in source public int TreeOrdinal { get { return _treeOrdinal; } } // Offset of location within the tree. Doesn't need to exactly that span returns by Locations, just // be good enough to sort. In order word, we don't need to go to extra work to return the location of the identifier, // just some syntax location is fine. // // Negative value indicates that the structure was not initialized yet, is used for lazy // initializations only along with LexicalSortKey.NotInitialized public int Position { get { return _position; } } public static readonly LexicalSortKey NotInSource = new LexicalSortKey() { _treeOrdinal = -1, _position = 0 }; public static readonly LexicalSortKey NotInitialized = new LexicalSortKey() { _treeOrdinal = -1, _position = -1 }; // Put other synthesized members right before synthesized constructors. public static LexicalSortKey GetSynthesizedMemberKey(int offset) => new LexicalSortKey() { _treeOrdinal = int.MaxValue, _position = int.MaxValue - 2 - offset }; // Dev12 compiler adds synthetic constructors to the child list after adding all other members. // Methods are emitted in the children order, but synthetic cctors would be deferred // until later when it is known if they can be optimized or not. // As a result the last emitted method tokens are synthetic ctor and then synthetic cctor (if not optimized) // Since it is not too hard, we will try keeping the same order just to be easy on metadata diffing tools and such. public static readonly LexicalSortKey SynthesizedCtor = new LexicalSortKey() { _treeOrdinal = int.MaxValue, _position = int.MaxValue - 1 }; public static readonly LexicalSortKey SynthesizedCCtor = new LexicalSortKey() { _treeOrdinal = int.MaxValue, _position = int.MaxValue }; private LexicalSortKey(int treeOrdinal, int position) { Debug.Assert(position >= 0); Debug.Assert(treeOrdinal >= 0); _treeOrdinal = treeOrdinal; _position = position; } private LexicalSortKey(SyntaxTree tree, int position, CSharpCompilation compilation) : this(tree == null ? -1 : compilation.GetSyntaxTreeOrdinal(tree), position) { } public LexicalSortKey(SyntaxReference syntaxRef, CSharpCompilation compilation) : this(syntaxRef.SyntaxTree, syntaxRef.Span.Start, compilation) { } // WARNING: Only use this if the location is obtainable without allocating it (even if cached later). E.g., only // if the location object is stored in the constructor of the symbol. public LexicalSortKey(Location location, CSharpCompilation compilation) : this((SyntaxTree)location.SourceTree, location.SourceSpan.Start, compilation) { } // WARNING: Only use this if the node is obtainable without allocating it (even if cached later). E.g., only // if the node is stored in the constructor of the symbol. In particular, do not call this on the result of a GetSyntax() // call on a SyntaxReference. public LexicalSortKey(CSharpSyntaxNode node, CSharpCompilation compilation) : this(node.SyntaxTree, node.SpanStart, compilation) { } // WARNING: Only use this if the token is obtainable without allocating it (even if cached later). E.g., only // if the node is stored in the constructor of the symbol. In particular, do not call this on the result of a GetSyntax() // call on a SyntaxReference. public LexicalSortKey(SyntaxToken token, CSharpCompilation compilation) : this((SyntaxTree)token.SyntaxTree, token.SpanStart, compilation) { } /// <summary> /// Compare two lexical sort keys in a compilation. /// </summary> public static int Compare(LexicalSortKey xSortKey, LexicalSortKey ySortKey) { int comparison; if (xSortKey.TreeOrdinal != ySortKey.TreeOrdinal) { if (xSortKey.TreeOrdinal < 0) { return 1; } else if (ySortKey.TreeOrdinal < 0) { return -1; } comparison = xSortKey.TreeOrdinal - ySortKey.TreeOrdinal; Debug.Assert(comparison != 0); return comparison; } return xSortKey.Position - ySortKey.Position; } public static LexicalSortKey First(LexicalSortKey xSortKey, LexicalSortKey ySortKey) { int comparison = Compare(xSortKey, ySortKey); return comparison > 0 ? ySortKey : xSortKey; } public bool IsInitialized { get { return Volatile.Read(ref _position) >= 0; } } public void SetFrom(LexicalSortKey other) { Debug.Assert(other.IsInitialized); _treeOrdinal = other._treeOrdinal; Volatile.Write(ref _position, other._position); } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Features/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.DocumentChanges { public partial class DocumentChangesTests : AbstractLanguageServerProtocolTests { [Fact] public async Task DocumentChanges_EndToEnd() { var source = @"class A { void M() { {|type:|} } }"; var expected = @"class A { void M() { // hi there } }"; var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts()); await DidOpen(testLspServer, locationTyped.Uri); Assert.Single(testLspServer.GetQueueAccessor().GetTrackedTexts()); var document = testLspServer.GetQueueAccessor().GetTrackedTexts().Single(); Assert.Equal(documentText, document.ToString()); await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there")); document = testLspServer.GetQueueAccessor().GetTrackedTexts().Single(); Assert.Equal(expected, document.ToString()); await DidClose(testLspServer, locationTyped.Uri); Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts()); } } [Fact] public async Task DidOpen_DocumentIsTracked() { var source = @"class A { void M() { {|type:|} } }"; var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await DidOpen(testLspServer, locationTyped.Uri); var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault(); Assert.NotNull(document); Assert.Equal(documentText, document.ToString()); } } [Fact] public async Task MultipleDidOpen_Errors() { var source = @"class A { void M() { {|type:|} } }"; var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await DidOpen(testLspServer, locationTyped.Uri); await Assert.ThrowsAsync<InvalidOperationException>(() => DidOpen(testLspServer, locationTyped.Uri)); } } [Fact] public async Task DidCloseWithoutDidOpen_Errors() { var source = @"class A { void M() { {|type:|} } }"; var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await Assert.ThrowsAsync<InvalidOperationException>(() => DidClose(testLspServer, locationTyped.Uri)); } } [Fact] public async Task DidChangeWithoutDidOpen_Errors() { var source = @"class A { void M() { {|type:|} } }"; var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await Assert.ThrowsAsync<InvalidOperationException>(() => DidChange(testLspServer, locationTyped.Uri, (0, 0, "goo"))); } } [Fact] public async Task DidClose_StopsTrackingDocument() { var source = @"class A { void M() { {|type:|} } }"; var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await DidOpen(testLspServer, locationTyped.Uri); await DidClose(testLspServer, locationTyped.Uri); Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts()); } } [Fact] public async Task DidChange_AppliesChanges() { var source = @"class A { void M() { {|type:|} } }"; var expected = @"class A { void M() { // hi there } }"; var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await DidOpen(testLspServer, locationTyped.Uri); await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there")); var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault(); Assert.NotNull(document); Assert.Equal(expected, document.ToString()); } } [Fact] public async Task DidChange_DoesntUpdateWorkspace() { var source = @"class A { void M() { {|type:|} } }"; var expected = @"class A { void M() { // hi there } }"; var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await DidOpen(testLspServer, locationTyped.Uri); await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there")); var documentTextFromWorkspace = (await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync()).ToString(); Assert.NotNull(documentTextFromWorkspace); Assert.Equal(documentText, documentTextFromWorkspace); // Just to ensure this test breaks if didChange stops working for some reason Assert.NotEqual(expected, documentTextFromWorkspace); } } [Fact] public async Task DidChange_MultipleChanges() { var source = @"class A { void M() { {|type:|} } }"; var expected = @"class A { void M() { // hi there // this builds on that } }"; var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await DidOpen(testLspServer, locationTyped.Uri); await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there"), (5, 0, " // this builds on that\r\n")); var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault(); Assert.NotNull(document); Assert.Equal(expected, document.ToString()); } } [Fact] public async Task DidChange_MultipleRequests() { var source = @"class A { void M() { {|type:|} } }"; var expected = @"class A { void M() { // hi there // this builds on that } }"; var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await DidOpen(testLspServer, locationTyped.Uri); await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there")); await DidChange(testLspServer, locationTyped.Uri, (5, 0, " // this builds on that\r\n")); var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault(); Assert.NotNull(document); Assert.Equal(expected, document.ToString()); } } private async Task<(TestLspServer, LSP.Location, string)> GetTestLspServerAndLocationAsync(string source) { var testLspServer = CreateTestLspServer(source, out var locations); var locationTyped = locations["type"].Single(); var documentText = await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync(); return (testLspServer, locationTyped, documentText.ToString()); } private static Task DidOpen(TestLspServer testLspServer, Uri uri) => testLspServer.OpenDocumentAsync(uri); private static async Task DidChange(TestLspServer testLspServer, Uri uri, params (int line, int column, string text)[] changes) => await testLspServer.InsertTextAsync(uri, changes); private static async Task DidClose(TestLspServer testLspServer, Uri uri) => await testLspServer.CloseDocumentAsync(uri); } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.DocumentChanges { public partial class DocumentChangesTests : AbstractLanguageServerProtocolTests { [Fact] public async Task DocumentChanges_EndToEnd() { var source = @"class A { void M() { {|type:|} } }"; var expected = @"class A { void M() { // hi there } }"; var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts()); await DidOpen(testLspServer, locationTyped.Uri); Assert.Single(testLspServer.GetQueueAccessor().GetTrackedTexts()); var document = testLspServer.GetQueueAccessor().GetTrackedTexts().Single(); Assert.Equal(documentText, document.ToString()); await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there")); document = testLspServer.GetQueueAccessor().GetTrackedTexts().Single(); Assert.Equal(expected, document.ToString()); await DidClose(testLspServer, locationTyped.Uri); Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts()); } } [Fact] public async Task DidOpen_DocumentIsTracked() { var source = @"class A { void M() { {|type:|} } }"; var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await DidOpen(testLspServer, locationTyped.Uri); var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault(); Assert.NotNull(document); Assert.Equal(documentText, document.ToString()); } } [Fact] public async Task MultipleDidOpen_Errors() { var source = @"class A { void M() { {|type:|} } }"; var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await DidOpen(testLspServer, locationTyped.Uri); await Assert.ThrowsAsync<InvalidOperationException>(() => DidOpen(testLspServer, locationTyped.Uri)); } } [Fact] public async Task DidCloseWithoutDidOpen_Errors() { var source = @"class A { void M() { {|type:|} } }"; var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await Assert.ThrowsAsync<InvalidOperationException>(() => DidClose(testLspServer, locationTyped.Uri)); } } [Fact] public async Task DidChangeWithoutDidOpen_Errors() { var source = @"class A { void M() { {|type:|} } }"; var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await Assert.ThrowsAsync<InvalidOperationException>(() => DidChange(testLspServer, locationTyped.Uri, (0, 0, "goo"))); } } [Fact] public async Task DidClose_StopsTrackingDocument() { var source = @"class A { void M() { {|type:|} } }"; var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await DidOpen(testLspServer, locationTyped.Uri); await DidClose(testLspServer, locationTyped.Uri); Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts()); } } [Fact] public async Task DidChange_AppliesChanges() { var source = @"class A { void M() { {|type:|} } }"; var expected = @"class A { void M() { // hi there } }"; var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await DidOpen(testLspServer, locationTyped.Uri); await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there")); var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault(); Assert.NotNull(document); Assert.Equal(expected, document.ToString()); } } [Fact] public async Task DidChange_DoesntUpdateWorkspace() { var source = @"class A { void M() { {|type:|} } }"; var expected = @"class A { void M() { // hi there } }"; var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await DidOpen(testLspServer, locationTyped.Uri); await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there")); var documentTextFromWorkspace = (await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync()).ToString(); Assert.NotNull(documentTextFromWorkspace); Assert.Equal(documentText, documentTextFromWorkspace); // Just to ensure this test breaks if didChange stops working for some reason Assert.NotEqual(expected, documentTextFromWorkspace); } } [Fact] public async Task DidChange_MultipleChanges() { var source = @"class A { void M() { {|type:|} } }"; var expected = @"class A { void M() { // hi there // this builds on that } }"; var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await DidOpen(testLspServer, locationTyped.Uri); await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there"), (5, 0, " // this builds on that\r\n")); var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault(); Assert.NotNull(document); Assert.Equal(expected, document.ToString()); } } [Fact] public async Task DidChange_MultipleRequests() { var source = @"class A { void M() { {|type:|} } }"; var expected = @"class A { void M() { // hi there // this builds on that } }"; var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source); using (testLspServer) { await DidOpen(testLspServer, locationTyped.Uri); await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there")); await DidChange(testLspServer, locationTyped.Uri, (5, 0, " // this builds on that\r\n")); var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault(); Assert.NotNull(document); Assert.Equal(expected, document.ToString()); } } private async Task<(TestLspServer, LSP.Location, string)> GetTestLspServerAndLocationAsync(string source) { var testLspServer = CreateTestLspServer(source, out var locations); var locationTyped = locations["type"].Single(); var documentText = await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync(); return (testLspServer, locationTyped, documentText.ToString()); } private static Task DidOpen(TestLspServer testLspServer, Uri uri) => testLspServer.OpenDocumentAsync(uri); private static async Task DidChange(TestLspServer testLspServer, Uri uri, params (int line, int column, string text)[] changes) => await testLspServer.InsertTextAsync(uri, changes); private static async Task DidClose(TestLspServer testLspServer, Uri uri) => await testLspServer.CloseDocumentAsync(uri); } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolVisibility.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.Utilities { internal enum SymbolVisibility { Public, Internal, Private, } }
// Licensed to the .NET Foundation under one or more 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.Utilities { internal enum SymbolVisibility { Public, Internal, Private, } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Compilers/CSharp/Portable/Lowering/SpillSequenceSpiller.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.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class SpillSequenceSpiller : BoundTreeRewriterWithStackGuard { private const BoundKind SpillSequenceBuilderKind = (BoundKind)byte.MaxValue; private readonly SyntheticBoundNodeFactory _F; private readonly PooledDictionary<LocalSymbol, LocalSymbol> _tempSubstitution; private SpillSequenceSpiller(MethodSymbol method, SyntaxNode syntaxNode, TypeCompilationState compilationState, PooledDictionary<LocalSymbol, LocalSymbol> tempSubstitution, BindingDiagnosticBag diagnostics) { _F = new SyntheticBoundNodeFactory(method, syntaxNode, compilationState, diagnostics); _F.CurrentFunction = method; _tempSubstitution = tempSubstitution; } private sealed class BoundSpillSequenceBuilder : BoundExpression { public readonly BoundExpression Value; private ArrayBuilder<LocalSymbol> _locals; private ArrayBuilder<BoundStatement> _statements; public BoundSpillSequenceBuilder(SyntaxNode syntax, BoundExpression value = null) : base(SpillSequenceBuilderKind, syntax, value?.Type) { Debug.Assert(value?.Kind != SpillSequenceBuilderKind); this.Value = value; } public bool HasStatements { get { return _statements != null; } } public bool HasLocals { get { return _locals != null; } } public ImmutableArray<LocalSymbol> GetLocals() { return (_locals == null) ? ImmutableArray<LocalSymbol>.Empty : _locals.ToImmutable(); } public ImmutableArray<BoundStatement> GetStatements() { if (_statements == null) { return ImmutableArray<BoundStatement>.Empty; } return _statements.ToImmutable(); } internal BoundSpillSequenceBuilder Update(BoundExpression value) { var result = new BoundSpillSequenceBuilder(this.Syntax, value); result._locals = _locals; result._statements = _statements; return result; } public void Free() { if (_locals != null) _locals.Free(); if (_statements != null) _statements.Free(); } internal void Include(BoundSpillSequenceBuilder other) { if (other != null) { IncludeAndFree(ref _locals, ref other._locals); IncludeAndFree(ref _statements, ref other._statements); } } private static void IncludeAndFree<T>(ref ArrayBuilder<T> left, ref ArrayBuilder<T> right) { if (right == null) { return; } if (left == null) { left = right; return; } left.AddRange(right); right.Free(); } public void AddLocal(LocalSymbol local) { if (_locals == null) { _locals = ArrayBuilder<LocalSymbol>.GetInstance(); } _locals.Add(local); } public void AddLocals(ImmutableArray<LocalSymbol> locals) { foreach (var local in locals) { AddLocal(local); } } public void AddStatement(BoundStatement statement) { if (_statements == null) { _statements = ArrayBuilder<BoundStatement>.GetInstance(); } _statements.Add(statement); } public void AddStatements(ImmutableArray<BoundStatement> statements) { foreach (var statement in statements) { AddStatement(statement); } } internal void AddExpressions(ImmutableArray<BoundExpression> expressions) { foreach (var expression in expressions) { AddStatement(new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true }); } } #if DEBUG internal override string Dump() { var node = new TreeDumperNode("boundSpillSequenceBuilder", null, new TreeDumperNode[] { new TreeDumperNode("locals", this.GetLocals(), null), new TreeDumperNode("statements", null, from x in this.GetStatements() select BoundTreeDumperNodeProducer.MakeTree(x)), new TreeDumperNode("value", null, new TreeDumperNode[] { BoundTreeDumperNodeProducer.MakeTree(this.Value) }), new TreeDumperNode("type", this.Type, null) }); return TreeDumper.DumpCompact(node); } #endif } private sealed class LocalSubstituter : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private readonly PooledDictionary<LocalSymbol, LocalSymbol> _tempSubstitution; private LocalSubstituter(PooledDictionary<LocalSymbol, LocalSymbol> tempSubstitution, int recursionDepth = 0) : base(recursionDepth) { _tempSubstitution = tempSubstitution; } public static BoundNode Rewrite(PooledDictionary<LocalSymbol, LocalSymbol> tempSubstitution, BoundNode node) { if (tempSubstitution.Count == 0) { return node; } var substituter = new LocalSubstituter(tempSubstitution); return substituter.Visit(node); } public override BoundNode VisitLocal(BoundLocal node) { if (!node.LocalSymbol.SynthesizedKind.IsLongLived()) { LocalSymbol longLived; if (_tempSubstitution.TryGetValue(node.LocalSymbol, out longLived)) { return node.Update(longLived, node.ConstantValueOpt, node.Type); } } return base.VisitLocal(node); } } internal static BoundStatement Rewrite(BoundStatement body, MethodSymbol method, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var tempSubstitution = PooledDictionary<LocalSymbol, LocalSymbol>.GetInstance(); var spiller = new SpillSequenceSpiller(method, body.Syntax, compilationState, tempSubstitution, diagnostics); BoundNode result = spiller.Visit(body); result = LocalSubstituter.Rewrite(tempSubstitution, result); tempSubstitution.Free(); return (BoundStatement)result; } private BoundExpression VisitExpression(ref BoundSpillSequenceBuilder builder, BoundExpression expression) { var e = (BoundExpression)this.Visit(expression); if (e == null || e.Kind != SpillSequenceBuilderKind) { return e; } var newBuilder = (BoundSpillSequenceBuilder)e; if (builder == null) { builder = newBuilder.Update(null); } else { builder.Include(newBuilder); } return newBuilder.Value; } private static BoundExpression UpdateExpression(BoundSpillSequenceBuilder builder, BoundExpression expression) { if (builder == null) { return expression; } Debug.Assert(builder.Value == null); if (!builder.HasLocals && !builder.HasStatements) { builder.Free(); return expression; } return builder.Update(expression); } private BoundStatement UpdateStatement(BoundSpillSequenceBuilder builder, BoundStatement statement) { if (builder == null) { Debug.Assert(statement != null); return statement; } Debug.Assert(builder.Value == null); if (statement != null) { builder.AddStatement(statement); } var result = new BoundBlock(statement.Syntax, builder.GetLocals(), builder.GetStatements()) { WasCompilerGenerated = true }; builder.Free(); return result; } private BoundExpression Spill( BoundSpillSequenceBuilder builder, BoundExpression expression, RefKind refKind = RefKind.None, bool sideEffectsOnly = false) { Debug.Assert(builder != null); if (builder.Syntax != null) _F.Syntax = builder.Syntax; while (true) { switch (expression.Kind) { case BoundKind.ArrayInitialization: Debug.Assert(refKind == RefKind.None); Debug.Assert(!sideEffectsOnly); var arrayInitialization = (BoundArrayInitialization)expression; var newInitializers = VisitExpressionList(ref builder, arrayInitialization.Initializers, forceSpill: true); return arrayInitialization.Update(newInitializers); case BoundKind.ArgListOperator: Debug.Assert(refKind == RefKind.None); Debug.Assert(!sideEffectsOnly); var argumentList = (BoundArgListOperator)expression; var newArgs = VisitExpressionList(ref builder, argumentList.Arguments, argumentList.ArgumentRefKindsOpt, forceSpill: true); return argumentList.Update(newArgs, argumentList.ArgumentRefKindsOpt, argumentList.Type); case SpillSequenceBuilderKind: var sequenceBuilder = (BoundSpillSequenceBuilder)expression; builder.Include(sequenceBuilder); expression = sequenceBuilder.Value; continue; case BoundKind.Sequence: // neither the side-effects nor the value of the sequence contains await // (otherwise it would be converted to a SpillSequenceBuilder). if (refKind != RefKind.None) { return expression; } goto default; case BoundKind.ThisReference: case BoundKind.BaseReference: if (refKind != RefKind.None || expression.Type.IsReferenceType) { return expression; } goto default; case BoundKind.Parameter: if (refKind != RefKind.None) { return expression; } goto default; case BoundKind.Local: var local = (BoundLocal)expression; if (local.LocalSymbol.SynthesizedKind == SynthesizedLocalKind.Spill || refKind != RefKind.None) { return local; } goto default; case BoundKind.FieldAccess: var field = (BoundFieldAccess)expression; var fieldSymbol = field.FieldSymbol; if (fieldSymbol.IsStatic) { // no need to spill static fields if used as locations or if readonly if (refKind != RefKind.None || fieldSymbol.IsReadOnly) { return field; } goto default; } if (refKind == RefKind.None) goto default; var receiver = Spill(builder, field.ReceiverOpt, fieldSymbol.ContainingType.IsValueType ? refKind : RefKind.None); return field.Update(receiver, fieldSymbol, field.ConstantValueOpt, field.ResultKind, field.Type); case BoundKind.Literal: case BoundKind.TypeExpression: return expression; case BoundKind.ConditionalReceiver: // we will rewrite this as a part of rewriting whole LoweredConditionalAccess // later, if needed return expression; default: if (expression.Type.IsVoidType() || sideEffectsOnly) { builder.AddStatement(_F.ExpressionStatement(expression)); return null; } else { BoundAssignmentOperator assignToTemp; var replacement = _F.StoreToTemp( expression, out assignToTemp, refKind: refKind, kind: SynthesizedLocalKind.Spill, syntaxOpt: _F.Syntax); builder.AddLocal(replacement.LocalSymbol); builder.AddStatement(_F.ExpressionStatement(assignToTemp)); return replacement; } } } } private ImmutableArray<BoundExpression> VisitExpressionList( ref BoundSpillSequenceBuilder builder, ImmutableArray<BoundExpression> args, ImmutableArray<RefKind> refKinds = default(ImmutableArray<RefKind>), bool forceSpill = false, bool sideEffectsOnly = false) { Debug.Assert(!sideEffectsOnly || refKinds.IsDefault); Debug.Assert(refKinds.IsDefault || refKinds.Length == args.Length); if (args.Length == 0) { return args; } var newList = VisitList(args); Debug.Assert(newList.Length == args.Length); int lastSpill; if (forceSpill) { lastSpill = newList.Length; } else { lastSpill = -1; for (int i = newList.Length - 1; i >= 0; i--) { if (newList[i].Kind == SpillSequenceBuilderKind) { lastSpill = i; break; } } } if (lastSpill == -1) { return newList; } if (builder == null) { builder = new BoundSpillSequenceBuilder(lastSpill < newList.Length ? (newList[lastSpill] as BoundSpillSequenceBuilder)?.Syntax : null); } var result = ArrayBuilder<BoundExpression>.GetInstance(newList.Length); // everything up until the last spill must be spilled entirely for (int i = 0; i < lastSpill; i++) { var refKind = refKinds.IsDefault ? RefKind.None : refKinds[i]; var replacement = Spill(builder, newList[i], refKind, sideEffectsOnly); Debug.Assert(sideEffectsOnly || replacement != null); if (!sideEffectsOnly) { result.Add(replacement); } } // the value of the last spill and everything that follows is not spilled if (lastSpill < newList.Length) { var lastSpillNode = (BoundSpillSequenceBuilder)newList[lastSpill]; builder.Include(lastSpillNode); result.Add(lastSpillNode.Value); for (int i = lastSpill + 1; i < newList.Length; i++) { result.Add(newList[i]); } } return result.ToImmutableAndFree(); } #region Statement Visitors public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node) { BoundSpillSequenceBuilder builder = null; var expression = VisitExpression(ref builder, node.Expression); return UpdateStatement(builder, node.Update(expression, node.Cases, node.DefaultLabel, node.EqualityMethod)); } public override BoundNode VisitThrowStatement(BoundThrowStatement node) { BoundSpillSequenceBuilder builder = null; BoundExpression expression = VisitExpression(ref builder, node.ExpressionOpt); return UpdateStatement(builder, node.Update(expression)); } public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) { BoundSpillSequenceBuilder builder = null; BoundExpression expr = VisitExpression(ref builder, node.Expression); Debug.Assert(expr != null); Debug.Assert(builder == null || builder.Value == null); return UpdateStatement(builder, node.Update(expr)); } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { BoundSpillSequenceBuilder builder = null; var condition = VisitExpression(ref builder, node.Condition); return UpdateStatement(builder, node.Update(condition, node.JumpIfTrue, node.Label)); } public override BoundNode VisitReturnStatement(BoundReturnStatement node) { BoundSpillSequenceBuilder builder = null; var expression = VisitExpression(ref builder, node.ExpressionOpt); return UpdateStatement(builder, node.Update(node.RefKind, expression)); } public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) { BoundSpillSequenceBuilder builder = null; var expression = VisitExpression(ref builder, node.Expression); return UpdateStatement(builder, node.Update(expression)); } public override BoundNode VisitCatchBlock(BoundCatchBlock node) { BoundExpression exceptionSourceOpt = (BoundExpression)this.Visit(node.ExceptionSourceOpt); var locals = node.Locals; var exceptionFilterPrologueOpt = node.ExceptionFilterPrologueOpt; Debug.Assert(exceptionFilterPrologueOpt is null); // it is introduced by this pass BoundSpillSequenceBuilder builder = null; var exceptionFilterOpt = VisitExpression(ref builder, node.ExceptionFilterOpt); if (builder is { }) { Debug.Assert(builder.Value is null); locals = locals.AddRange(builder.GetLocals()); exceptionFilterPrologueOpt = new BoundStatementList(node.Syntax, builder.GetStatements()); } BoundBlock body = (BoundBlock)this.Visit(node.Body); TypeSymbol exceptionTypeOpt = this.VisitType(node.ExceptionTypeOpt); return node.Update(locals, exceptionSourceOpt, exceptionTypeOpt, exceptionFilterPrologueOpt, exceptionFilterOpt, body, node.IsSynthesizedAsyncCatchAll); } #if DEBUG public override BoundNode DefaultVisit(BoundNode node) { Debug.Assert(!(node is BoundStatement)); return base.DefaultVisit(node); } #endif #endregion #region Expression Visitors public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) { // An await expression has already been wrapped in a BoundSpillSequence if not at the top level, so // the spilling will occur in the enclosing node. BoundSpillSequenceBuilder builder = null; var expr = VisitExpression(ref builder, node.Expression); return UpdateExpression(builder, node.Update(expr, node.AwaitableInfo, node.Type)); } public override BoundNode VisitSpillSequence(BoundSpillSequence node) { var builder = new BoundSpillSequenceBuilder(node.Syntax); // Ensure later errors (e.g. in async rewriting) are associated with the correct node. _F.Syntax = node.Syntax; builder.AddStatements(VisitList(node.SideEffects)); builder.AddLocals(node.Locals); var value = VisitExpression(ref builder, node.Value); return builder.Update(value); } public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) { BoundSpillSequenceBuilder builder = null; var expr = VisitExpression(ref builder, node.Operand); return UpdateExpression(builder, node.Update(expr, node.IsManaged, node.Type)); } public override BoundNode VisitArgListOperator(BoundArgListOperator node) { BoundSpillSequenceBuilder builder = null; var newArgs = VisitExpressionList(ref builder, node.Arguments); return UpdateExpression(builder, node.Update(newArgs, node.ArgumentRefKindsOpt, node.Type)); } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { BoundSpillSequenceBuilder builder = null; var expression = VisitExpression(ref builder, node.Expression); BoundSpillSequenceBuilder indicesBuilder = null; var indices = this.VisitExpressionList(ref indicesBuilder, node.Indices); if (indicesBuilder != null) { // spill the array if there were await expressions in the indices if (builder == null) { builder = new BoundSpillSequenceBuilder(indicesBuilder.Syntax); } expression = Spill(builder, expression); } if (builder != null) { builder.Include(indicesBuilder); indicesBuilder = builder; builder = null; } return UpdateExpression(indicesBuilder, node.Update(expression, indices, node.Type)); } public override BoundNode VisitArrayCreation(BoundArrayCreation node) { BoundSpillSequenceBuilder builder = null; var init = (BoundArrayInitialization)VisitExpression(ref builder, node.InitializerOpt); ImmutableArray<BoundExpression> bounds; if (builder == null) { bounds = VisitExpressionList(ref builder, node.Bounds); } else { // spill bounds expressions if initializers contain await var boundsBuilder = new BoundSpillSequenceBuilder(builder.Syntax); bounds = VisitExpressionList(ref boundsBuilder, node.Bounds, forceSpill: true); boundsBuilder.Include(builder); builder = boundsBuilder; } return UpdateExpression(builder, node.Update(bounds, init, node.Type)); } public override BoundNode VisitArrayInitialization(BoundArrayInitialization node) { BoundSpillSequenceBuilder builder = null; var initializers = this.VisitExpressionList(ref builder, node.Initializers); return UpdateExpression(builder, node.Update(initializers)); } public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { BoundSpillSequenceBuilder builder = null; BoundExpression count = VisitExpression(ref builder, node.Count); var initializerOpt = (BoundArrayInitialization)VisitExpression(ref builder, node.InitializerOpt); return UpdateExpression(builder, node.Update(node.ElementType, count, initializerOpt, node.Type)); } public override BoundNode VisitArrayLength(BoundArrayLength node) { BoundSpillSequenceBuilder builder = null; var expression = VisitExpression(ref builder, node.Expression); return UpdateExpression(builder, node.Update(expression, node.Type)); } public override BoundNode VisitAsOperator(BoundAsOperator node) { BoundSpillSequenceBuilder builder = null; var operand = VisitExpression(ref builder, node.Operand); return UpdateExpression(builder, node.Update(operand, node.TargetType, node.Conversion, node.Type)); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { BoundSpillSequenceBuilder builder = null; var right = VisitExpression(ref builder, node.Right); BoundExpression left = node.Left; if (builder == null) { left = VisitExpression(ref builder, left); } else { // if the right-hand-side has await, spill the left var leftBuilder = new BoundSpillSequenceBuilder(builder.Syntax); switch (left.Kind) { case BoundKind.Local: case BoundKind.Parameter: // locals and parameters are directly assignable, LHS is not on the stack so nothing to spill break; case BoundKind.FieldAccess: var field = (BoundFieldAccess)left; // static fields are directly assignable, LHS is not on the stack, nothing to spill if (field.FieldSymbol.IsStatic) break; // instance fields are directly assignable, but receiver is pushed, so need to spill that. left = fieldWithSpilledReceiver(field, ref leftBuilder, isAssignmentTarget: true); break; case BoundKind.ArrayAccess: var arrayAccess = (BoundArrayAccess)left; // array and indices are pushed on stack so need to spill that var expression = VisitExpression(ref leftBuilder, arrayAccess.Expression); expression = Spill(leftBuilder, expression, RefKind.None); var indices = this.VisitExpressionList(ref leftBuilder, arrayAccess.Indices, forceSpill: true); left = arrayAccess.Update(expression, indices, arrayAccess.Type); break; default: // must be something indirectly assignable, just visit and spill as an ordinary Ref (not a RefReadOnly!!) // // NOTE: in some cases this will result in spiller producing an error. // For example if the LHS is a ref-returning method like // // obj.RefReturning(a, b, c) = await Something(); // // the spiller would eventually have to spill the evaluation result of "refReturning" call as an ordinary Ref, // which it can't. left = Spill(leftBuilder, VisitExpression(ref leftBuilder, left), RefKind.Ref); break; } leftBuilder.Include(builder); builder = leftBuilder; } return UpdateExpression(builder, node.Update(left, right, node.IsRef, node.Type)); BoundExpression fieldWithSpilledReceiver(BoundFieldAccess field, ref BoundSpillSequenceBuilder leftBuilder, bool isAssignmentTarget) { var generateDummyFieldAccess = false; if (!field.FieldSymbol.IsStatic) { Debug.Assert(field.ReceiverOpt is object); BoundExpression receiver; if (field.FieldSymbol.ContainingType.IsReferenceType) { // a reference type can always live across await so Spill using leftBuilder receiver = Spill(leftBuilder, VisitExpression(ref leftBuilder, field.ReceiverOpt)); // dummy field access to trigger NRE // a.b = c will trigger a NRE if a is null on assignment, // but a.b.c = d will trigger a NRE if a is null before evaluating d // so check whether we assign to the field directly generateDummyFieldAccess = !isAssignmentTarget; } else if (field.ReceiverOpt is BoundArrayAccess arrayAccess) { // an arrayAccess returns a ref so can only be called after the await, but spill expression and indices var expression = VisitExpression(ref leftBuilder, arrayAccess.Expression); expression = Spill(leftBuilder, expression, RefKind.None); var indices = this.VisitExpressionList(ref leftBuilder, arrayAccess.Indices, forceSpill: true); receiver = arrayAccess.Update(expression, indices, arrayAccess.Type); // dummy array access to trigger IndexOutRangeException or NRE // we only need this if the array access is a receiver since // a[0] = b triggers a NRE/IORE on assignment // but a[0].b = c triggers an NRE/IORE before evaluating c Spill(leftBuilder, receiver, sideEffectsOnly: true); } else if (field.ReceiverOpt is BoundFieldAccess receiverField) { receiver = fieldWithSpilledReceiver(receiverField, ref leftBuilder, isAssignmentTarget: false); } else { receiver = Spill(leftBuilder, VisitExpression(ref leftBuilder, field.ReceiverOpt), RefKind.Ref); } field = field.Update(receiver, field.FieldSymbol, field.ConstantValueOpt, field.ResultKind, field.Type); } if (generateDummyFieldAccess) { Spill(leftBuilder, field, sideEffectsOnly: true); } return field; } } public override BoundNode VisitBadExpression(BoundBadExpression node) { // Cannot recurse into BadExpression children return node; } public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { BoundSpillSequenceBuilder builder = null; var right = VisitExpression(ref builder, node.Right); BoundExpression left; if (builder == null) { left = VisitExpression(ref builder, node.Left); } else { var leftBuilder = new BoundSpillSequenceBuilder(builder.Syntax); left = VisitExpression(ref leftBuilder, node.Left); left = Spill(leftBuilder, left); if (node.OperatorKind == BinaryOperatorKind.LogicalBoolOr || node.OperatorKind == BinaryOperatorKind.LogicalBoolAnd) { var tmp = _F.SynthesizedLocal(node.Type, kind: SynthesizedLocalKind.Spill, syntax: _F.Syntax); leftBuilder.AddLocal(tmp); leftBuilder.AddStatement(_F.Assignment(_F.Local(tmp), left)); leftBuilder.AddStatement(_F.If( node.OperatorKind == BinaryOperatorKind.LogicalBoolAnd ? _F.Local(tmp) : _F.Not(_F.Local(tmp)), UpdateStatement(builder, _F.Assignment(_F.Local(tmp), right)))); return UpdateExpression(leftBuilder, _F.Local(tmp)); } else { // if the right-hand-side has await, spill the left leftBuilder.Include(builder); builder = leftBuilder; } } return UpdateExpression(builder, node.Update(node.OperatorKind, node.ConstantValue, node.Method, node.ConstrainedToType, node.ResultKind, left, right, node.Type)); } public override BoundNode VisitCall(BoundCall node) { BoundSpillSequenceBuilder builder = null; var arguments = this.VisitExpressionList(ref builder, node.Arguments, node.ArgumentRefKindsOpt); BoundExpression receiver = null; if (builder == null || node.ReceiverOpt is BoundTypeExpression) { receiver = VisitExpression(ref builder, node.ReceiverOpt); } else if (node.Method.RequiresInstanceReceiver) { // spill the receiver if there were await expressions in the arguments var receiverBuilder = new BoundSpillSequenceBuilder(builder.Syntax); receiver = node.ReceiverOpt; RefKind refKind = ReceiverSpillRefKind(receiver); receiver = Spill(receiverBuilder, VisitExpression(ref receiverBuilder, receiver), refKind: refKind); receiverBuilder.Include(builder); builder = receiverBuilder; } return UpdateExpression(builder, node.Update(receiver, node.Method, arguments)); } private static RefKind ReceiverSpillRefKind(BoundExpression receiver) { var result = RefKind.None; if (!receiver.Type.IsReferenceType && LocalRewriter.CanBePassedByReference(receiver)) { result = receiver.Type.IsReadOnly ? RefKind.In : RefKind.Ref; } return result; } public override BoundNode VisitConditionalOperator(BoundConditionalOperator node) { BoundSpillSequenceBuilder conditionBuilder = null; var condition = VisitExpression(ref conditionBuilder, node.Condition); BoundSpillSequenceBuilder consequenceBuilder = null; var consequence = VisitExpression(ref consequenceBuilder, node.Consequence); BoundSpillSequenceBuilder alternativeBuilder = null; var alternative = VisitExpression(ref alternativeBuilder, node.Alternative); if (consequenceBuilder == null && alternativeBuilder == null) { return UpdateExpression(conditionBuilder, node.Update(node.IsRef, condition, consequence, alternative, node.ConstantValueOpt, node.NaturalTypeOpt, node.WasTargetTyped, node.Type)); } if (conditionBuilder == null) conditionBuilder = new BoundSpillSequenceBuilder((consequenceBuilder ?? alternativeBuilder).Syntax); if (consequenceBuilder == null) consequenceBuilder = new BoundSpillSequenceBuilder(alternativeBuilder.Syntax); if (alternativeBuilder == null) alternativeBuilder = new BoundSpillSequenceBuilder(consequenceBuilder.Syntax); if (node.Type.IsVoidType()) { conditionBuilder.AddStatement( _F.If(condition, UpdateStatement(consequenceBuilder, _F.ExpressionStatement(consequence)), UpdateStatement(alternativeBuilder, _F.ExpressionStatement(alternative)))); return conditionBuilder.Update(_F.Default(node.Type)); } else { var tmp = _F.SynthesizedLocal(node.Type, kind: SynthesizedLocalKind.Spill, syntax: _F.Syntax); conditionBuilder.AddLocal(tmp); conditionBuilder.AddStatement( _F.If(condition, UpdateStatement(consequenceBuilder, _F.Assignment(_F.Local(tmp), consequence)), UpdateStatement(alternativeBuilder, _F.Assignment(_F.Local(tmp), alternative)))); return conditionBuilder.Update(_F.Local(tmp)); } } public override BoundNode VisitConversion(BoundConversion node) { if (node.ConversionKind == ConversionKind.AnonymousFunction && node.Type.IsExpressionTree()) { // Expression trees do not contain any code that requires spilling. return node; } BoundSpillSequenceBuilder builder = null; var operand = VisitExpression(ref builder, node.Operand); return UpdateExpression( builder, node.UpdateOperand(operand)); } public override BoundNode VisitPassByCopy(BoundPassByCopy node) { BoundSpillSequenceBuilder builder = null; var expression = VisitExpression(ref builder, node.Expression); return UpdateExpression( builder, node.Update( expression, type: node.Type)); } public override BoundNode VisitMethodGroup(BoundMethodGroup node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { BoundSpillSequenceBuilder builder = null; var argument = VisitExpression(ref builder, node.Argument); return UpdateExpression(builder, node.Update(argument, node.MethodOpt, node.IsExtensionMethod, node.Type)); } public override BoundNode VisitFieldAccess(BoundFieldAccess node) { BoundSpillSequenceBuilder builder = null; var receiver = VisitExpression(ref builder, node.ReceiverOpt); return UpdateExpression(builder, node.Update(receiver, node.FieldSymbol, node.ConstantValueOpt, node.ResultKind, node.Type)); } public override BoundNode VisitIsOperator(BoundIsOperator node) { BoundSpillSequenceBuilder builder = null; var operand = VisitExpression(ref builder, node.Operand); return UpdateExpression(builder, node.Update(operand, node.TargetType, node.Conversion, node.Type)); } public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { BoundSpillSequenceBuilder builder = null; var right = VisitExpression(ref builder, node.RightOperand); BoundExpression left; if (builder == null) { left = VisitExpression(ref builder, node.LeftOperand); } else { var leftBuilder = new BoundSpillSequenceBuilder(builder.Syntax); left = VisitExpression(ref leftBuilder, node.LeftOperand); left = Spill(leftBuilder, left); var tmp = _F.SynthesizedLocal(node.Type, kind: SynthesizedLocalKind.Spill, syntax: _F.Syntax); leftBuilder.AddLocal(tmp); leftBuilder.AddStatement(_F.Assignment(_F.Local(tmp), left)); leftBuilder.AddStatement(_F.If( _F.ObjectEqual(_F.Local(tmp), _F.Null(left.Type)), UpdateStatement(builder, _F.Assignment(_F.Local(tmp), right)))); return UpdateExpression(leftBuilder, _F.Local(tmp)); } return UpdateExpression(builder, node.Update(left, right, node.LeftConversion, node.OperatorResultKind, node.Type)); } public override BoundNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) { var receiverRefKind = ReceiverSpillRefKind(node.Receiver); BoundSpillSequenceBuilder receiverBuilder = null; var receiver = VisitExpression(ref receiverBuilder, node.Receiver); BoundSpillSequenceBuilder whenNotNullBuilder = null; var whenNotNull = VisitExpression(ref whenNotNullBuilder, node.WhenNotNull); BoundSpillSequenceBuilder whenNullBuilder = null; var whenNullOpt = VisitExpression(ref whenNullBuilder, node.WhenNullOpt); if (whenNotNullBuilder == null && whenNullBuilder == null) { return UpdateExpression(receiverBuilder, node.Update(receiver, node.HasValueMethodOpt, whenNotNull, whenNullOpt, node.Id, node.Type)); } if (receiverBuilder == null) receiverBuilder = new BoundSpillSequenceBuilder((whenNotNullBuilder ?? whenNullBuilder).Syntax); if (whenNotNullBuilder == null) whenNotNullBuilder = new BoundSpillSequenceBuilder(whenNullBuilder.Syntax); if (whenNullBuilder == null) whenNullBuilder = new BoundSpillSequenceBuilder(whenNotNullBuilder.Syntax); BoundExpression condition; if (receiver.Type.IsReferenceType || receiver.Type.IsValueType || receiverRefKind == RefKind.None) { // spill to a clone receiver = Spill(receiverBuilder, receiver, RefKind.None); var hasValueOpt = node.HasValueMethodOpt; if (hasValueOpt == null) { condition = _F.ObjectNotEqual( _F.Convert(_F.SpecialType(SpecialType.System_Object), receiver), _F.Null(_F.SpecialType(SpecialType.System_Object))); } else { condition = _F.Call(receiver, hasValueOpt); } } else { Debug.Assert(node.HasValueMethodOpt == null); receiver = Spill(receiverBuilder, receiver, RefKind.Ref); var clone = _F.SynthesizedLocal(receiver.Type, _F.Syntax, refKind: RefKind.None, kind: SynthesizedLocalKind.Spill); receiverBuilder.AddLocal(clone); // (object)default(T) != null var isNotClass = _F.ObjectNotEqual( _F.Convert(_F.SpecialType(SpecialType.System_Object), _F.Default(receiver.Type)), _F.Null(_F.SpecialType(SpecialType.System_Object))); // isNotCalss || {clone = receiver; (object)clone != null} condition = _F.LogicalOr( isNotClass, _F.MakeSequence( _F.AssignmentExpression(_F.Local(clone), receiver), _F.ObjectNotEqual( _F.Convert(_F.SpecialType(SpecialType.System_Object), _F.Local(clone)), _F.Null(_F.SpecialType(SpecialType.System_Object)))) ); receiver = _F.ComplexConditionalReceiver(receiver, _F.Local(clone)); } if (node.Type.IsVoidType()) { var whenNotNullStatement = UpdateStatement(whenNotNullBuilder, _F.ExpressionStatement(whenNotNull)); whenNotNullStatement = ConditionalReceiverReplacer.Replace(whenNotNullStatement, receiver, node.Id, RecursionDepth); Debug.Assert(whenNullOpt == null || !LocalRewriter.ReadIsSideeffecting(whenNullOpt)); receiverBuilder.AddStatement(_F.If(condition, whenNotNullStatement)); return receiverBuilder.Update(_F.Default(node.Type)); } else { var tmp = _F.SynthesizedLocal(node.Type, kind: SynthesizedLocalKind.Spill, syntax: _F.Syntax); var whenNotNullStatement = UpdateStatement(whenNotNullBuilder, _F.Assignment(_F.Local(tmp), whenNotNull)); whenNotNullStatement = ConditionalReceiverReplacer.Replace(whenNotNullStatement, receiver, node.Id, RecursionDepth); whenNullOpt = whenNullOpt ?? _F.Default(node.Type); receiverBuilder.AddLocal(tmp); receiverBuilder.AddStatement( _F.If(condition, whenNotNullStatement, UpdateStatement(whenNullBuilder, _F.Assignment(_F.Local(tmp), whenNullOpt)))); return receiverBuilder.Update(_F.Local(tmp)); } } private sealed class ConditionalReceiverReplacer : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private readonly BoundExpression _receiver; private readonly int _receiverId; #if DEBUG // we must replace exactly one node private int _replaced; #endif private ConditionalReceiverReplacer(BoundExpression receiver, int receiverId, int recursionDepth) : base(recursionDepth) { _receiver = receiver; _receiverId = receiverId; } public static BoundStatement Replace(BoundNode node, BoundExpression receiver, int receiverID, int recursionDepth) { var replacer = new ConditionalReceiverReplacer(receiver, receiverID, recursionDepth); var result = (BoundStatement)replacer.Visit(node); #if DEBUG Debug.Assert(replacer._replaced == 1, "should have replaced exactly one node"); #endif return result; } public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node) { if (node.Id == _receiverId) { #if DEBUG _replaced++; #endif return _receiver; } return node; } } public override BoundNode VisitLambda(BoundLambda node) { var oldCurrentFunction = _F.CurrentFunction; _F.CurrentFunction = node.Symbol; var result = base.VisitLambda(node); _F.CurrentFunction = oldCurrentFunction; return result; } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { var oldCurrentFunction = _F.CurrentFunction; _F.CurrentFunction = node.Symbol; var result = base.VisitLocalFunctionStatement(node); _F.CurrentFunction = oldCurrentFunction; return result; } public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) { Debug.Assert(node.InitializerExpressionOpt == null); BoundSpillSequenceBuilder builder = null; var arguments = this.VisitExpressionList(ref builder, node.Arguments, node.ArgumentRefKindsOpt); return UpdateExpression(builder, node.Update(node.Constructor, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ConstantValueOpt, node.InitializerExpressionOpt, node.Type)); } public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) { BoundSpillSequenceBuilder builder = null; var index = VisitExpression(ref builder, node.Index); BoundExpression expression; if (builder == null) { expression = VisitExpression(ref builder, node.Expression); } else { var expressionBuilder = new BoundSpillSequenceBuilder(builder.Syntax); expression = VisitExpression(ref expressionBuilder, node.Expression); expression = Spill(expressionBuilder, expression); expressionBuilder.Include(builder); builder = expressionBuilder; } return UpdateExpression(builder, node.Update(expression, index, node.Checked, node.Type)); } public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { BoundSpillSequenceBuilder builder = null; var operand = VisitExpression(ref builder, node.Operand); return UpdateExpression(builder, node.Update(operand, node.Type)); } public override BoundNode VisitSequence(BoundSequence node) { BoundSpillSequenceBuilder valueBuilder = null; var value = VisitExpression(ref valueBuilder, node.Value); BoundSpillSequenceBuilder builder = null; var sideEffects = VisitExpressionList(ref builder, node.SideEffects, forceSpill: valueBuilder != null, sideEffectsOnly: true); if (builder == null && valueBuilder == null) { return node.Update(node.Locals, sideEffects, value, node.Type); } if (builder == null) { builder = new BoundSpillSequenceBuilder(valueBuilder.Syntax); } PromoteAndAddLocals(builder, node.Locals); builder.AddExpressions(sideEffects); builder.Include(valueBuilder); return builder.Update(value); } public override BoundNode VisitThrowExpression(BoundThrowExpression node) { BoundSpillSequenceBuilder builder = null; BoundExpression operand = VisitExpression(ref builder, node.Expression); return UpdateExpression(builder, node.Update(operand, node.Type)); } /// <summary> /// If an expression node that declares synthesized short-lived locals (currently only sequence) contains /// a spill sequence (from an await or switch expression), these locals become long-lived since their /// values may be read by code that follows. We promote these variables to long-lived of kind /// <see cref="SynthesizedLocalKind.Spill"/>. /// </summary> private void PromoteAndAddLocals(BoundSpillSequenceBuilder builder, ImmutableArray<LocalSymbol> locals) { foreach (var local in locals) { if (local.SynthesizedKind.IsLongLived()) { builder.AddLocal(local); } else { LocalSymbol longLived = local.WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind.Spill, _F.Syntax); _tempSubstitution.Add(local, longLived); builder.AddLocal(longLived); } } } public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) { BoundSpillSequenceBuilder builder = null; BoundExpression operand = VisitExpression(ref builder, node.Operand); return UpdateExpression(builder, node.Update(node.OperatorKind, operand, node.ConstantValueOpt, node.MethodOpt, node.ConstrainedToTypeOpt, node.ResultKind, node.Type)); } public override BoundNode VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node) { BoundSpillSequenceBuilder builder = null; BoundExpression operand = VisitExpression(ref builder, node.Operand); return UpdateExpression(builder, node.Update(operand, node.ConversionMethod, node.Type)); } public override BoundNode VisitSequencePointExpression(BoundSequencePointExpression node) { BoundSpillSequenceBuilder builder = null; BoundExpression expression = VisitExpression(ref builder, node.Expression); return UpdateExpression(builder, node.Update(expression, node.Type)); } #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; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class SpillSequenceSpiller : BoundTreeRewriterWithStackGuard { private const BoundKind SpillSequenceBuilderKind = (BoundKind)byte.MaxValue; private readonly SyntheticBoundNodeFactory _F; private readonly PooledDictionary<LocalSymbol, LocalSymbol> _tempSubstitution; private SpillSequenceSpiller(MethodSymbol method, SyntaxNode syntaxNode, TypeCompilationState compilationState, PooledDictionary<LocalSymbol, LocalSymbol> tempSubstitution, BindingDiagnosticBag diagnostics) { _F = new SyntheticBoundNodeFactory(method, syntaxNode, compilationState, diagnostics); _F.CurrentFunction = method; _tempSubstitution = tempSubstitution; } private sealed class BoundSpillSequenceBuilder : BoundExpression { public readonly BoundExpression Value; private ArrayBuilder<LocalSymbol> _locals; private ArrayBuilder<BoundStatement> _statements; public BoundSpillSequenceBuilder(SyntaxNode syntax, BoundExpression value = null) : base(SpillSequenceBuilderKind, syntax, value?.Type) { Debug.Assert(value?.Kind != SpillSequenceBuilderKind); this.Value = value; } public bool HasStatements { get { return _statements != null; } } public bool HasLocals { get { return _locals != null; } } public ImmutableArray<LocalSymbol> GetLocals() { return (_locals == null) ? ImmutableArray<LocalSymbol>.Empty : _locals.ToImmutable(); } public ImmutableArray<BoundStatement> GetStatements() { if (_statements == null) { return ImmutableArray<BoundStatement>.Empty; } return _statements.ToImmutable(); } internal BoundSpillSequenceBuilder Update(BoundExpression value) { var result = new BoundSpillSequenceBuilder(this.Syntax, value); result._locals = _locals; result._statements = _statements; return result; } public void Free() { if (_locals != null) _locals.Free(); if (_statements != null) _statements.Free(); } internal void Include(BoundSpillSequenceBuilder other) { if (other != null) { IncludeAndFree(ref _locals, ref other._locals); IncludeAndFree(ref _statements, ref other._statements); } } private static void IncludeAndFree<T>(ref ArrayBuilder<T> left, ref ArrayBuilder<T> right) { if (right == null) { return; } if (left == null) { left = right; return; } left.AddRange(right); right.Free(); } public void AddLocal(LocalSymbol local) { if (_locals == null) { _locals = ArrayBuilder<LocalSymbol>.GetInstance(); } _locals.Add(local); } public void AddLocals(ImmutableArray<LocalSymbol> locals) { foreach (var local in locals) { AddLocal(local); } } public void AddStatement(BoundStatement statement) { if (_statements == null) { _statements = ArrayBuilder<BoundStatement>.GetInstance(); } _statements.Add(statement); } public void AddStatements(ImmutableArray<BoundStatement> statements) { foreach (var statement in statements) { AddStatement(statement); } } internal void AddExpressions(ImmutableArray<BoundExpression> expressions) { foreach (var expression in expressions) { AddStatement(new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true }); } } #if DEBUG internal override string Dump() { var node = new TreeDumperNode("boundSpillSequenceBuilder", null, new TreeDumperNode[] { new TreeDumperNode("locals", this.GetLocals(), null), new TreeDumperNode("statements", null, from x in this.GetStatements() select BoundTreeDumperNodeProducer.MakeTree(x)), new TreeDumperNode("value", null, new TreeDumperNode[] { BoundTreeDumperNodeProducer.MakeTree(this.Value) }), new TreeDumperNode("type", this.Type, null) }); return TreeDumper.DumpCompact(node); } #endif } private sealed class LocalSubstituter : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private readonly PooledDictionary<LocalSymbol, LocalSymbol> _tempSubstitution; private LocalSubstituter(PooledDictionary<LocalSymbol, LocalSymbol> tempSubstitution, int recursionDepth = 0) : base(recursionDepth) { _tempSubstitution = tempSubstitution; } public static BoundNode Rewrite(PooledDictionary<LocalSymbol, LocalSymbol> tempSubstitution, BoundNode node) { if (tempSubstitution.Count == 0) { return node; } var substituter = new LocalSubstituter(tempSubstitution); return substituter.Visit(node); } public override BoundNode VisitLocal(BoundLocal node) { if (!node.LocalSymbol.SynthesizedKind.IsLongLived()) { LocalSymbol longLived; if (_tempSubstitution.TryGetValue(node.LocalSymbol, out longLived)) { return node.Update(longLived, node.ConstantValueOpt, node.Type); } } return base.VisitLocal(node); } } internal static BoundStatement Rewrite(BoundStatement body, MethodSymbol method, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var tempSubstitution = PooledDictionary<LocalSymbol, LocalSymbol>.GetInstance(); var spiller = new SpillSequenceSpiller(method, body.Syntax, compilationState, tempSubstitution, diagnostics); BoundNode result = spiller.Visit(body); result = LocalSubstituter.Rewrite(tempSubstitution, result); tempSubstitution.Free(); return (BoundStatement)result; } private BoundExpression VisitExpression(ref BoundSpillSequenceBuilder builder, BoundExpression expression) { var e = (BoundExpression)this.Visit(expression); if (e == null || e.Kind != SpillSequenceBuilderKind) { return e; } var newBuilder = (BoundSpillSequenceBuilder)e; if (builder == null) { builder = newBuilder.Update(null); } else { builder.Include(newBuilder); } return newBuilder.Value; } private static BoundExpression UpdateExpression(BoundSpillSequenceBuilder builder, BoundExpression expression) { if (builder == null) { return expression; } Debug.Assert(builder.Value == null); if (!builder.HasLocals && !builder.HasStatements) { builder.Free(); return expression; } return builder.Update(expression); } private BoundStatement UpdateStatement(BoundSpillSequenceBuilder builder, BoundStatement statement) { if (builder == null) { Debug.Assert(statement != null); return statement; } Debug.Assert(builder.Value == null); if (statement != null) { builder.AddStatement(statement); } var result = new BoundBlock(statement.Syntax, builder.GetLocals(), builder.GetStatements()) { WasCompilerGenerated = true }; builder.Free(); return result; } private BoundExpression Spill( BoundSpillSequenceBuilder builder, BoundExpression expression, RefKind refKind = RefKind.None, bool sideEffectsOnly = false) { Debug.Assert(builder != null); if (builder.Syntax != null) _F.Syntax = builder.Syntax; while (true) { switch (expression.Kind) { case BoundKind.ArrayInitialization: Debug.Assert(refKind == RefKind.None); Debug.Assert(!sideEffectsOnly); var arrayInitialization = (BoundArrayInitialization)expression; var newInitializers = VisitExpressionList(ref builder, arrayInitialization.Initializers, forceSpill: true); return arrayInitialization.Update(newInitializers); case BoundKind.ArgListOperator: Debug.Assert(refKind == RefKind.None); Debug.Assert(!sideEffectsOnly); var argumentList = (BoundArgListOperator)expression; var newArgs = VisitExpressionList(ref builder, argumentList.Arguments, argumentList.ArgumentRefKindsOpt, forceSpill: true); return argumentList.Update(newArgs, argumentList.ArgumentRefKindsOpt, argumentList.Type); case SpillSequenceBuilderKind: var sequenceBuilder = (BoundSpillSequenceBuilder)expression; builder.Include(sequenceBuilder); expression = sequenceBuilder.Value; continue; case BoundKind.Sequence: // neither the side-effects nor the value of the sequence contains await // (otherwise it would be converted to a SpillSequenceBuilder). if (refKind != RefKind.None) { return expression; } goto default; case BoundKind.ThisReference: case BoundKind.BaseReference: if (refKind != RefKind.None || expression.Type.IsReferenceType) { return expression; } goto default; case BoundKind.Parameter: if (refKind != RefKind.None) { return expression; } goto default; case BoundKind.Local: var local = (BoundLocal)expression; if (local.LocalSymbol.SynthesizedKind == SynthesizedLocalKind.Spill || refKind != RefKind.None) { return local; } goto default; case BoundKind.FieldAccess: var field = (BoundFieldAccess)expression; var fieldSymbol = field.FieldSymbol; if (fieldSymbol.IsStatic) { // no need to spill static fields if used as locations or if readonly if (refKind != RefKind.None || fieldSymbol.IsReadOnly) { return field; } goto default; } if (refKind == RefKind.None) goto default; var receiver = Spill(builder, field.ReceiverOpt, fieldSymbol.ContainingType.IsValueType ? refKind : RefKind.None); return field.Update(receiver, fieldSymbol, field.ConstantValueOpt, field.ResultKind, field.Type); case BoundKind.Literal: case BoundKind.TypeExpression: return expression; case BoundKind.ConditionalReceiver: // we will rewrite this as a part of rewriting whole LoweredConditionalAccess // later, if needed return expression; default: if (expression.Type.IsVoidType() || sideEffectsOnly) { builder.AddStatement(_F.ExpressionStatement(expression)); return null; } else { BoundAssignmentOperator assignToTemp; var replacement = _F.StoreToTemp( expression, out assignToTemp, refKind: refKind, kind: SynthesizedLocalKind.Spill, syntaxOpt: _F.Syntax); builder.AddLocal(replacement.LocalSymbol); builder.AddStatement(_F.ExpressionStatement(assignToTemp)); return replacement; } } } } private ImmutableArray<BoundExpression> VisitExpressionList( ref BoundSpillSequenceBuilder builder, ImmutableArray<BoundExpression> args, ImmutableArray<RefKind> refKinds = default(ImmutableArray<RefKind>), bool forceSpill = false, bool sideEffectsOnly = false) { Debug.Assert(!sideEffectsOnly || refKinds.IsDefault); Debug.Assert(refKinds.IsDefault || refKinds.Length == args.Length); if (args.Length == 0) { return args; } var newList = VisitList(args); Debug.Assert(newList.Length == args.Length); int lastSpill; if (forceSpill) { lastSpill = newList.Length; } else { lastSpill = -1; for (int i = newList.Length - 1; i >= 0; i--) { if (newList[i].Kind == SpillSequenceBuilderKind) { lastSpill = i; break; } } } if (lastSpill == -1) { return newList; } if (builder == null) { builder = new BoundSpillSequenceBuilder(lastSpill < newList.Length ? (newList[lastSpill] as BoundSpillSequenceBuilder)?.Syntax : null); } var result = ArrayBuilder<BoundExpression>.GetInstance(newList.Length); // everything up until the last spill must be spilled entirely for (int i = 0; i < lastSpill; i++) { var refKind = refKinds.IsDefault ? RefKind.None : refKinds[i]; var replacement = Spill(builder, newList[i], refKind, sideEffectsOnly); Debug.Assert(sideEffectsOnly || replacement != null); if (!sideEffectsOnly) { result.Add(replacement); } } // the value of the last spill and everything that follows is not spilled if (lastSpill < newList.Length) { var lastSpillNode = (BoundSpillSequenceBuilder)newList[lastSpill]; builder.Include(lastSpillNode); result.Add(lastSpillNode.Value); for (int i = lastSpill + 1; i < newList.Length; i++) { result.Add(newList[i]); } } return result.ToImmutableAndFree(); } #region Statement Visitors public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node) { BoundSpillSequenceBuilder builder = null; var expression = VisitExpression(ref builder, node.Expression); return UpdateStatement(builder, node.Update(expression, node.Cases, node.DefaultLabel, node.EqualityMethod)); } public override BoundNode VisitThrowStatement(BoundThrowStatement node) { BoundSpillSequenceBuilder builder = null; BoundExpression expression = VisitExpression(ref builder, node.ExpressionOpt); return UpdateStatement(builder, node.Update(expression)); } public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) { BoundSpillSequenceBuilder builder = null; BoundExpression expr = VisitExpression(ref builder, node.Expression); Debug.Assert(expr != null); Debug.Assert(builder == null || builder.Value == null); return UpdateStatement(builder, node.Update(expr)); } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { BoundSpillSequenceBuilder builder = null; var condition = VisitExpression(ref builder, node.Condition); return UpdateStatement(builder, node.Update(condition, node.JumpIfTrue, node.Label)); } public override BoundNode VisitReturnStatement(BoundReturnStatement node) { BoundSpillSequenceBuilder builder = null; var expression = VisitExpression(ref builder, node.ExpressionOpt); return UpdateStatement(builder, node.Update(node.RefKind, expression)); } public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) { BoundSpillSequenceBuilder builder = null; var expression = VisitExpression(ref builder, node.Expression); return UpdateStatement(builder, node.Update(expression)); } public override BoundNode VisitCatchBlock(BoundCatchBlock node) { BoundExpression exceptionSourceOpt = (BoundExpression)this.Visit(node.ExceptionSourceOpt); var locals = node.Locals; var exceptionFilterPrologueOpt = node.ExceptionFilterPrologueOpt; Debug.Assert(exceptionFilterPrologueOpt is null); // it is introduced by this pass BoundSpillSequenceBuilder builder = null; var exceptionFilterOpt = VisitExpression(ref builder, node.ExceptionFilterOpt); if (builder is { }) { Debug.Assert(builder.Value is null); locals = locals.AddRange(builder.GetLocals()); exceptionFilterPrologueOpt = new BoundStatementList(node.Syntax, builder.GetStatements()); } BoundBlock body = (BoundBlock)this.Visit(node.Body); TypeSymbol exceptionTypeOpt = this.VisitType(node.ExceptionTypeOpt); return node.Update(locals, exceptionSourceOpt, exceptionTypeOpt, exceptionFilterPrologueOpt, exceptionFilterOpt, body, node.IsSynthesizedAsyncCatchAll); } #if DEBUG public override BoundNode DefaultVisit(BoundNode node) { Debug.Assert(!(node is BoundStatement)); return base.DefaultVisit(node); } #endif #endregion #region Expression Visitors public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) { // An await expression has already been wrapped in a BoundSpillSequence if not at the top level, so // the spilling will occur in the enclosing node. BoundSpillSequenceBuilder builder = null; var expr = VisitExpression(ref builder, node.Expression); return UpdateExpression(builder, node.Update(expr, node.AwaitableInfo, node.Type)); } public override BoundNode VisitSpillSequence(BoundSpillSequence node) { var builder = new BoundSpillSequenceBuilder(node.Syntax); // Ensure later errors (e.g. in async rewriting) are associated with the correct node. _F.Syntax = node.Syntax; builder.AddStatements(VisitList(node.SideEffects)); builder.AddLocals(node.Locals); var value = VisitExpression(ref builder, node.Value); return builder.Update(value); } public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) { BoundSpillSequenceBuilder builder = null; var expr = VisitExpression(ref builder, node.Operand); return UpdateExpression(builder, node.Update(expr, node.IsManaged, node.Type)); } public override BoundNode VisitArgListOperator(BoundArgListOperator node) { BoundSpillSequenceBuilder builder = null; var newArgs = VisitExpressionList(ref builder, node.Arguments); return UpdateExpression(builder, node.Update(newArgs, node.ArgumentRefKindsOpt, node.Type)); } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { BoundSpillSequenceBuilder builder = null; var expression = VisitExpression(ref builder, node.Expression); BoundSpillSequenceBuilder indicesBuilder = null; var indices = this.VisitExpressionList(ref indicesBuilder, node.Indices); if (indicesBuilder != null) { // spill the array if there were await expressions in the indices if (builder == null) { builder = new BoundSpillSequenceBuilder(indicesBuilder.Syntax); } expression = Spill(builder, expression); } if (builder != null) { builder.Include(indicesBuilder); indicesBuilder = builder; builder = null; } return UpdateExpression(indicesBuilder, node.Update(expression, indices, node.Type)); } public override BoundNode VisitArrayCreation(BoundArrayCreation node) { BoundSpillSequenceBuilder builder = null; var init = (BoundArrayInitialization)VisitExpression(ref builder, node.InitializerOpt); ImmutableArray<BoundExpression> bounds; if (builder == null) { bounds = VisitExpressionList(ref builder, node.Bounds); } else { // spill bounds expressions if initializers contain await var boundsBuilder = new BoundSpillSequenceBuilder(builder.Syntax); bounds = VisitExpressionList(ref boundsBuilder, node.Bounds, forceSpill: true); boundsBuilder.Include(builder); builder = boundsBuilder; } return UpdateExpression(builder, node.Update(bounds, init, node.Type)); } public override BoundNode VisitArrayInitialization(BoundArrayInitialization node) { BoundSpillSequenceBuilder builder = null; var initializers = this.VisitExpressionList(ref builder, node.Initializers); return UpdateExpression(builder, node.Update(initializers)); } public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { BoundSpillSequenceBuilder builder = null; BoundExpression count = VisitExpression(ref builder, node.Count); var initializerOpt = (BoundArrayInitialization)VisitExpression(ref builder, node.InitializerOpt); return UpdateExpression(builder, node.Update(node.ElementType, count, initializerOpt, node.Type)); } public override BoundNode VisitArrayLength(BoundArrayLength node) { BoundSpillSequenceBuilder builder = null; var expression = VisitExpression(ref builder, node.Expression); return UpdateExpression(builder, node.Update(expression, node.Type)); } public override BoundNode VisitAsOperator(BoundAsOperator node) { BoundSpillSequenceBuilder builder = null; var operand = VisitExpression(ref builder, node.Operand); return UpdateExpression(builder, node.Update(operand, node.TargetType, node.Conversion, node.Type)); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { BoundSpillSequenceBuilder builder = null; var right = VisitExpression(ref builder, node.Right); BoundExpression left = node.Left; if (builder == null) { left = VisitExpression(ref builder, left); } else { // if the right-hand-side has await, spill the left var leftBuilder = new BoundSpillSequenceBuilder(builder.Syntax); switch (left.Kind) { case BoundKind.Local: case BoundKind.Parameter: // locals and parameters are directly assignable, LHS is not on the stack so nothing to spill break; case BoundKind.FieldAccess: var field = (BoundFieldAccess)left; // static fields are directly assignable, LHS is not on the stack, nothing to spill if (field.FieldSymbol.IsStatic) break; // instance fields are directly assignable, but receiver is pushed, so need to spill that. left = fieldWithSpilledReceiver(field, ref leftBuilder, isAssignmentTarget: true); break; case BoundKind.ArrayAccess: var arrayAccess = (BoundArrayAccess)left; // array and indices are pushed on stack so need to spill that var expression = VisitExpression(ref leftBuilder, arrayAccess.Expression); expression = Spill(leftBuilder, expression, RefKind.None); var indices = this.VisitExpressionList(ref leftBuilder, arrayAccess.Indices, forceSpill: true); left = arrayAccess.Update(expression, indices, arrayAccess.Type); break; default: // must be something indirectly assignable, just visit and spill as an ordinary Ref (not a RefReadOnly!!) // // NOTE: in some cases this will result in spiller producing an error. // For example if the LHS is a ref-returning method like // // obj.RefReturning(a, b, c) = await Something(); // // the spiller would eventually have to spill the evaluation result of "refReturning" call as an ordinary Ref, // which it can't. left = Spill(leftBuilder, VisitExpression(ref leftBuilder, left), RefKind.Ref); break; } leftBuilder.Include(builder); builder = leftBuilder; } return UpdateExpression(builder, node.Update(left, right, node.IsRef, node.Type)); BoundExpression fieldWithSpilledReceiver(BoundFieldAccess field, ref BoundSpillSequenceBuilder leftBuilder, bool isAssignmentTarget) { var generateDummyFieldAccess = false; if (!field.FieldSymbol.IsStatic) { Debug.Assert(field.ReceiverOpt is object); BoundExpression receiver; if (field.FieldSymbol.ContainingType.IsReferenceType) { // a reference type can always live across await so Spill using leftBuilder receiver = Spill(leftBuilder, VisitExpression(ref leftBuilder, field.ReceiverOpt)); // dummy field access to trigger NRE // a.b = c will trigger a NRE if a is null on assignment, // but a.b.c = d will trigger a NRE if a is null before evaluating d // so check whether we assign to the field directly generateDummyFieldAccess = !isAssignmentTarget; } else if (field.ReceiverOpt is BoundArrayAccess arrayAccess) { // an arrayAccess returns a ref so can only be called after the await, but spill expression and indices var expression = VisitExpression(ref leftBuilder, arrayAccess.Expression); expression = Spill(leftBuilder, expression, RefKind.None); var indices = this.VisitExpressionList(ref leftBuilder, arrayAccess.Indices, forceSpill: true); receiver = arrayAccess.Update(expression, indices, arrayAccess.Type); // dummy array access to trigger IndexOutRangeException or NRE // we only need this if the array access is a receiver since // a[0] = b triggers a NRE/IORE on assignment // but a[0].b = c triggers an NRE/IORE before evaluating c Spill(leftBuilder, receiver, sideEffectsOnly: true); } else if (field.ReceiverOpt is BoundFieldAccess receiverField) { receiver = fieldWithSpilledReceiver(receiverField, ref leftBuilder, isAssignmentTarget: false); } else { receiver = Spill(leftBuilder, VisitExpression(ref leftBuilder, field.ReceiverOpt), RefKind.Ref); } field = field.Update(receiver, field.FieldSymbol, field.ConstantValueOpt, field.ResultKind, field.Type); } if (generateDummyFieldAccess) { Spill(leftBuilder, field, sideEffectsOnly: true); } return field; } } public override BoundNode VisitBadExpression(BoundBadExpression node) { // Cannot recurse into BadExpression children return node; } public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { BoundSpillSequenceBuilder builder = null; var right = VisitExpression(ref builder, node.Right); BoundExpression left; if (builder == null) { left = VisitExpression(ref builder, node.Left); } else { var leftBuilder = new BoundSpillSequenceBuilder(builder.Syntax); left = VisitExpression(ref leftBuilder, node.Left); left = Spill(leftBuilder, left); if (node.OperatorKind == BinaryOperatorKind.LogicalBoolOr || node.OperatorKind == BinaryOperatorKind.LogicalBoolAnd) { var tmp = _F.SynthesizedLocal(node.Type, kind: SynthesizedLocalKind.Spill, syntax: _F.Syntax); leftBuilder.AddLocal(tmp); leftBuilder.AddStatement(_F.Assignment(_F.Local(tmp), left)); leftBuilder.AddStatement(_F.If( node.OperatorKind == BinaryOperatorKind.LogicalBoolAnd ? _F.Local(tmp) : _F.Not(_F.Local(tmp)), UpdateStatement(builder, _F.Assignment(_F.Local(tmp), right)))); return UpdateExpression(leftBuilder, _F.Local(tmp)); } else { // if the right-hand-side has await, spill the left leftBuilder.Include(builder); builder = leftBuilder; } } return UpdateExpression(builder, node.Update(node.OperatorKind, node.ConstantValue, node.Method, node.ConstrainedToType, node.ResultKind, left, right, node.Type)); } public override BoundNode VisitCall(BoundCall node) { BoundSpillSequenceBuilder builder = null; var arguments = this.VisitExpressionList(ref builder, node.Arguments, node.ArgumentRefKindsOpt); BoundExpression receiver = null; if (builder == null || node.ReceiverOpt is BoundTypeExpression) { receiver = VisitExpression(ref builder, node.ReceiverOpt); } else if (node.Method.RequiresInstanceReceiver) { // spill the receiver if there were await expressions in the arguments var receiverBuilder = new BoundSpillSequenceBuilder(builder.Syntax); receiver = node.ReceiverOpt; RefKind refKind = ReceiverSpillRefKind(receiver); receiver = Spill(receiverBuilder, VisitExpression(ref receiverBuilder, receiver), refKind: refKind); receiverBuilder.Include(builder); builder = receiverBuilder; } return UpdateExpression(builder, node.Update(receiver, node.Method, arguments)); } private static RefKind ReceiverSpillRefKind(BoundExpression receiver) { var result = RefKind.None; if (!receiver.Type.IsReferenceType && LocalRewriter.CanBePassedByReference(receiver)) { result = receiver.Type.IsReadOnly ? RefKind.In : RefKind.Ref; } return result; } public override BoundNode VisitConditionalOperator(BoundConditionalOperator node) { BoundSpillSequenceBuilder conditionBuilder = null; var condition = VisitExpression(ref conditionBuilder, node.Condition); BoundSpillSequenceBuilder consequenceBuilder = null; var consequence = VisitExpression(ref consequenceBuilder, node.Consequence); BoundSpillSequenceBuilder alternativeBuilder = null; var alternative = VisitExpression(ref alternativeBuilder, node.Alternative); if (consequenceBuilder == null && alternativeBuilder == null) { return UpdateExpression(conditionBuilder, node.Update(node.IsRef, condition, consequence, alternative, node.ConstantValueOpt, node.NaturalTypeOpt, node.WasTargetTyped, node.Type)); } if (conditionBuilder == null) conditionBuilder = new BoundSpillSequenceBuilder((consequenceBuilder ?? alternativeBuilder).Syntax); if (consequenceBuilder == null) consequenceBuilder = new BoundSpillSequenceBuilder(alternativeBuilder.Syntax); if (alternativeBuilder == null) alternativeBuilder = new BoundSpillSequenceBuilder(consequenceBuilder.Syntax); if (node.Type.IsVoidType()) { conditionBuilder.AddStatement( _F.If(condition, UpdateStatement(consequenceBuilder, _F.ExpressionStatement(consequence)), UpdateStatement(alternativeBuilder, _F.ExpressionStatement(alternative)))); return conditionBuilder.Update(_F.Default(node.Type)); } else { var tmp = _F.SynthesizedLocal(node.Type, kind: SynthesizedLocalKind.Spill, syntax: _F.Syntax); conditionBuilder.AddLocal(tmp); conditionBuilder.AddStatement( _F.If(condition, UpdateStatement(consequenceBuilder, _F.Assignment(_F.Local(tmp), consequence)), UpdateStatement(alternativeBuilder, _F.Assignment(_F.Local(tmp), alternative)))); return conditionBuilder.Update(_F.Local(tmp)); } } public override BoundNode VisitConversion(BoundConversion node) { if (node.ConversionKind == ConversionKind.AnonymousFunction && node.Type.IsExpressionTree()) { // Expression trees do not contain any code that requires spilling. return node; } BoundSpillSequenceBuilder builder = null; var operand = VisitExpression(ref builder, node.Operand); return UpdateExpression( builder, node.UpdateOperand(operand)); } public override BoundNode VisitPassByCopy(BoundPassByCopy node) { BoundSpillSequenceBuilder builder = null; var expression = VisitExpression(ref builder, node.Expression); return UpdateExpression( builder, node.Update( expression, type: node.Type)); } public override BoundNode VisitMethodGroup(BoundMethodGroup node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { BoundSpillSequenceBuilder builder = null; var argument = VisitExpression(ref builder, node.Argument); return UpdateExpression(builder, node.Update(argument, node.MethodOpt, node.IsExtensionMethod, node.Type)); } public override BoundNode VisitFieldAccess(BoundFieldAccess node) { BoundSpillSequenceBuilder builder = null; var receiver = VisitExpression(ref builder, node.ReceiverOpt); return UpdateExpression(builder, node.Update(receiver, node.FieldSymbol, node.ConstantValueOpt, node.ResultKind, node.Type)); } public override BoundNode VisitIsOperator(BoundIsOperator node) { BoundSpillSequenceBuilder builder = null; var operand = VisitExpression(ref builder, node.Operand); return UpdateExpression(builder, node.Update(operand, node.TargetType, node.Conversion, node.Type)); } public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { BoundSpillSequenceBuilder builder = null; var right = VisitExpression(ref builder, node.RightOperand); BoundExpression left; if (builder == null) { left = VisitExpression(ref builder, node.LeftOperand); } else { var leftBuilder = new BoundSpillSequenceBuilder(builder.Syntax); left = VisitExpression(ref leftBuilder, node.LeftOperand); left = Spill(leftBuilder, left); var tmp = _F.SynthesizedLocal(node.Type, kind: SynthesizedLocalKind.Spill, syntax: _F.Syntax); leftBuilder.AddLocal(tmp); leftBuilder.AddStatement(_F.Assignment(_F.Local(tmp), left)); leftBuilder.AddStatement(_F.If( _F.ObjectEqual(_F.Local(tmp), _F.Null(left.Type)), UpdateStatement(builder, _F.Assignment(_F.Local(tmp), right)))); return UpdateExpression(leftBuilder, _F.Local(tmp)); } return UpdateExpression(builder, node.Update(left, right, node.LeftConversion, node.OperatorResultKind, node.Type)); } public override BoundNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) { var receiverRefKind = ReceiverSpillRefKind(node.Receiver); BoundSpillSequenceBuilder receiverBuilder = null; var receiver = VisitExpression(ref receiverBuilder, node.Receiver); BoundSpillSequenceBuilder whenNotNullBuilder = null; var whenNotNull = VisitExpression(ref whenNotNullBuilder, node.WhenNotNull); BoundSpillSequenceBuilder whenNullBuilder = null; var whenNullOpt = VisitExpression(ref whenNullBuilder, node.WhenNullOpt); if (whenNotNullBuilder == null && whenNullBuilder == null) { return UpdateExpression(receiverBuilder, node.Update(receiver, node.HasValueMethodOpt, whenNotNull, whenNullOpt, node.Id, node.Type)); } if (receiverBuilder == null) receiverBuilder = new BoundSpillSequenceBuilder((whenNotNullBuilder ?? whenNullBuilder).Syntax); if (whenNotNullBuilder == null) whenNotNullBuilder = new BoundSpillSequenceBuilder(whenNullBuilder.Syntax); if (whenNullBuilder == null) whenNullBuilder = new BoundSpillSequenceBuilder(whenNotNullBuilder.Syntax); BoundExpression condition; if (receiver.Type.IsReferenceType || receiver.Type.IsValueType || receiverRefKind == RefKind.None) { // spill to a clone receiver = Spill(receiverBuilder, receiver, RefKind.None); var hasValueOpt = node.HasValueMethodOpt; if (hasValueOpt == null) { condition = _F.ObjectNotEqual( _F.Convert(_F.SpecialType(SpecialType.System_Object), receiver), _F.Null(_F.SpecialType(SpecialType.System_Object))); } else { condition = _F.Call(receiver, hasValueOpt); } } else { Debug.Assert(node.HasValueMethodOpt == null); receiver = Spill(receiverBuilder, receiver, RefKind.Ref); var clone = _F.SynthesizedLocal(receiver.Type, _F.Syntax, refKind: RefKind.None, kind: SynthesizedLocalKind.Spill); receiverBuilder.AddLocal(clone); // (object)default(T) != null var isNotClass = _F.ObjectNotEqual( _F.Convert(_F.SpecialType(SpecialType.System_Object), _F.Default(receiver.Type)), _F.Null(_F.SpecialType(SpecialType.System_Object))); // isNotCalss || {clone = receiver; (object)clone != null} condition = _F.LogicalOr( isNotClass, _F.MakeSequence( _F.AssignmentExpression(_F.Local(clone), receiver), _F.ObjectNotEqual( _F.Convert(_F.SpecialType(SpecialType.System_Object), _F.Local(clone)), _F.Null(_F.SpecialType(SpecialType.System_Object)))) ); receiver = _F.ComplexConditionalReceiver(receiver, _F.Local(clone)); } if (node.Type.IsVoidType()) { var whenNotNullStatement = UpdateStatement(whenNotNullBuilder, _F.ExpressionStatement(whenNotNull)); whenNotNullStatement = ConditionalReceiverReplacer.Replace(whenNotNullStatement, receiver, node.Id, RecursionDepth); Debug.Assert(whenNullOpt == null || !LocalRewriter.ReadIsSideeffecting(whenNullOpt)); receiverBuilder.AddStatement(_F.If(condition, whenNotNullStatement)); return receiverBuilder.Update(_F.Default(node.Type)); } else { var tmp = _F.SynthesizedLocal(node.Type, kind: SynthesizedLocalKind.Spill, syntax: _F.Syntax); var whenNotNullStatement = UpdateStatement(whenNotNullBuilder, _F.Assignment(_F.Local(tmp), whenNotNull)); whenNotNullStatement = ConditionalReceiverReplacer.Replace(whenNotNullStatement, receiver, node.Id, RecursionDepth); whenNullOpt = whenNullOpt ?? _F.Default(node.Type); receiverBuilder.AddLocal(tmp); receiverBuilder.AddStatement( _F.If(condition, whenNotNullStatement, UpdateStatement(whenNullBuilder, _F.Assignment(_F.Local(tmp), whenNullOpt)))); return receiverBuilder.Update(_F.Local(tmp)); } } private sealed class ConditionalReceiverReplacer : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private readonly BoundExpression _receiver; private readonly int _receiverId; #if DEBUG // we must replace exactly one node private int _replaced; #endif private ConditionalReceiverReplacer(BoundExpression receiver, int receiverId, int recursionDepth) : base(recursionDepth) { _receiver = receiver; _receiverId = receiverId; } public static BoundStatement Replace(BoundNode node, BoundExpression receiver, int receiverID, int recursionDepth) { var replacer = new ConditionalReceiverReplacer(receiver, receiverID, recursionDepth); var result = (BoundStatement)replacer.Visit(node); #if DEBUG Debug.Assert(replacer._replaced == 1, "should have replaced exactly one node"); #endif return result; } public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node) { if (node.Id == _receiverId) { #if DEBUG _replaced++; #endif return _receiver; } return node; } } public override BoundNode VisitLambda(BoundLambda node) { var oldCurrentFunction = _F.CurrentFunction; _F.CurrentFunction = node.Symbol; var result = base.VisitLambda(node); _F.CurrentFunction = oldCurrentFunction; return result; } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { var oldCurrentFunction = _F.CurrentFunction; _F.CurrentFunction = node.Symbol; var result = base.VisitLocalFunctionStatement(node); _F.CurrentFunction = oldCurrentFunction; return result; } public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) { Debug.Assert(node.InitializerExpressionOpt == null); BoundSpillSequenceBuilder builder = null; var arguments = this.VisitExpressionList(ref builder, node.Arguments, node.ArgumentRefKindsOpt); return UpdateExpression(builder, node.Update(node.Constructor, arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.ConstantValueOpt, node.InitializerExpressionOpt, node.Type)); } public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) { BoundSpillSequenceBuilder builder = null; var index = VisitExpression(ref builder, node.Index); BoundExpression expression; if (builder == null) { expression = VisitExpression(ref builder, node.Expression); } else { var expressionBuilder = new BoundSpillSequenceBuilder(builder.Syntax); expression = VisitExpression(ref expressionBuilder, node.Expression); expression = Spill(expressionBuilder, expression); expressionBuilder.Include(builder); builder = expressionBuilder; } return UpdateExpression(builder, node.Update(expression, index, node.Checked, node.Type)); } public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { BoundSpillSequenceBuilder builder = null; var operand = VisitExpression(ref builder, node.Operand); return UpdateExpression(builder, node.Update(operand, node.Type)); } public override BoundNode VisitSequence(BoundSequence node) { BoundSpillSequenceBuilder valueBuilder = null; var value = VisitExpression(ref valueBuilder, node.Value); BoundSpillSequenceBuilder builder = null; var sideEffects = VisitExpressionList(ref builder, node.SideEffects, forceSpill: valueBuilder != null, sideEffectsOnly: true); if (builder == null && valueBuilder == null) { return node.Update(node.Locals, sideEffects, value, node.Type); } if (builder == null) { builder = new BoundSpillSequenceBuilder(valueBuilder.Syntax); } PromoteAndAddLocals(builder, node.Locals); builder.AddExpressions(sideEffects); builder.Include(valueBuilder); return builder.Update(value); } public override BoundNode VisitThrowExpression(BoundThrowExpression node) { BoundSpillSequenceBuilder builder = null; BoundExpression operand = VisitExpression(ref builder, node.Expression); return UpdateExpression(builder, node.Update(operand, node.Type)); } /// <summary> /// If an expression node that declares synthesized short-lived locals (currently only sequence) contains /// a spill sequence (from an await or switch expression), these locals become long-lived since their /// values may be read by code that follows. We promote these variables to long-lived of kind /// <see cref="SynthesizedLocalKind.Spill"/>. /// </summary> private void PromoteAndAddLocals(BoundSpillSequenceBuilder builder, ImmutableArray<LocalSymbol> locals) { foreach (var local in locals) { if (local.SynthesizedKind.IsLongLived()) { builder.AddLocal(local); } else { LocalSymbol longLived = local.WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind.Spill, _F.Syntax); _tempSubstitution.Add(local, longLived); builder.AddLocal(longLived); } } } public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) { BoundSpillSequenceBuilder builder = null; BoundExpression operand = VisitExpression(ref builder, node.Operand); return UpdateExpression(builder, node.Update(node.OperatorKind, operand, node.ConstantValueOpt, node.MethodOpt, node.ConstrainedToTypeOpt, node.ResultKind, node.Type)); } public override BoundNode VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node) { BoundSpillSequenceBuilder builder = null; BoundExpression operand = VisitExpression(ref builder, node.Operand); return UpdateExpression(builder, node.Update(operand, node.ConversionMethod, node.Type)); } public override BoundNode VisitSequencePointExpression(BoundSequencePointExpression node) { BoundSpillSequenceBuilder builder = null; BoundExpression expression = VisitExpression(ref builder, node.Expression); return UpdateExpression(builder, node.Update(expression, node.Type)); } #endregion } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/VisualStudio/CSharp/Test/Interactive/InteractiveWindowTestHost.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 Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.InteractiveWindow; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive { public sealed class InteractiveWindowTestHost : IDisposable { internal readonly IInteractiveWindow Window; internal readonly TestInteractiveEvaluator Evaluator; internal InteractiveWindowTestHost(IInteractiveWindowFactoryService interactiveWindowFactory) { Evaluator = new TestInteractiveEvaluator(); Window = interactiveWindowFactory.CreateWindow(Evaluator); Window.InitializeAsync().Wait(); } public void Dispose() { if (Window != null) { // close interactive host process: Window.Evaluator?.Dispose(); // dispose buffer: Window.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. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.InteractiveWindow; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive { public sealed class InteractiveWindowTestHost : IDisposable { internal readonly IInteractiveWindow Window; internal readonly TestInteractiveEvaluator Evaluator; internal InteractiveWindowTestHost(IInteractiveWindowFactoryService interactiveWindowFactory) { Evaluator = new TestInteractiveEvaluator(); Window = interactiveWindowFactory.CreateWindow(Evaluator); Window.InitializeAsync().Wait(); } public void Dispose() { if (Window != null) { // close interactive host process: Window.Evaluator?.Dispose(); // dispose buffer: Window.Dispose(); } } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Workspaces/Core/Portable/Workspace/FileTextLoader.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.Composition; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal static class FileTextLoaderOptions { /// <summary> /// Hidden registry key to control maximum size of a text file we will read into memory. /// we have this option to reduce a chance of OOM when user adds massive size files to the solution. /// Default threshold is 100MB which came from some internal data on big files and some discussion. /// /// User can override default value by setting DWORD value on FileLengthThreshold in /// "[VS HIVE]\Roslyn\Internal\Performance\Text" /// </summary> internal static readonly Option<long> FileLengthThreshold = new(nameof(FileTextLoaderOptions), nameof(FileLengthThreshold), defaultValue: 100 * 1024 * 1024, storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\Text\FileLengthThreshold")); } [ExportOptionProvider, Shared] internal class FileTextLoaderOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FileTextLoaderOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( FileTextLoaderOptions.FileLengthThreshold); } [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public class FileTextLoader : TextLoader { /// <summary> /// Absolute path of the file. /// </summary> public string Path { get; } /// <summary> /// Specifies an encoding to be used if the actual encoding of the file /// can't be determined from the stream content (the stream doesn't start with Byte Order Mark). /// If <c>null</c> auto-detect heuristics are used to determine the encoding. /// Note that if the stream starts with Byte Order Mark the value of <see cref="DefaultEncoding"/> is ignored. /// </summary> public Encoding? DefaultEncoding { get; } /// <summary> /// Creates a content loader for specified file. /// </summary> /// <param name="path">An absolute file path.</param> /// <param name="defaultEncoding"> /// Specifies an encoding to be used if the actual encoding can't be determined from the stream content (the stream doesn't start with Byte Order Mark). /// If not specified auto-detect heuristics are used to determine the encoding. /// Note that if the stream starts with Byte Order Mark the value of <paramref name="defaultEncoding"/> is ignored. /// </param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is not an absolute path.</exception> public FileTextLoader(string path, Encoding? defaultEncoding) { CompilerPathUtilities.RequireAbsolutePath(path, "path"); Path = path; DefaultEncoding = defaultEncoding; } internal sealed override string FilePath => Path; protected virtual SourceText CreateText(Stream stream, Workspace workspace) { var factory = workspace.Services.GetRequiredService<ITextFactoryService>(); return factory.CreateText(stream, DefaultEncoding); } /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException"></exception> /// <exception cref="InvalidDataException"></exception> public override async Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { ValidateFileLength(workspace, Path); var prevLastWriteTime = FileUtilities.GetFileTimeStamp(Path); TextAndVersion textAndVersion; // In many .NET Framework versions (specifically the 4.5.* series, but probably much earlier // and also later) there is this particularly interesting bit in FileStream.BeginReadAsync: // // // [ed: full comment clipped for brevity] // // // // If we did a sync read to fill the buffer, we could avoid the // // problem, and any async read less than 64K gets turned into a // // synchronous read by NT anyways... // if (numBytes < _bufferSize) // { // if (_buffer == null) _buffer = new byte[_bufferSize]; // IAsyncResult bufferRead = BeginReadCore(_buffer, 0, _bufferSize, null, null, 0); // _readLen = EndRead(bufferRead); // // In English, this means that if you do a asynchronous read for smaller than _bufferSize, // this is implemented by the framework by starting an asynchronous read, and then // blocking your thread until that read is completed. The comment implies this is "fine" // because the asynchronous read will actually be synchronous and thus EndRead won't do // any blocking -- it'll be an effective no-op. In theory, everything is fine here. // // In reality, this can end very poorly. That read in fact can be asynchronous, which means the // EndRead will enter a wait and block the thread. If we are running that call to ReadAsync on a // thread pool thread that completed a previous piece of IO, it means there has to be another // thread available to service the completion of that request in order for our thread to make // progress. Why is this worse than the claim about the operating system turning an // asynchronous read into a synchronous one? If the underlying native ReadFile completes // synchronously, that would mean just our thread is being blocked, and will be unblocked once // the kernel gets done with our work. In this case, if the OS does do the read asynchronously // we are now dependent on another thread being available to unblock us. // // So how does ths manifest itself? We have seen dumps from customers reporting hangs where // we have over a hundred thread pool threads all blocked on EndRead() calls as we read this stream. // In these cases, the user had just completed a build that had a bunch of XAML files, and // this resulted in many .g.i.cs files being written and updated. As a result, Roslyn is trying to // re-read them to provide a new compilation to the XAML language service that is asking for it. // Inspecting these dumps and sampling some of the threads made some notable discoveries: // // 1. When there was a read blocked, it was the _last_ chunk that we were reading in the file in // the file that we were reading. This leads me to believe that it isn't simply very slow IO // (like a network drive), because in that case I'd expect to see some threads in different // places than others. // 2. Some stacks were starting by the continuation of a ReadAsync, and some were the first read // of a file from the background parser. In the first case, all of those threads were if the // files were over 4K in size. The ones with the BackgroundParser still on the stack were files // less than 4K in size. // 3. The "time unresponsive" in seconds correlated with roughly the number of threads we had // blocked, which makes me think we were impacted by the once-per-second hill climbing algorithm // used by the thread pool. // // So what's my analysis? When the XAML language service updated all the files, we kicked off // background parses for all of them. If the file was over 4K the asynchronous read actually did // happen (see point #2), but we'd eventually block the thread pool reading the last chunk. // Point #1 confirms that it was always the last chunk. And in small file cases, we'd block on // the first chunk. But in either case, we'd be blocking off a thread pool thread until another // thread pool thread was available. Since we had enough requests going (over a hundred), // sometimes the user got unlucky and all the threads got blocked. At this point, the CLR // started slowly kicking off more threads, but each time it'd start a new thread rather than // starting work that would be needed to unblock a thread, it just handled an IO that resulted // in another file read hitting the end of the file and another thread would get blocked. The // CLR then must kick off another thread, rinse, repeat. Eventually it'll make progress once // there's no more pending IO requests, everything will complete, and life then continues. // // To work around this issue, we set bufferSize to 1, which means that all reads should bypass // this logic. This is tracked by https://github.com/dotnet/corefx/issues/6007, at least in // corefx. We also open the file for reading with FileShare mode read/write/delete so that // we do not lock this file. using (var stream = FileUtilities.RethrowExceptionsAsIOException(() => new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 1, useAsync: true))) { var version = VersionStamp.Create(prevLastWriteTime); // we do this so that we asynchronously read from file. and this should allocate less for IDE case. // but probably not for command line case where it doesn't use more sophisticated services. using var readStream = await SerializableBytes.CreateReadableStreamAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); var text = CreateText(readStream, workspace); textAndVersion = TextAndVersion.Create(text, version, Path); } // Check if the file was definitely modified and closed while we were reading. In this case, we know the read we got was // probably invalid, so throw an IOException which indicates to our caller that we should automatically attempt a re-read. // If the file hasn't been closed yet and there's another writer, we will rely on file change notifications to notify us // and reload the file. var newLastWriteTime = FileUtilities.GetFileTimeStamp(Path); if (!newLastWriteTime.Equals(prevLastWriteTime)) { var message = string.Format(WorkspacesResources.File_was_externally_modified_colon_0, Path); throw new IOException(message); } return textAndVersion; } /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException"></exception> /// <exception cref="InvalidDataException"></exception> internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { ValidateFileLength(workspace, Path); var prevLastWriteTime = FileUtilities.GetFileTimeStamp(Path); TextAndVersion textAndVersion; // Open file for reading with FileShare mode read/write/delete so that we do not lock this file. using (var stream = FileUtilities.RethrowExceptionsAsIOException(() => new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 4096, useAsync: false))) { var version = VersionStamp.Create(prevLastWriteTime); var text = CreateText(stream, workspace); textAndVersion = TextAndVersion.Create(text, version, Path); } // Check if the file was definitely modified and closed while we were reading. In this case, we know the read we got was // probably invalid, so throw an IOException which indicates to our caller that we should automatically attempt a re-read. // If the file hasn't been closed yet and there's another writer, we will rely on file change notifications to notify us // and reload the file. var newLastWriteTime = FileUtilities.GetFileTimeStamp(Path); if (!newLastWriteTime.Equals(prevLastWriteTime)) { var message = string.Format(WorkspacesResources.File_was_externally_modified_colon_0, Path); throw new IOException(message); } return textAndVersion; } private string GetDebuggerDisplay() => nameof(Path) + " = " + Path; private static void ValidateFileLength(Workspace workspace, string path) { // Validate file length is under our threshold. // Otherwise, rather than reading the content into the memory, we will throw // InvalidDataException to caller of FileTextLoader.LoadText to deal with // the situation. // // check this (http://source.roslyn.io/#Microsoft.CodeAnalysis.Workspaces/Workspace/Solution/TextDocumentState.cs,132) // to see how workspace deal with exception from FileTextLoader. other consumer can handle the exception differently var fileLength = FileUtilities.GetFileLength(path); var threshold = workspace.Options.GetOption(FileTextLoaderOptions.FileLengthThreshold); if (fileLength > threshold) { // log max file length which will log to VS telemetry in VS host Logger.Log(FunctionId.FileTextLoader_FileLengthThresholdExceeded, KeyValueLogMessage.Create(m => { m["FileLength"] = fileLength; m["Ext"] = PathUtilities.GetExtension(path); })); var message = string.Format(WorkspacesResources.File_0_size_of_1_exceeds_maximum_allowed_size_of_2, path, fileLength, threshold); throw new InvalidDataException(message); } } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal static class FileTextLoaderOptions { /// <summary> /// Hidden registry key to control maximum size of a text file we will read into memory. /// we have this option to reduce a chance of OOM when user adds massive size files to the solution. /// Default threshold is 100MB which came from some internal data on big files and some discussion. /// /// User can override default value by setting DWORD value on FileLengthThreshold in /// "[VS HIVE]\Roslyn\Internal\Performance\Text" /// </summary> internal static readonly Option<long> FileLengthThreshold = new(nameof(FileTextLoaderOptions), nameof(FileLengthThreshold), defaultValue: 100 * 1024 * 1024, storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\Text\FileLengthThreshold")); } [ExportOptionProvider, Shared] internal class FileTextLoaderOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FileTextLoaderOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( FileTextLoaderOptions.FileLengthThreshold); } [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public class FileTextLoader : TextLoader { /// <summary> /// Absolute path of the file. /// </summary> public string Path { get; } /// <summary> /// Specifies an encoding to be used if the actual encoding of the file /// can't be determined from the stream content (the stream doesn't start with Byte Order Mark). /// If <c>null</c> auto-detect heuristics are used to determine the encoding. /// Note that if the stream starts with Byte Order Mark the value of <see cref="DefaultEncoding"/> is ignored. /// </summary> public Encoding? DefaultEncoding { get; } /// <summary> /// Creates a content loader for specified file. /// </summary> /// <param name="path">An absolute file path.</param> /// <param name="defaultEncoding"> /// Specifies an encoding to be used if the actual encoding can't be determined from the stream content (the stream doesn't start with Byte Order Mark). /// If not specified auto-detect heuristics are used to determine the encoding. /// Note that if the stream starts with Byte Order Mark the value of <paramref name="defaultEncoding"/> is ignored. /// </param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is not an absolute path.</exception> public FileTextLoader(string path, Encoding? defaultEncoding) { CompilerPathUtilities.RequireAbsolutePath(path, "path"); Path = path; DefaultEncoding = defaultEncoding; } internal sealed override string FilePath => Path; protected virtual SourceText CreateText(Stream stream, Workspace workspace) { var factory = workspace.Services.GetRequiredService<ITextFactoryService>(); return factory.CreateText(stream, DefaultEncoding); } /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException"></exception> /// <exception cref="InvalidDataException"></exception> public override async Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { ValidateFileLength(workspace, Path); var prevLastWriteTime = FileUtilities.GetFileTimeStamp(Path); TextAndVersion textAndVersion; // In many .NET Framework versions (specifically the 4.5.* series, but probably much earlier // and also later) there is this particularly interesting bit in FileStream.BeginReadAsync: // // // [ed: full comment clipped for brevity] // // // // If we did a sync read to fill the buffer, we could avoid the // // problem, and any async read less than 64K gets turned into a // // synchronous read by NT anyways... // if (numBytes < _bufferSize) // { // if (_buffer == null) _buffer = new byte[_bufferSize]; // IAsyncResult bufferRead = BeginReadCore(_buffer, 0, _bufferSize, null, null, 0); // _readLen = EndRead(bufferRead); // // In English, this means that if you do a asynchronous read for smaller than _bufferSize, // this is implemented by the framework by starting an asynchronous read, and then // blocking your thread until that read is completed. The comment implies this is "fine" // because the asynchronous read will actually be synchronous and thus EndRead won't do // any blocking -- it'll be an effective no-op. In theory, everything is fine here. // // In reality, this can end very poorly. That read in fact can be asynchronous, which means the // EndRead will enter a wait and block the thread. If we are running that call to ReadAsync on a // thread pool thread that completed a previous piece of IO, it means there has to be another // thread available to service the completion of that request in order for our thread to make // progress. Why is this worse than the claim about the operating system turning an // asynchronous read into a synchronous one? If the underlying native ReadFile completes // synchronously, that would mean just our thread is being blocked, and will be unblocked once // the kernel gets done with our work. In this case, if the OS does do the read asynchronously // we are now dependent on another thread being available to unblock us. // // So how does ths manifest itself? We have seen dumps from customers reporting hangs where // we have over a hundred thread pool threads all blocked on EndRead() calls as we read this stream. // In these cases, the user had just completed a build that had a bunch of XAML files, and // this resulted in many .g.i.cs files being written and updated. As a result, Roslyn is trying to // re-read them to provide a new compilation to the XAML language service that is asking for it. // Inspecting these dumps and sampling some of the threads made some notable discoveries: // // 1. When there was a read blocked, it was the _last_ chunk that we were reading in the file in // the file that we were reading. This leads me to believe that it isn't simply very slow IO // (like a network drive), because in that case I'd expect to see some threads in different // places than others. // 2. Some stacks were starting by the continuation of a ReadAsync, and some were the first read // of a file from the background parser. In the first case, all of those threads were if the // files were over 4K in size. The ones with the BackgroundParser still on the stack were files // less than 4K in size. // 3. The "time unresponsive" in seconds correlated with roughly the number of threads we had // blocked, which makes me think we were impacted by the once-per-second hill climbing algorithm // used by the thread pool. // // So what's my analysis? When the XAML language service updated all the files, we kicked off // background parses for all of them. If the file was over 4K the asynchronous read actually did // happen (see point #2), but we'd eventually block the thread pool reading the last chunk. // Point #1 confirms that it was always the last chunk. And in small file cases, we'd block on // the first chunk. But in either case, we'd be blocking off a thread pool thread until another // thread pool thread was available. Since we had enough requests going (over a hundred), // sometimes the user got unlucky and all the threads got blocked. At this point, the CLR // started slowly kicking off more threads, but each time it'd start a new thread rather than // starting work that would be needed to unblock a thread, it just handled an IO that resulted // in another file read hitting the end of the file and another thread would get blocked. The // CLR then must kick off another thread, rinse, repeat. Eventually it'll make progress once // there's no more pending IO requests, everything will complete, and life then continues. // // To work around this issue, we set bufferSize to 1, which means that all reads should bypass // this logic. This is tracked by https://github.com/dotnet/corefx/issues/6007, at least in // corefx. We also open the file for reading with FileShare mode read/write/delete so that // we do not lock this file. using (var stream = FileUtilities.RethrowExceptionsAsIOException(() => new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 1, useAsync: true))) { var version = VersionStamp.Create(prevLastWriteTime); // we do this so that we asynchronously read from file. and this should allocate less for IDE case. // but probably not for command line case where it doesn't use more sophisticated services. using var readStream = await SerializableBytes.CreateReadableStreamAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); var text = CreateText(readStream, workspace); textAndVersion = TextAndVersion.Create(text, version, Path); } // Check if the file was definitely modified and closed while we were reading. In this case, we know the read we got was // probably invalid, so throw an IOException which indicates to our caller that we should automatically attempt a re-read. // If the file hasn't been closed yet and there's another writer, we will rely on file change notifications to notify us // and reload the file. var newLastWriteTime = FileUtilities.GetFileTimeStamp(Path); if (!newLastWriteTime.Equals(prevLastWriteTime)) { var message = string.Format(WorkspacesResources.File_was_externally_modified_colon_0, Path); throw new IOException(message); } return textAndVersion; } /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException"></exception> /// <exception cref="InvalidDataException"></exception> internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { ValidateFileLength(workspace, Path); var prevLastWriteTime = FileUtilities.GetFileTimeStamp(Path); TextAndVersion textAndVersion; // Open file for reading with FileShare mode read/write/delete so that we do not lock this file. using (var stream = FileUtilities.RethrowExceptionsAsIOException(() => new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 4096, useAsync: false))) { var version = VersionStamp.Create(prevLastWriteTime); var text = CreateText(stream, workspace); textAndVersion = TextAndVersion.Create(text, version, Path); } // Check if the file was definitely modified and closed while we were reading. In this case, we know the read we got was // probably invalid, so throw an IOException which indicates to our caller that we should automatically attempt a re-read. // If the file hasn't been closed yet and there's another writer, we will rely on file change notifications to notify us // and reload the file. var newLastWriteTime = FileUtilities.GetFileTimeStamp(Path); if (!newLastWriteTime.Equals(prevLastWriteTime)) { var message = string.Format(WorkspacesResources.File_was_externally_modified_colon_0, Path); throw new IOException(message); } return textAndVersion; } private string GetDebuggerDisplay() => nameof(Path) + " = " + Path; private static void ValidateFileLength(Workspace workspace, string path) { // Validate file length is under our threshold. // Otherwise, rather than reading the content into the memory, we will throw // InvalidDataException to caller of FileTextLoader.LoadText to deal with // the situation. // // check this (http://source.roslyn.io/#Microsoft.CodeAnalysis.Workspaces/Workspace/Solution/TextDocumentState.cs,132) // to see how workspace deal with exception from FileTextLoader. other consumer can handle the exception differently var fileLength = FileUtilities.GetFileLength(path); var threshold = workspace.Options.GetOption(FileTextLoaderOptions.FileLengthThreshold); if (fileLength > threshold) { // log max file length which will log to VS telemetry in VS host Logger.Log(FunctionId.FileTextLoader_FileLengthThresholdExceeded, KeyValueLogMessage.Create(m => { m["FileLength"] = fileLength; m["Ext"] = PathUtilities.GetExtension(path); })); var message = string.Format(WorkspacesResources.File_0_size_of_1_exceeds_maximum_allowed_size_of_2, path, fileLength, threshold); throw new InvalidDataException(message); } } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Compilers/Test/Resources/Core/NetFX/aacorlib/Key.snk
$RSA2+ok^q}5-8VA>&p)冀3es2[:gX:6̴ޏWOcM&顡 onSb'2.5}2m fW3b!Z["Aofj-k ckһmj&}es!U+qM,CS.$sF*Ee-WuEWe社M42޴溯.$e; u6푾f̰I h= <40Y$x|@9jJzה`}Z =5l7C2F#B5٥3ۏxctMu P/Q1^e6 0%6$$65VgL`򡜧X@|Rt2!zLNhGca !ge&R΂TSs(~p)D׿uaȿXOF<+6U 5 '[cW=E/ \QSUf^掓.p@9<1?c#C{5eTf% iWSgBJC)\ {z
$RSA2+ok^q}5-8VA>&p)冀3es2[:gX:6̴ޏWOcM&顡 onSb'2.5}2m fW3b!Z["Aofj-k ckһmj&}es!U+qM,CS.$sF*Ee-WuEWe社M42޴溯.$e; u6푾f̰I h= <40Y$x|@9jJzה`}Z =5l7C2F#B5٥3ۏxctMu P/Q1^e6 0%6$$65VgL`򡜧X@|Rt2!zLNhGca !ge&R΂TSs(~p)D׿uaȿXOF<+6U 5 '[cW=E/ \QSUf^掓.p@9<1?c#C{5eTf% iWSgBJC)\ {z
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./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.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, position As Integer, snippetNode As XElement, placeSystemNamespaceFirst As Boolean, 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.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, position As Integer, snippetNode As XElement, placeSystemNamespaceFirst As Boolean, allowInHiddenRegions As Boolean, cancellationToken As CancellationToken) As Document Return document End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Compilers/Core/Portable/Symbols/Attributes/CommonEventEarlyWellKnownAttributeData.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.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from early well-known custom attributes applied on an event. /// </summary> internal class CommonEventEarlyWellKnownAttributeData : EarlyWellKnownAttributeData { #region ObsoleteAttribute private ObsoleteAttributeData _obsoleteAttributeData = ObsoleteAttributeData.Uninitialized; public ObsoleteAttributeData ObsoleteAttributeData { get { VerifySealed(expected: true); return _obsoleteAttributeData.IsUninitialized ? null : _obsoleteAttributeData; } set { VerifySealed(expected: false); Debug.Assert(value != null); Debug.Assert(!value.IsUninitialized); _obsoleteAttributeData = value; SetDataStored(); } } #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.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from early well-known custom attributes applied on an event. /// </summary> internal class CommonEventEarlyWellKnownAttributeData : EarlyWellKnownAttributeData { #region ObsoleteAttribute private ObsoleteAttributeData _obsoleteAttributeData = ObsoleteAttributeData.Uninitialized; public ObsoleteAttributeData ObsoleteAttributeData { get { VerifySealed(expected: true); return _obsoleteAttributeData.IsUninitialized ? null : _obsoleteAttributeData; } set { VerifySealed(expected: false); Debug.Assert(value != null); Debug.Assert(!value.IsUninitialized); _obsoleteAttributeData = value; SetDataStored(); } } #endregion } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Compilers/CSharp/Portable/Emitter/Model/ParameterTypeInformation.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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class ParameterTypeInformation : Cci.IParameterTypeInformation { private readonly ParameterSymbol _underlyingParameter; public ParameterTypeInformation(ParameterSymbol underlyingParameter) { Debug.Assert((object)underlyingParameter != null); _underlyingParameter = underlyingParameter; } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.CustomModifiers { get { return ImmutableArray<Cci.ICustomModifier>.CastUp(_underlyingParameter.TypeWithAnnotations.CustomModifiers); } } bool Cci.IParameterTypeInformation.IsByReference { get { return _underlyingParameter.RefKind != RefKind.None; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.RefCustomModifiers { get { return ImmutableArray<Cci.ICustomModifier>.CastUp(_underlyingParameter.RefCustomModifiers); } } Cci.ITypeReference Cci.IParameterTypeInformation.GetType(EmitContext context) { return ((PEModuleBuilder)context.Module).Translate(_underlyingParameter.Type, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode, diagnostics: context.Diagnostics); } ushort Cci.IParameterListEntry.Index { get { return (ushort)_underlyingParameter.Ordinal; } } public override string ToString() { return _underlyingParameter.ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } internal sealed class ArgListParameterTypeInformation : Cci.IParameterTypeInformation { private readonly ushort _ordinal; private readonly bool _isByRef; private readonly Cci.ITypeReference _type; public ArgListParameterTypeInformation(int ordinal, bool isByRef, Cci.ITypeReference type) { _ordinal = (ushort)ordinal; _isByRef = isByRef; _type = type; } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.CustomModifiers { get { return ImmutableArray<Cci.ICustomModifier>.Empty; } } bool Cci.IParameterTypeInformation.IsByReference { get { return _isByRef; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.RefCustomModifiers { get { return ImmutableArray<Cci.ICustomModifier>.Empty; } } Cci.ITypeReference Cci.IParameterTypeInformation.GetType(EmitContext context) { return _type; } ushort Cci.IParameterListEntry.Index { get { return _ordinal; } } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class ParameterTypeInformation : Cci.IParameterTypeInformation { private readonly ParameterSymbol _underlyingParameter; public ParameterTypeInformation(ParameterSymbol underlyingParameter) { Debug.Assert((object)underlyingParameter != null); _underlyingParameter = underlyingParameter; } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.CustomModifiers { get { return ImmutableArray<Cci.ICustomModifier>.CastUp(_underlyingParameter.TypeWithAnnotations.CustomModifiers); } } bool Cci.IParameterTypeInformation.IsByReference { get { return _underlyingParameter.RefKind != RefKind.None; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.RefCustomModifiers { get { return ImmutableArray<Cci.ICustomModifier>.CastUp(_underlyingParameter.RefCustomModifiers); } } Cci.ITypeReference Cci.IParameterTypeInformation.GetType(EmitContext context) { return ((PEModuleBuilder)context.Module).Translate(_underlyingParameter.Type, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode, diagnostics: context.Diagnostics); } ushort Cci.IParameterListEntry.Index { get { return (ushort)_underlyingParameter.Ordinal; } } public override string ToString() { return _underlyingParameter.ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } internal sealed class ArgListParameterTypeInformation : Cci.IParameterTypeInformation { private readonly ushort _ordinal; private readonly bool _isByRef; private readonly Cci.ITypeReference _type; public ArgListParameterTypeInformation(int ordinal, bool isByRef, Cci.ITypeReference type) { _ordinal = (ushort)ordinal; _isByRef = isByRef; _type = type; } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.CustomModifiers { get { return ImmutableArray<Cci.ICustomModifier>.Empty; } } bool Cci.IParameterTypeInformation.IsByReference { get { return _isByRef; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.RefCustomModifiers { get { return ImmutableArray<Cci.ICustomModifier>.Empty; } } Cci.ITypeReference Cci.IParameterTypeInformation.GetType(EmitContext context) { return _type; } ushort Cci.IParameterListEntry.Index { get { return _ordinal; } } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Compilers/VisualBasic/Test/Symbol/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,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/EditorFeatures/Test/CodeActions/CodeActionSmartTagProducerTests.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 #if false using System.Linq; using System.Threading; using Microsoft.VisualStudio.Language.Intellisense; using Roslyn.Services.Editor.Implementation.CodeActions; using Roslyn.Services.Editor.Shared.Extensions; using Roslyn.Services.Editor.Shared.TestHooks; using Roslyn.Services.Editor.UnitTests.Utilities; using Roslyn.Services.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.Services.Editor.UnitTests.CodeActions { public class CodeActionSmartTagProducerTests { [WpfFact] public void TestWalker() { var text = @"class C : System.Exception { //Goo void Bar() { Console.WriteLine(1 + 1); } }"; using (var workspace = TestWorkspace.CreateWorkspaceFromFile(text)) { var textBuffer = workspace.Documents.First().TextBuffer; var issueProducer = new CodeIssueTagProducer( TestWaitIndicator.Default, textBuffer, workspace.ExportProvider.GetExportedValue<CodeActionProviderManager>()); var snapshot = textBuffer.CurrentSnapshot; var tags1 = issueProducer.ProduceTagsAsync(snapshot.GetSpan(0, snapshot.Length), null, CancellationToken.None).PumpingWaitResult().ToList(); var tagCount1 = tags1.Count; Assert.True(tagCount1 > 0, tagCount1.ToString()); } } } } #endif
// Licensed to the .NET Foundation under one or more 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 #if false using System.Linq; using System.Threading; using Microsoft.VisualStudio.Language.Intellisense; using Roslyn.Services.Editor.Implementation.CodeActions; using Roslyn.Services.Editor.Shared.Extensions; using Roslyn.Services.Editor.Shared.TestHooks; using Roslyn.Services.Editor.UnitTests.Utilities; using Roslyn.Services.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.Services.Editor.UnitTests.CodeActions { public class CodeActionSmartTagProducerTests { [WpfFact] public void TestWalker() { var text = @"class C : System.Exception { //Goo void Bar() { Console.WriteLine(1 + 1); } }"; using (var workspace = TestWorkspace.CreateWorkspaceFromFile(text)) { var textBuffer = workspace.Documents.First().TextBuffer; var issueProducer = new CodeIssueTagProducer( TestWaitIndicator.Default, textBuffer, workspace.ExportProvider.GetExportedValue<CodeActionProviderManager>()); var snapshot = textBuffer.CurrentSnapshot; var tags1 = issueProducer.ProduceTagsAsync(snapshot.GetSpan(0, snapshot.Length), null, CancellationToken.None).PumpingWaitResult().ToList(); var tagCount1 = tags1.Count; Assert.True(tagCount1 > 0, tagCount1.ToString()); } } } } #endif
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/VisualStudio/Core/Def/Implementation/Venus/IVsContainedLanguageStaticEventBinding.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.CompilerServices; using System.Runtime.InteropServices; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { /// <summary> /// This interface is redefined by copy/paste from Reflector, so that we can tweak the /// definitions of GetStaticEventBindingsForObject, because they take optional out params, and /// the marshalling was wrong in the PIA. /// </summary> [ComImport, Guid("22FF7776-2C9A-48C4-809F-39E5184CC32D"), ComConversionLoss, InterfaceType((short)1)] internal interface IVsContainedLanguageStaticEventBinding { [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetStaticEventBindingsForObject( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectName, out int pcMembers, IntPtr ppbstrEventNames, IntPtr ppbstrDisplayNames, IntPtr ppbstrMemberIDs); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int RemoveStaticEventBinding( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszUniqueMemberID, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int AddStaticEventBinding( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszUniqueMemberID, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int EnsureStaticEventHandler( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectTypeName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszEventHandlerName, [In, ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")] uint itemidInsertionPoint, [MarshalAs(UnmanagedType.BStr)] out string pbstrUniqueMemberID, [MarshalAs(UnmanagedType.BStr)] out string pbstrEventBody, [Out, ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan"), MarshalAs(UnmanagedType.LPArray)] TextSpan[] pSpanInsertionPoint); } }
// Licensed to the .NET Foundation under one or more 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.CompilerServices; using System.Runtime.InteropServices; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { /// <summary> /// This interface is redefined by copy/paste from Reflector, so that we can tweak the /// definitions of GetStaticEventBindingsForObject, because they take optional out params, and /// the marshalling was wrong in the PIA. /// </summary> [ComImport, Guid("22FF7776-2C9A-48C4-809F-39E5184CC32D"), ComConversionLoss, InterfaceType((short)1)] internal interface IVsContainedLanguageStaticEventBinding { [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetStaticEventBindingsForObject( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectName, out int pcMembers, IntPtr ppbstrEventNames, IntPtr ppbstrDisplayNames, IntPtr ppbstrMemberIDs); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int RemoveStaticEventBinding( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszUniqueMemberID, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int AddStaticEventBinding( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszUniqueMemberID, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int EnsureStaticEventHandler( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectTypeName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszEventHandlerName, [In, ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")] uint itemidInsertionPoint, [MarshalAs(UnmanagedType.BStr)] out string pbstrUniqueMemberID, [MarshalAs(UnmanagedType.BStr)] out string pbstrEventBody, [Out, ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan"), MarshalAs(UnmanagedType.LPArray)] TextSpan[] pSpanInsertionPoint); } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeAction.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Packaging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddPackage { internal class InstallPackageDirectlyCodeAction : CodeAction { private readonly CodeActionOperation _installPackageOperation; public override string Title { get; } public InstallPackageDirectlyCodeAction( IPackageInstallerService installerService, Document document, string source, string packageName, string versionOpt, bool includePrerelease, bool isLocal) { Title = versionOpt == null ? FeaturesResources.Find_and_install_latest_version : isLocal ? string.Format(FeaturesResources.Use_local_version_0, versionOpt) : string.Format(FeaturesResources.Install_version_0, versionOpt); _installPackageOperation = new InstallPackageDirectlyCodeActionOperation( installerService, document, source, packageName, versionOpt, includePrerelease, isLocal); } protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken) => Task.FromResult(SpecializedCollections.SingletonEnumerable(_installPackageOperation)); } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Packaging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddPackage { internal class InstallPackageDirectlyCodeAction : CodeAction { private readonly CodeActionOperation _installPackageOperation; public override string Title { get; } public InstallPackageDirectlyCodeAction( IPackageInstallerService installerService, Document document, string source, string packageName, string versionOpt, bool includePrerelease, bool isLocal) { Title = versionOpt == null ? FeaturesResources.Find_and_install_latest_version : isLocal ? string.Format(FeaturesResources.Use_local_version_0, versionOpt) : string.Format(FeaturesResources.Install_version_0, versionOpt); _installPackageOperation = new InstallPackageDirectlyCodeActionOperation( installerService, document, source, packageName, versionOpt, includePrerelease, isLocal); } protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken) => Task.FromResult(SpecializedCollections.SingletonEnumerable(_installPackageOperation)); } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/VisualStudio/Core/Def/EditorConfigSettings/Common/IEnumSettingViewModelFactory.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.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common { internal interface IEnumSettingViewModelFactory { bool IsSupported(OptionKey2 key); IEnumSettingViewModel CreateViewModel(FormattingSetting setting); } }
// Licensed to the .NET Foundation under one or more 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.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common { internal interface IEnumSettingViewModelFactory { bool IsSupported(OptionKey2 key); IEnumSettingViewModel CreateViewModel(FormattingSetting setting); } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Features/CSharp/Portable/Wrapping/SeparatedSyntaxList/CSharpParameterWrapper.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.Linq; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Wrapping.SeparatedSyntaxList { internal partial class CSharpParameterWrapper : AbstractCSharpSeparatedSyntaxListWrapper<BaseParameterListSyntax, ParameterSyntax> { protected override string Align_wrapped_items => FeaturesResources.Align_wrapped_parameters; protected override string Indent_all_items => FeaturesResources.Indent_all_parameters; protected override string Indent_wrapped_items => FeaturesResources.Indent_wrapped_parameters; protected override string Unwrap_all_items => FeaturesResources.Unwrap_all_parameters; protected override string Unwrap_and_indent_all_items => FeaturesResources.Unwrap_and_indent_all_parameters; protected override string Unwrap_list => FeaturesResources.Unwrap_parameter_list; protected override string Wrap_every_item => FeaturesResources.Wrap_every_parameter; protected override string Wrap_long_list => FeaturesResources.Wrap_long_parameter_list; protected override SeparatedSyntaxList<ParameterSyntax> GetListItems(BaseParameterListSyntax listSyntax) => listSyntax.Parameters; protected override BaseParameterListSyntax? TryGetApplicableList(SyntaxNode node) => node.GetParameterList(); protected override bool PositionIsApplicable( SyntaxNode root, int position, SyntaxNode declaration, BaseParameterListSyntax listSyntax) { // CSharpSyntaxGenerator.GetParameterList synthesizes a parameter list for simple-lambdas. // In that case, we're not applicable in that list. if (declaration.Kind() == SyntaxKind.SimpleLambdaExpression) { return false; } var generator = CSharpSyntaxGenerator.Instance; var attributes = generator.GetAttributes(declaration); // We want to offer this feature in the header of the member. For now, we consider // the header to be the part after the attributes, to the end of the parameter list. var firstToken = attributes?.Count > 0 ? attributes.Last().GetLastToken().GetNextToken() : declaration.GetFirstToken(); var lastToken = listSyntax.GetLastToken(); var headerSpan = TextSpan.FromBounds(firstToken.SpanStart, lastToken.Span.End); return headerSpan.IntersectsWith(position); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Wrapping.SeparatedSyntaxList { internal partial class CSharpParameterWrapper : AbstractCSharpSeparatedSyntaxListWrapper<BaseParameterListSyntax, ParameterSyntax> { protected override string Align_wrapped_items => FeaturesResources.Align_wrapped_parameters; protected override string Indent_all_items => FeaturesResources.Indent_all_parameters; protected override string Indent_wrapped_items => FeaturesResources.Indent_wrapped_parameters; protected override string Unwrap_all_items => FeaturesResources.Unwrap_all_parameters; protected override string Unwrap_and_indent_all_items => FeaturesResources.Unwrap_and_indent_all_parameters; protected override string Unwrap_list => FeaturesResources.Unwrap_parameter_list; protected override string Wrap_every_item => FeaturesResources.Wrap_every_parameter; protected override string Wrap_long_list => FeaturesResources.Wrap_long_parameter_list; protected override SeparatedSyntaxList<ParameterSyntax> GetListItems(BaseParameterListSyntax listSyntax) => listSyntax.Parameters; protected override BaseParameterListSyntax? TryGetApplicableList(SyntaxNode node) => node.GetParameterList(); protected override bool PositionIsApplicable( SyntaxNode root, int position, SyntaxNode declaration, BaseParameterListSyntax listSyntax) { // CSharpSyntaxGenerator.GetParameterList synthesizes a parameter list for simple-lambdas. // In that case, we're not applicable in that list. if (declaration.Kind() == SyntaxKind.SimpleLambdaExpression) { return false; } var generator = CSharpSyntaxGenerator.Instance; var attributes = generator.GetAttributes(declaration); // We want to offer this feature in the header of the member. For now, we consider // the header to be the part after the attributes, to the end of the parameter list. var firstToken = attributes?.Count > 0 ? attributes.Last().GetLastToken().GetNextToken() : declaration.GetFirstToken(); var lastToken = listSyntax.GetLastToken(); var headerSpan = TextSpan.FromBounds(firstToken.SpanStart, lastToken.Span.End); return headerSpan.IntersectsWith(position); } } }
-1
dotnet/roslyn
55,032
Fix a couple of bugs in SG
- Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
chsienki
2021-07-21T23:39:32Z
2021-07-26T22:37:15Z
720c1c1838a3178f95c69618bd1fbf87130b58e9
25f922c63141d89f5805bea6df8f7a4cd7a13dc7
Fix a couple of bugs in SG. - Ensure that `.Collect()` reports as cached if all the inputs are cached - Don't use user comparer for matching inputs Fixes https://github.com/dotnet/roslyn/issues/54855
./src/Workspaces/Core/Portable/Rename/RenameOptions.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.Options; namespace Microsoft.CodeAnalysis.Rename { public static class RenameOptions { public static Option<bool> RenameOverloads { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameOverloads), defaultValue: false); public static Option<bool> RenameInStrings { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameInStrings), defaultValue: false); public static Option<bool> RenameInComments { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameInComments), defaultValue: false); /// <summary> /// Set to true if the file name should match the type name after a rename operation /// </summary> internal static Option<bool> RenameFile { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameFile), defaultValue: false); public static Option<bool> PreviewChanges { get; } = new Option<bool>(nameof(RenameOptions), nameof(PreviewChanges), defaultValue: false); } internal struct RenameOptionSet { public readonly bool RenameOverloads; public readonly bool RenameInStrings; public readonly bool RenameInComments; public readonly bool RenameFile; public RenameOptionSet(bool renameOverloads, bool renameInStrings, bool renameInComments, bool renameFile) { RenameOverloads = renameOverloads; RenameInStrings = renameInStrings; RenameInComments = renameInComments; RenameFile = renameFile; } internal static RenameOptionSet From(Solution solution) => From(solution, options: null); internal static RenameOptionSet From(Solution solution, OptionSet options) { options ??= solution.Options; return new RenameOptionSet( options.GetOption(RenameOptions.RenameOverloads), options.GetOption(RenameOptions.RenameInStrings), options.GetOption(RenameOptions.RenameInComments), options.GetOption(RenameOptions.RenameFile)); } } }
// Licensed to the .NET Foundation under one or more 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.Options; namespace Microsoft.CodeAnalysis.Rename { public static class RenameOptions { public static Option<bool> RenameOverloads { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameOverloads), defaultValue: false); public static Option<bool> RenameInStrings { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameInStrings), defaultValue: false); public static Option<bool> RenameInComments { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameInComments), defaultValue: false); /// <summary> /// Set to true if the file name should match the type name after a rename operation /// </summary> internal static Option<bool> RenameFile { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameFile), defaultValue: false); public static Option<bool> PreviewChanges { get; } = new Option<bool>(nameof(RenameOptions), nameof(PreviewChanges), defaultValue: false); } internal struct RenameOptionSet { public readonly bool RenameOverloads; public readonly bool RenameInStrings; public readonly bool RenameInComments; public readonly bool RenameFile; public RenameOptionSet(bool renameOverloads, bool renameInStrings, bool renameInComments, bool renameFile) { RenameOverloads = renameOverloads; RenameInStrings = renameInStrings; RenameInComments = renameInComments; RenameFile = renameFile; } internal static RenameOptionSet From(Solution solution) => From(solution, options: null); internal static RenameOptionSet From(Solution solution, OptionSet options) { options ??= solution.Options; return new RenameOptionSet( options.GetOption(RenameOptions.RenameOverloads), options.GetOption(RenameOptions.RenameInStrings), options.GetOption(RenameOptions.RenameInComments), options.GetOption(RenameOptions.RenameFile)); } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/InheritanceMargin.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. using System.Collections.Immutable; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.GoToDefinition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal partial class InheritanceMargin { private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; private readonly IUIThreadOperationExecutor _operationExecutor; private readonly Workspace _workspace; private readonly IWpfTextView _textView; public InheritanceMargin( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingFindUsagesPresenter, ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, IUIThreadOperationExecutor operationExecutor, InheritanceMarginTag tag, IWpfTextView textView) { _threadingContext = threadingContext; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; _workspace = tag.Workspace; _operationExecutor = operationExecutor; _textView = textView; InitializeComponent(); // ZoomLevel of textView is percentage based. (e.g. 20 -> 400 means 20% -> 400%) // and the scaleFactor of CrispImage is 1 based. (e.g 1 means 100%) var scaleFactor = textView.ZoomLevel; var viewModel = InheritanceMarginViewModel.Create(classificationTypeMap, classificationFormatMap, tag, scaleFactor); DataContext = viewModel; ContextMenu.DataContext = viewModel; ToolTip = new ToolTip { Content = viewModel.ToolTipTextBlock, Style = (Style)FindResource("ToolTipStyle") }; } private void InheritanceMargin_OnClick(object sender, RoutedEventArgs e) { if (this.ContextMenu != null) { this.ContextMenu.IsOpen = true; e.Handled = true; } } private void TargetMenuItem_OnClick(object sender, RoutedEventArgs e) { if (e.OriginalSource is MenuItem { DataContext: TargetMenuItemViewModel viewModel }) { Logger.Log(FunctionId.InheritanceMargin_NavigateToTarget, KeyValueLogMessage.Create(LogType.UserAction)); _operationExecutor.Execute( new UIThreadOperationExecutionOptions( title: EditorFeaturesResources.Navigating, defaultDescription: string.Format(ServicesVSResources.Navigate_to_0, viewModel.DisplayContent), allowCancellation: true, showProgress: false), context => GoToDefinitionHelpers.TryGoToDefinition( ImmutableArray.Create(viewModel.DefinitionItem), _workspace, string.Format(EditorFeaturesResources._0_declarations, viewModel.DisplayContent), _threadingContext, _streamingFindUsagesPresenter, context.UserCancellationToken)); } } private void ChangeBorderToHoveringColor() { SetResourceReference(BackgroundProperty, VsBrushes.CommandBarMenuBackgroundGradientKey); SetResourceReference(BorderBrushProperty, VsBrushes.CommandBarMenuBorderKey); } private void InheritanceMargin_OnMouseEnter(object sender, MouseEventArgs e) { ChangeBorderToHoveringColor(); } private void InheritanceMargin_OnMouseLeave(object sender, MouseEventArgs e) { // If the context menu is open, then don't reset the color of the button because we need // the margin looks like being pressed. if (!ContextMenu.IsOpen) { ResetBorderToInitialColor(); } } private void ContextMenu_OnClose(object sender, RoutedEventArgs e) { ResetBorderToInitialColor(); // Move the focus back to textView when the context menu is closed. // It ensures the focus won't be left at the margin ResetFocus(); } private void ContextMenu_OnOpen(object sender, RoutedEventArgs e) { if (e.OriginalSource is ContextMenu { DataContext: InheritanceMarginViewModel inheritanceMarginViewModel } && inheritanceMarginViewModel.MenuItemViewModels.Any(vm => vm is TargetMenuItemViewModel)) { // We have two kinds of context menu. e.g. // 1. [margin] -> Header // Target1 // Target2 // Target3 // // 2. [margin] -> method Bar -> Header // -> Target1 // -> Target2 // -> method Foo -> Header // -> Target3 // -> Target4 // If the first level of the context menu contains a TargetMenuItemViewModel, it means here it is case 1, // user is viewing the targets menu. Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } } private void TargetsSubmenu_OnOpen(object sender, RoutedEventArgs e) { Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } private void ResetBorderToInitialColor() { this.Background = Brushes.Transparent; this.BorderBrush = Brushes.Transparent; } private void ResetFocus() { if (!_textView.HasAggregateFocus) { var visualElement = _textView.VisualElement; if (visualElement.Focusable) { Keyboard.Focus(visualElement); } } } } }
// Licensed to the .NET Foundation under one or more 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.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.GoToDefinition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal partial class InheritanceMargin { private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; private readonly IUIThreadOperationExecutor _operationExecutor; private readonly Workspace _workspace; private readonly IWpfTextView _textView; public InheritanceMargin( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingFindUsagesPresenter, ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, IUIThreadOperationExecutor operationExecutor, InheritanceMarginTag tag, IWpfTextView textView) { _threadingContext = threadingContext; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; _workspace = tag.Workspace; _operationExecutor = operationExecutor; _textView = textView; InitializeComponent(); var viewModel = InheritanceMarginViewModel.Create(classificationTypeMap, classificationFormatMap, tag, textView.ZoomLevel); DataContext = viewModel; ContextMenu.DataContext = viewModel; ToolTip = new ToolTip { Content = viewModel.ToolTipTextBlock, Style = (Style)FindResource("ToolTipStyle") }; } private void InheritanceMargin_OnClick(object sender, RoutedEventArgs e) { if (this.ContextMenu != null) { this.ContextMenu.IsOpen = true; e.Handled = true; } } private void TargetMenuItem_OnClick(object sender, RoutedEventArgs e) { if (e.OriginalSource is MenuItem { DataContext: TargetMenuItemViewModel viewModel }) { Logger.Log(FunctionId.InheritanceMargin_NavigateToTarget, KeyValueLogMessage.Create(LogType.UserAction)); _operationExecutor.Execute( new UIThreadOperationExecutionOptions( title: EditorFeaturesResources.Navigating, defaultDescription: string.Format(ServicesVSResources.Navigate_to_0, viewModel.DisplayContent), allowCancellation: true, showProgress: false), context => GoToDefinitionHelpers.TryGoToDefinition( ImmutableArray.Create(viewModel.DefinitionItem), _workspace, string.Format(EditorFeaturesResources._0_declarations, viewModel.DisplayContent), _threadingContext, _streamingFindUsagesPresenter, context.UserCancellationToken)); } } private void ChangeBorderToHoveringColor() { SetResourceReference(BackgroundProperty, VsBrushes.CommandBarMenuBackgroundGradientKey); SetResourceReference(BorderBrushProperty, VsBrushes.CommandBarMenuBorderKey); } private void InheritanceMargin_OnMouseEnter(object sender, MouseEventArgs e) { ChangeBorderToHoveringColor(); } private void InheritanceMargin_OnMouseLeave(object sender, MouseEventArgs e) { // If the context menu is open, then don't reset the color of the button because we need // the margin looks like being pressed. if (!ContextMenu.IsOpen) { ResetBorderToInitialColor(); } } private void ContextMenu_OnClose(object sender, RoutedEventArgs e) { ResetBorderToInitialColor(); // Move the focus back to textView when the context menu is closed. // It ensures the focus won't be left at the margin ResetFocus(); } private void ContextMenu_OnOpen(object sender, RoutedEventArgs e) { if (e.OriginalSource is ContextMenu { DataContext: InheritanceMarginViewModel inheritanceMarginViewModel } && inheritanceMarginViewModel.MenuItemViewModels.Any(vm => vm is TargetMenuItemViewModel)) { // We have two kinds of context menu. e.g. // 1. [margin] -> Header // Target1 // Target2 // Target3 // // 2. [margin] -> method Bar -> Header // -> Target1 // -> Target2 // -> method Foo -> Header // -> Target3 // -> Target4 // If the first level of the context menu contains a TargetMenuItemViewModel, it means here it is case 1, // user is viewing the targets menu. Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } } private void TargetsSubmenu_OnOpen(object sender, RoutedEventArgs e) { Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } private void ResetBorderToInitialColor() { this.Background = Brushes.Transparent; this.BorderBrush = Brushes.Transparent; } private void ResetFocus() { if (!_textView.HasAggregateFocus) { var visualElement = _textView.VisualElement; if (visualElement.Focusable) { Keyboard.Focus(visualElement); } } } } }
1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/InheritanceMarginViewModel.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.Windows; using System.Windows.Controls; using System.Windows.Documents; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal class InheritanceMarginViewModel { /// <summary> /// ImageMoniker used for the margin. /// </summary> public ImageMoniker ImageMoniker { get; } /// <summary> /// Tooltip for the margin. /// </summary> public TextBlock ToolTipTextBlock { get; } /// <summary> /// Text used for automation. /// </summary> public string AutomationName { get; } /// <summary> /// ViewModels for the context menu items. /// </summary> public ImmutableArray<InheritanceMenuItemViewModel> MenuItemViewModels { get; } /// <summary> /// Scale factor for the margin. /// </summary> public double ScaleFactor { get; } // Internal for testing purpose internal InheritanceMarginViewModel( ImageMoniker imageMoniker, TextBlock toolTipTextBlock, string automationName, double scaleFactor, ImmutableArray<InheritanceMenuItemViewModel> menuItemViewModels) { ImageMoniker = imageMoniker; ToolTipTextBlock = toolTipTextBlock; AutomationName = automationName; MenuItemViewModels = menuItemViewModels; ScaleFactor = scaleFactor; } public static InheritanceMarginViewModel Create( ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, InheritanceMarginTag tag, double scaleFactor) { var members = tag.MembersOnLine; if (members.Length == 1) { var member = tag.MembersOnLine[0]; // Here we want to show a classified text with loc text, // e.g. 'Bar' is inherited. // But the classified text are inlines, so can't directly use string.format to generate the string var inlines = member.DisplayTexts.ToInlines(classificationFormatMap, classificationTypeMap); var startOfThePlaceholder = ServicesVSResources._0_is_inherited.IndexOf("{0}", StringComparison.Ordinal); var prefixString = ServicesVSResources._0_is_inherited[..startOfThePlaceholder]; var suffixString = ServicesVSResources._0_is_inherited[(startOfThePlaceholder + "{0}".Length)..]; inlines.Insert(0, new Run(prefixString)); inlines.Add(new Run(suffixString)); var toolTipTextBlock = inlines.ToTextBlock(classificationFormatMap); toolTipTextBlock.FlowDirection = FlowDirection.LeftToRight; var automationName = string.Format(ServicesVSResources._0_is_inherited, member.DisplayTexts.JoinText()); var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForSingleMember(member.TargetItems); return new InheritanceMarginViewModel(tag.Moniker, toolTipTextBlock, automationName, scaleFactor, menuItemViewModels); } else { var textBlock = new TextBlock { Text = ServicesVSResources.Multiple_members_are_inherited }; // Same automation name can't be set for control for accessibility purpose. So add the line number info. var automationName = string.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, tag.LineNumber); var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForMultipleMembers(tag.MembersOnLine); return new InheritanceMarginViewModel(tag.Moniker, textBlock, automationName, scaleFactor, menuItemViewModels); } } } }
// Licensed to the .NET Foundation under one or more 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.Windows; using System.Windows.Controls; using System.Windows.Documents; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal class InheritanceMarginViewModel { /// <summary> /// ImageMoniker used for the margin. /// </summary> public ImageMoniker ImageMoniker { get; } /// <summary> /// Tooltip for the margin. /// </summary> public TextBlock ToolTipTextBlock { get; } /// <summary> /// Text used for automation. /// </summary> public string AutomationName { get; } /// <summary> /// ViewModels for the context menu items. /// </summary> public ImmutableArray<InheritanceMenuItemViewModel> MenuItemViewModels { get; } /// <summary> /// Scale factor for the margin. /// </summary> public double ScaleFactor { get; } // Internal for testing purpose internal InheritanceMarginViewModel( ImageMoniker imageMoniker, TextBlock toolTipTextBlock, string automationName, double scaleFactor, ImmutableArray<InheritanceMenuItemViewModel> menuItemViewModels) { ImageMoniker = imageMoniker; ToolTipTextBlock = toolTipTextBlock; AutomationName = automationName; MenuItemViewModels = menuItemViewModels; ScaleFactor = scaleFactor; } public static InheritanceMarginViewModel Create( ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, InheritanceMarginTag tag, double zoomLevel) { var members = tag.MembersOnLine; // ZoomLevel is 100 based. (e.g. 150%, 100%) // ScaleFactor is 1 based. (e.g. 1.5, 1) var scaleFactor = zoomLevel / 100; if (members.Length == 1) { var member = tag.MembersOnLine[0]; // Here we want to show a classified text with loc text, // e.g. 'Bar' is inherited. // But the classified text are inlines, so can't directly use string.format to generate the string var inlines = member.DisplayTexts.ToInlines(classificationFormatMap, classificationTypeMap); var startOfThePlaceholder = ServicesVSResources._0_is_inherited.IndexOf("{0}", StringComparison.Ordinal); var prefixString = ServicesVSResources._0_is_inherited[..startOfThePlaceholder]; var suffixString = ServicesVSResources._0_is_inherited[(startOfThePlaceholder + "{0}".Length)..]; inlines.Insert(0, new Run(prefixString)); inlines.Add(new Run(suffixString)); var toolTipTextBlock = inlines.ToTextBlock(classificationFormatMap); toolTipTextBlock.FlowDirection = FlowDirection.LeftToRight; var automationName = string.Format(ServicesVSResources._0_is_inherited, member.DisplayTexts.JoinText()); var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForSingleMember(member.TargetItems); return new InheritanceMarginViewModel(tag.Moniker, toolTipTextBlock, automationName, scaleFactor, menuItemViewModels); } else { var textBlock = new TextBlock { Text = ServicesVSResources.Multiple_members_are_inherited }; // Same automation name can't be set for control for accessibility purpose. So add the line number info. var automationName = string.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, tag.LineNumber); var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForMultipleMembers(tag.MembersOnLine); return new InheritanceMarginViewModel(tag.Moniker, textBlock, automationName, scaleFactor, menuItemViewModels); } } } }
1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Test/InheritanceMargin/InheritanceMarginViewModelTests.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.Text Imports System.Threading Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Documents Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.InheritanceMargin Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Imaging Imports Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin Imports Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph Imports Microsoft.VisualStudio.Text.Classification Imports Microsoft.VisualStudio.Threading Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.InheritanceMargin <Trait(Traits.Feature, Traits.Features.InheritanceMargin)> <UseExportProvider> Public Class InheritanceMarginViewModelTests Private Shared s_defaultMargin As Thickness = New Thickness(4, 1, 4, 1) Private Shared s_indentMargin As Thickness = New Thickness(22, 1, 4, 1) Private Shared Async Function VerifyAsync(markup As String, languageName As String, expectedViewModels As Dictionary(Of Integer, InheritanceMarginViewModel)) As Task ' Add an lf before the document so that the line number starts ' with 1, which meets the line number in the editor (but in fact all things start from 0) Dim workspaceFile = <Workspace> <Project Language=<%= languageName %> CommonReferences="true"> <Document><%= vbLf %> <%= markup.Replace(vbCrLf, vbLf) %> </Document> </Project> </Workspace> Dim cancellationToken As CancellationToken = CancellationToken.None Using workspace = TestWorkspace.Create(workspaceFile) Dim testDocument = workspace.Documents.Single() Dim document = workspace.CurrentSolution.GetDocument(testDocument.Id) Dim service = document.GetRequiredLanguageService(Of IInheritanceMarginService) Dim classificationTypeMap = workspace.ExportProvider.GetExportedValue(Of ClassificationTypeMap) Dim classificationFormatMap = workspace.ExportProvider.GetExportedValue(Of IClassificationFormatMapService) ' For these tests, we need to be on UI thread, so don't call ConfigureAwait(False) Dim root = Await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(True) Dim inheritanceItems = Await service.GetInheritanceMemberItemsAsync(document, root.FullSpan, cancellationToken).ConfigureAwait(True) Dim acutalLineToTagDictionary = inheritanceItems.GroupBy(Function(item) item.LineNumber) _ .ToDictionary(Function(grouping) grouping.Key, Function(grouping) Dim lineNumber = grouping.Key Dim items = grouping.Select(Function(g) g).ToImmutableArray() Return New InheritanceMarginTag(workspace, lineNumber, items) End Function) Assert.Equal(expectedViewModels.Count, acutalLineToTagDictionary.Count) For Each kvp In expectedViewModels Dim lineNumber = kvp.Key Dim expectedViewModel = kvp.Value Assert.True(acutalLineToTagDictionary.ContainsKey(lineNumber)) Dim acutalTag = acutalLineToTagDictionary(lineNumber) Dim actualViewModel = InheritanceMarginViewModel.Create( classificationTypeMap, classificationFormatMap.GetClassificationFormatMap("tooltip"), acutalTag, 1) VerifyTwoViewModelAreSame(expectedViewModel, actualViewModel) Next End Using End Function Private Shared Sub VerifyTwoViewModelAreSame(expected As InheritanceMarginViewModel, acutal As InheritanceMarginViewModel) Assert.Equal(expected.ImageMoniker, acutal.ImageMoniker) Dim actualTextGetFromTextBlock = acutal.ToolTipTextBlock.Inlines _ .OfType(Of Run).Select(Function(run) run.Text) _ .Aggregate(Function(text1, text2) text1 + text2) ' When the text block is created, a unicode 'left to right' would be inserted between the space. ' Make sure it is removed. Dim leftToRightMarker = Char.ConvertFromUtf32(&H200E) Dim actualText = actualTextGetFromTextBlock.Replace(leftToRightMarker, String.Empty) Assert.Equal(expected.ToolTipTextBlock.Text, actualText) Assert.Equal(expected.AutomationName, acutal.AutomationName) Assert.Equal(expected.MenuItemViewModels.Length, acutal.MenuItemViewModels.Length) For i = 0 To expected.MenuItemViewModels.Length - 1 Dim expectedMenuItem = expected.MenuItemViewModels(i) Dim actualMenuItem = acutal.MenuItemViewModels(i) VerifyMenuItem(expectedMenuItem, actualMenuItem) Next End Sub Private Shared Sub VerifyMenuItem(expected As InheritanceMenuItemViewModel, actual As InheritanceMenuItemViewModel) Assert.Equal(expected.AutomationName, actual.AutomationName) Assert.Equal(expected.DisplayContent, actual.DisplayContent) Assert.Equal(expected.ImageMoniker, actual.ImageMoniker) Dim expectedTargetMenuItem = TryCast(expected, TargetMenuItemViewModel) Dim acutalTargetMenuItem = TryCast(actual, TargetMenuItemViewModel) If expectedTargetMenuItem IsNot Nothing AndAlso acutalTargetMenuItem IsNot Nothing Then Return End If Dim expectedMemberMenuItem = TryCast(expected, MemberMenuItemViewModel) Dim acutalMemberMenuItem = TryCast(actual, MemberMenuItemViewModel) If expectedMemberMenuItem IsNot Nothing AndAlso acutalMemberMenuItem IsNot Nothing Then Assert.Equal(expectedMemberMenuItem.Targets.Length, acutalMemberMenuItem.Targets.Length) For i = 0 To expectedMemberMenuItem.Targets.Length - 1 VerifyMenuItem(expectedMemberMenuItem.Targets(i), acutalMemberMenuItem.Targets(i)) Next Return End If ' At this stage, both of the items should be header Assert.True(TypeOf expected Is HeaderMenuItemViewModel) Assert.True(TypeOf actual Is HeaderMenuItemViewModel) End Sub Private Shared Function CreateTextBlock(text As String) As TextBlock Return New TextBlock With { .Text = text } End Function <WpfFact> Public Function TestClassImplementsInterfaceRelationship() As Task Dim markup = " public interface IBar { } public class Bar : IBar { }" Dim tooltipTextForIBar = String.Format(ServicesVSResources._0_is_inherited, "interface IBar") Dim targetForIBar = ImmutableArray.Create(Of InheritanceMenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types)). Add(New TargetMenuItemViewModel("Bar", KnownMonikers.ClassPublic, "Bar", Nothing)) Dim tooltipTextForBar = String.Format(ServicesVSResources._0_is_inherited, "class Bar") Dim targetForBar = ImmutableArray.Create(Of InheritanceMenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Implemented_interfaces, KnownMonikers.Implementing, ServicesVSResources.Implemented_interfaces)). Add(New TargetMenuItemViewModel("IBar", KnownMonikers.InterfacePublic, "IBar", Nothing)) Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginViewModel) From { {2, New InheritanceMarginViewModel( KnownMonikers.Implemented, CreateTextBlock(tooltipTextForIBar), tooltipTextForIBar, 1, targetForIBar)}, {5, New InheritanceMarginViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForBar), tooltipTextForBar, 1, targetForBar)}}) End Function <WpfFact> Public Function TestClassOverridesAbstractClassRelationship() As Task Dim markup = " public abstract class AbsBar { public abstract void Foo(); } public class Bar : AbsBar { public override void Foo(); }" Dim tooltipTextForAbsBar = String.Format(ServicesVSResources._0_is_inherited, "class AbsBar") Dim targetForAbsBar = ImmutableArray.Create(Of InheritanceMenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Derived_types, KnownMonikers.Overridden, ServicesVSResources.Derived_types)). Add(New TargetMenuItemViewModel("Bar", KnownMonikers.ClassPublic, "Bar", Nothing)) Dim tooltipTextForAbstractFoo = String.Format(ServicesVSResources._0_is_inherited, "abstract void AbsBar.Foo()") Dim targetForAbsFoo = ImmutableArray.Create(Of InheritanceMenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Overriding_members, KnownMonikers.Overridden, ServicesVSResources.Overriding_members)). Add(New TargetMenuItemViewModel("Bar.Foo", KnownMonikers.MethodPublic, "Bar.Foo", Nothing)) Dim tooltipTextForBar = String.Format(ServicesVSResources._0_is_inherited, "class Bar") Dim targetForBar = ImmutableArray.Create(Of InheritanceMenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Base_Types, KnownMonikers.Overriding, ServicesVSResources.Base_Types)). Add(New TargetMenuItemViewModel("AbsBar", KnownMonikers.ClassPublic, "AbsBar", Nothing)) Dim tooltipTextForOverrideFoo = String.Format(ServicesVSResources._0_is_inherited, "override void Bar.Foo()") Dim targetForOverrideFoo = ImmutableArray.Create(Of InheritanceMenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Overridden_members, KnownMonikers.Overriding, ServicesVSResources.Overridden_members)). Add(New TargetMenuItemViewModel("AbsBar.Foo", KnownMonikers.MethodPublic, "AbsBar.Foo", Nothing)) Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginViewModel) From { {2, New InheritanceMarginViewModel( KnownMonikers.Overridden, CreateTextBlock(tooltipTextForAbsBar), tooltipTextForAbsBar, 1, targetForAbsBar)}, {4, New InheritanceMarginViewModel( KnownMonikers.Overridden, CreateTextBlock(tooltipTextForAbstractFoo), tooltipTextForAbstractFoo, 1, targetForAbsFoo)}, {7, New InheritanceMarginViewModel( KnownMonikers.Overriding, CreateTextBlock(tooltipTextForBar), tooltipTextForBar, 1, targetForBar)}, {9, New InheritanceMarginViewModel( KnownMonikers.Overriding, CreateTextBlock(tooltipTextForOverrideFoo), tooltipTextForOverrideFoo, 1, targetForOverrideFoo)}}) End Function <WpfFact> Public Function TestInterfaceImplementsInterfaceRelationship() As Task Dim markup = " public interface IBar1 { } public interface IBar2 : IBar1 { } public interface IBar3 : IBar2 { } " Dim tooltipTextForIBar1 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar1") Dim targetForIBar1 = ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types), New TargetMenuItemViewModel("IBar2", KnownMonikers.InterfacePublic, "IBar2", Nothing), New TargetMenuItemViewModel("IBar3", KnownMonikers.InterfacePublic, "IBar3", Nothing)) Dim tooltipTextForIBar2 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar2") Dim targetForIBar2 = ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Inherited_interfaces, KnownMonikers.Implementing, ServicesVSResources.Inherited_interfaces), New TargetMenuItemViewModel("IBar1", KnownMonikers.InterfacePublic, "IBar1", Nothing), New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types), New TargetMenuItemViewModel("IBar3", KnownMonikers.InterfacePublic, "IBar3", Nothing)) Dim tooltipTextForIBar3 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar3") Dim targetForIBar3 = ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Inherited_interfaces, KnownMonikers.Implementing, ServicesVSResources.Inherited_interfaces), New TargetMenuItemViewModel("IBar1", KnownMonikers.InterfacePublic, "IBar1", Nothing), New TargetMenuItemViewModel("IBar2", KnownMonikers.InterfacePublic, "IBar2", Nothing)).CastArray(Of InheritanceMenuItemViewModel) Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginViewModel) From { {2, New InheritanceMarginViewModel( KnownMonikers.Implemented, CreateTextBlock(tooltipTextForIBar1), tooltipTextForIBar1, 1, targetForIBar1)}, {3, New InheritanceMarginViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForIBar2), tooltipTextForIBar2, 1, targetForIBar2)}, {4, New InheritanceMarginViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForIBar3), tooltipTextForIBar3, 1, targetForIBar3)}}) End Function <WpfFact> Public Function TestMutipleMemberOnSameline() As Task Dim markup = " using System; interface IBar1 { public event EventHandler e1, e2; } public class BarSample : IBar1 { public virtual event EventHandler e1, e2; }" Dim tooltipTextForIBar1 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar1") Dim targetForIBar1 = ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types), New TargetMenuItemViewModel("BarSample", KnownMonikers.ClassPublic, "BarSample", Nothing)) Dim tooltipTextForE1AndE2InInterface = ServicesVSResources.Multiple_members_are_inherited Dim targetForE1AndE2InInterface = ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New MemberMenuItemViewModel("event EventHandler IBar1.e1", KnownMonikers.EventPublic, "event EventHandler IBar1.e1", ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implementing_members, KnownMonikers.Implemented, ServicesVSResources.Implementing_members), New TargetMenuItemViewModel("BarSample.e1", KnownMonikers.EventPublic, "BarSample.e1", Nothing))), New MemberMenuItemViewModel("event EventHandler IBar1.e2", KnownMonikers.EventPublic, "event EventHandler IBar1.e2", ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implementing_members, KnownMonikers.Implemented, ServicesVSResources.Implementing_members), New TargetMenuItemViewModel("BarSample.e2", KnownMonikers.EventPublic, "BarSample.e2", Nothing)))) Dim tooltipTextForBarSample = String.Format(ServicesVSResources._0_is_inherited, "class BarSample") Dim targetForBarSample = ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implemented_interfaces, KnownMonikers.Implementing, ServicesVSResources.Implemented_interfaces), New TargetMenuItemViewModel("IBar1", KnownMonikers.InterfaceInternal, "IBar1", Nothing)) Dim tooltipTextForE1AndE2InBarSample = ServicesVSResources.Multiple_members_are_inherited Dim targetForE1AndE2InInBarSample = ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New MemberMenuItemViewModel("virtual event EventHandler BarSample.e1", KnownMonikers.EventPublic, "virtual event EventHandler BarSample.e1", ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implemented_members, KnownMonikers.Implementing, ServicesVSResources.Implemented_members), New TargetMenuItemViewModel("IBar1.e1", KnownMonikers.EventPublic, "IBar1.e1", Nothing)).CastArray(Of InheritanceMenuItemViewModel)), New MemberMenuItemViewModel("virtual event EventHandler BarSample.e2", KnownMonikers.EventPublic, "virtual event EventHandler BarSample.e2", ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implemented_members, KnownMonikers.Implementing, ServicesVSResources.Implemented_members), New TargetMenuItemViewModel("IBar1.e2", KnownMonikers.EventPublic, "IBar1.e2", Nothing)).CastArray(Of InheritanceMenuItemViewModel))) _ .CastArray(Of InheritanceMenuItemViewModel) Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginViewModel) From { {3, New InheritanceMarginViewModel( KnownMonikers.Implemented, CreateTextBlock(tooltipTextForIBar1), tooltipTextForIBar1, 1, targetForIBar1)}, {5, New InheritanceMarginViewModel( KnownMonikers.Implemented, CreateTextBlock(tooltipTextForE1AndE2InInterface), String.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, 5), 1, targetForE1AndE2InInterface)}, {8, New InheritanceMarginViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForBarSample), tooltipTextForBarSample, 1, targetForBarSample)}, {10, New InheritanceMarginViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForE1AndE2InBarSample), String.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, 10), 1, targetForE1AndE2InInBarSample)}}) 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.Text Imports System.Threading Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Documents Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.InheritanceMargin Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Imaging Imports Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin Imports Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph Imports Microsoft.VisualStudio.Text.Classification Imports Microsoft.VisualStudio.Threading Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.InheritanceMargin <Trait(Traits.Feature, Traits.Features.InheritanceMargin)> <UseExportProvider> Public Class InheritanceMarginViewModelTests Private Shared s_defaultMargin As Thickness = New Thickness(4, 1, 4, 1) Private Shared s_indentMargin As Thickness = New Thickness(22, 1, 4, 1) Private Shared Async Function VerifyAsync(markup As String, languageName As String, expectedViewModels As Dictionary(Of Integer, InheritanceMarginViewModel)) As Task ' Add an lf before the document so that the line number starts ' with 1, which meets the line number in the editor (but in fact all things start from 0) Dim workspaceFile = <Workspace> <Project Language=<%= languageName %> CommonReferences="true"> <Document><%= vbLf %> <%= markup.Replace(vbCrLf, vbLf) %> </Document> </Project> </Workspace> Dim cancellationToken As CancellationToken = CancellationToken.None Using workspace = TestWorkspace.Create(workspaceFile) Dim testDocument = workspace.Documents.Single() Dim document = workspace.CurrentSolution.GetDocument(testDocument.Id) Dim service = document.GetRequiredLanguageService(Of IInheritanceMarginService) Dim classificationTypeMap = workspace.ExportProvider.GetExportedValue(Of ClassificationTypeMap) Dim classificationFormatMap = workspace.ExportProvider.GetExportedValue(Of IClassificationFormatMapService) ' For these tests, we need to be on UI thread, so don't call ConfigureAwait(False) Dim root = Await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(True) Dim inheritanceItems = Await service.GetInheritanceMemberItemsAsync(document, root.FullSpan, cancellationToken).ConfigureAwait(True) Dim acutalLineToTagDictionary = inheritanceItems.GroupBy(Function(item) item.LineNumber) _ .ToDictionary(Function(grouping) grouping.Key, Function(grouping) Dim lineNumber = grouping.Key Dim items = grouping.Select(Function(g) g).ToImmutableArray() Return New InheritanceMarginTag(workspace, lineNumber, items) End Function) Assert.Equal(expectedViewModels.Count, acutalLineToTagDictionary.Count) For Each kvp In expectedViewModels Dim lineNumber = kvp.Key Dim expectedViewModel = kvp.Value Assert.True(acutalLineToTagDictionary.ContainsKey(lineNumber)) Dim acutalTag = acutalLineToTagDictionary(lineNumber) ' Editor TestView zoom level is 100 based. Dim actualViewModel = InheritanceMarginViewModel.Create( classificationTypeMap, classificationFormatMap.GetClassificationFormatMap("tooltip"), acutalTag, 100) VerifyTwoViewModelAreSame(expectedViewModel, actualViewModel) Next End Using End Function Private Shared Sub VerifyTwoViewModelAreSame(expected As InheritanceMarginViewModel, actual As InheritanceMarginViewModel) Assert.Equal(expected.ImageMoniker, actual.ImageMoniker) Dim actualTextGetFromTextBlock = actual.ToolTipTextBlock.Inlines _ .OfType(Of Run).Select(Function(run) run.Text) _ .Aggregate(Function(text1, text2) text1 + text2) ' When the text block is created, a unicode 'left to right' would be inserted between the space. ' Make sure it is removed. Dim leftToRightMarker = Char.ConvertFromUtf32(&H200E) Dim actualText = actualTextGetFromTextBlock.Replace(leftToRightMarker, String.Empty) Assert.Equal(expected.ToolTipTextBlock.Text, actualText) Assert.Equal(expected.AutomationName, actual.AutomationName) Assert.Equal(expected.MenuItemViewModels.Length, actual.MenuItemViewModels.Length) Assert.Equal(expected.ScaleFactor, actual.ScaleFactor) For i = 0 To expected.MenuItemViewModels.Length - 1 Dim expectedMenuItem = expected.MenuItemViewModels(i) Dim actualMenuItem = actual.MenuItemViewModels(i) VerifyMenuItem(expectedMenuItem, actualMenuItem) Next End Sub Private Shared Sub VerifyMenuItem(expected As InheritanceMenuItemViewModel, actual As InheritanceMenuItemViewModel) Assert.Equal(expected.AutomationName, actual.AutomationName) Assert.Equal(expected.DisplayContent, actual.DisplayContent) Assert.Equal(expected.ImageMoniker, actual.ImageMoniker) Dim expectedTargetMenuItem = TryCast(expected, TargetMenuItemViewModel) Dim acutalTargetMenuItem = TryCast(actual, TargetMenuItemViewModel) If expectedTargetMenuItem IsNot Nothing AndAlso acutalTargetMenuItem IsNot Nothing Then Return End If Dim expectedMemberMenuItem = TryCast(expected, MemberMenuItemViewModel) Dim acutalMemberMenuItem = TryCast(actual, MemberMenuItemViewModel) If expectedMemberMenuItem IsNot Nothing AndAlso acutalMemberMenuItem IsNot Nothing Then Assert.Equal(expectedMemberMenuItem.Targets.Length, acutalMemberMenuItem.Targets.Length) For i = 0 To expectedMemberMenuItem.Targets.Length - 1 VerifyMenuItem(expectedMemberMenuItem.Targets(i), acutalMemberMenuItem.Targets(i)) Next Return End If ' At this stage, both of the items should be header Assert.True(TypeOf expected Is HeaderMenuItemViewModel) Assert.True(TypeOf actual Is HeaderMenuItemViewModel) End Sub Private Shared Function CreateTextBlock(text As String) As TextBlock Return New TextBlock With { .Text = text } End Function <WpfFact> Public Function TestClassImplementsInterfaceRelationship() As Task Dim markup = " public interface IBar { } public class Bar : IBar { }" Dim tooltipTextForIBar = String.Format(ServicesVSResources._0_is_inherited, "interface IBar") Dim targetForIBar = ImmutableArray.Create(Of InheritanceMenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types)). Add(New TargetMenuItemViewModel("Bar", KnownMonikers.ClassPublic, "Bar", Nothing)) Dim tooltipTextForBar = String.Format(ServicesVSResources._0_is_inherited, "class Bar") Dim targetForBar = ImmutableArray.Create(Of InheritanceMenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Implemented_interfaces, KnownMonikers.Implementing, ServicesVSResources.Implemented_interfaces)). Add(New TargetMenuItemViewModel("IBar", KnownMonikers.InterfacePublic, "IBar", Nothing)) Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginViewModel) From { {2, New InheritanceMarginViewModel( KnownMonikers.Implemented, CreateTextBlock(tooltipTextForIBar), tooltipTextForIBar, 1, targetForIBar)}, {5, New InheritanceMarginViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForBar), tooltipTextForBar, 1, targetForBar)}}) End Function <WpfFact> Public Function TestClassOverridesAbstractClassRelationship() As Task Dim markup = " public abstract class AbsBar { public abstract void Foo(); } public class Bar : AbsBar { public override void Foo(); }" Dim tooltipTextForAbsBar = String.Format(ServicesVSResources._0_is_inherited, "class AbsBar") Dim targetForAbsBar = ImmutableArray.Create(Of InheritanceMenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Derived_types, KnownMonikers.Overridden, ServicesVSResources.Derived_types)). Add(New TargetMenuItemViewModel("Bar", KnownMonikers.ClassPublic, "Bar", Nothing)) Dim tooltipTextForAbstractFoo = String.Format(ServicesVSResources._0_is_inherited, "abstract void AbsBar.Foo()") Dim targetForAbsFoo = ImmutableArray.Create(Of InheritanceMenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Overriding_members, KnownMonikers.Overridden, ServicesVSResources.Overriding_members)). Add(New TargetMenuItemViewModel("Bar.Foo", KnownMonikers.MethodPublic, "Bar.Foo", Nothing)) Dim tooltipTextForBar = String.Format(ServicesVSResources._0_is_inherited, "class Bar") Dim targetForBar = ImmutableArray.Create(Of InheritanceMenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Base_Types, KnownMonikers.Overriding, ServicesVSResources.Base_Types)). Add(New TargetMenuItemViewModel("AbsBar", KnownMonikers.ClassPublic, "AbsBar", Nothing)) Dim tooltipTextForOverrideFoo = String.Format(ServicesVSResources._0_is_inherited, "override void Bar.Foo()") Dim targetForOverrideFoo = ImmutableArray.Create(Of InheritanceMenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Overridden_members, KnownMonikers.Overriding, ServicesVSResources.Overridden_members)). Add(New TargetMenuItemViewModel("AbsBar.Foo", KnownMonikers.MethodPublic, "AbsBar.Foo", Nothing)) Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginViewModel) From { {2, New InheritanceMarginViewModel( KnownMonikers.Overridden, CreateTextBlock(tooltipTextForAbsBar), tooltipTextForAbsBar, 1, targetForAbsBar)}, {4, New InheritanceMarginViewModel( KnownMonikers.Overridden, CreateTextBlock(tooltipTextForAbstractFoo), tooltipTextForAbstractFoo, 1, targetForAbsFoo)}, {7, New InheritanceMarginViewModel( KnownMonikers.Overriding, CreateTextBlock(tooltipTextForBar), tooltipTextForBar, 1, targetForBar)}, {9, New InheritanceMarginViewModel( KnownMonikers.Overriding, CreateTextBlock(tooltipTextForOverrideFoo), tooltipTextForOverrideFoo, 1, targetForOverrideFoo)}}) End Function <WpfFact> Public Function TestInterfaceImplementsInterfaceRelationship() As Task Dim markup = " public interface IBar1 { } public interface IBar2 : IBar1 { } public interface IBar3 : IBar2 { } " Dim tooltipTextForIBar1 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar1") Dim targetForIBar1 = ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types), New TargetMenuItemViewModel("IBar2", KnownMonikers.InterfacePublic, "IBar2", Nothing), New TargetMenuItemViewModel("IBar3", KnownMonikers.InterfacePublic, "IBar3", Nothing)) Dim tooltipTextForIBar2 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar2") Dim targetForIBar2 = ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Inherited_interfaces, KnownMonikers.Implementing, ServicesVSResources.Inherited_interfaces), New TargetMenuItemViewModel("IBar1", KnownMonikers.InterfacePublic, "IBar1", Nothing), New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types), New TargetMenuItemViewModel("IBar3", KnownMonikers.InterfacePublic, "IBar3", Nothing)) Dim tooltipTextForIBar3 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar3") Dim targetForIBar3 = ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Inherited_interfaces, KnownMonikers.Implementing, ServicesVSResources.Inherited_interfaces), New TargetMenuItemViewModel("IBar1", KnownMonikers.InterfacePublic, "IBar1", Nothing), New TargetMenuItemViewModel("IBar2", KnownMonikers.InterfacePublic, "IBar2", Nothing)).CastArray(Of InheritanceMenuItemViewModel) Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginViewModel) From { {2, New InheritanceMarginViewModel( KnownMonikers.Implemented, CreateTextBlock(tooltipTextForIBar1), tooltipTextForIBar1, 1, targetForIBar1)}, {3, New InheritanceMarginViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForIBar2), tooltipTextForIBar2, 1, targetForIBar2)}, {4, New InheritanceMarginViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForIBar3), tooltipTextForIBar3, 1, targetForIBar3)}}) End Function <WpfFact> Public Function TestMutipleMemberOnSameline() As Task Dim markup = " using System; interface IBar1 { public event EventHandler e1, e2; } public class BarSample : IBar1 { public virtual event EventHandler e1, e2; }" Dim tooltipTextForIBar1 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar1") Dim targetForIBar1 = ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types), New TargetMenuItemViewModel("BarSample", KnownMonikers.ClassPublic, "BarSample", Nothing)) Dim tooltipTextForE1AndE2InInterface = ServicesVSResources.Multiple_members_are_inherited Dim targetForE1AndE2InInterface = ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New MemberMenuItemViewModel("event EventHandler IBar1.e1", KnownMonikers.EventPublic, "event EventHandler IBar1.e1", ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implementing_members, KnownMonikers.Implemented, ServicesVSResources.Implementing_members), New TargetMenuItemViewModel("BarSample.e1", KnownMonikers.EventPublic, "BarSample.e1", Nothing))), New MemberMenuItemViewModel("event EventHandler IBar1.e2", KnownMonikers.EventPublic, "event EventHandler IBar1.e2", ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implementing_members, KnownMonikers.Implemented, ServicesVSResources.Implementing_members), New TargetMenuItemViewModel("BarSample.e2", KnownMonikers.EventPublic, "BarSample.e2", Nothing)))) Dim tooltipTextForBarSample = String.Format(ServicesVSResources._0_is_inherited, "class BarSample") Dim targetForBarSample = ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implemented_interfaces, KnownMonikers.Implementing, ServicesVSResources.Implemented_interfaces), New TargetMenuItemViewModel("IBar1", KnownMonikers.InterfaceInternal, "IBar1", Nothing)) Dim tooltipTextForE1AndE2InBarSample = ServicesVSResources.Multiple_members_are_inherited Dim targetForE1AndE2InInBarSample = ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New MemberMenuItemViewModel("virtual event EventHandler BarSample.e1", KnownMonikers.EventPublic, "virtual event EventHandler BarSample.e1", ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implemented_members, KnownMonikers.Implementing, ServicesVSResources.Implemented_members), New TargetMenuItemViewModel("IBar1.e1", KnownMonikers.EventPublic, "IBar1.e1", Nothing)).CastArray(Of InheritanceMenuItemViewModel)), New MemberMenuItemViewModel("virtual event EventHandler BarSample.e2", KnownMonikers.EventPublic, "virtual event EventHandler BarSample.e2", ImmutableArray.Create(Of InheritanceMenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implemented_members, KnownMonikers.Implementing, ServicesVSResources.Implemented_members), New TargetMenuItemViewModel("IBar1.e2", KnownMonikers.EventPublic, "IBar1.e2", Nothing)).CastArray(Of InheritanceMenuItemViewModel))) _ .CastArray(Of InheritanceMenuItemViewModel) Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginViewModel) From { {3, New InheritanceMarginViewModel( KnownMonikers.Implemented, CreateTextBlock(tooltipTextForIBar1), tooltipTextForIBar1, 1, targetForIBar1)}, {5, New InheritanceMarginViewModel( KnownMonikers.Implemented, CreateTextBlock(tooltipTextForE1AndE2InInterface), String.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, 5), 1, targetForE1AndE2InInterface)}, {8, New InheritanceMarginViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForBarSample), tooltipTextForBarSample, 1, targetForBarSample)}, {10, New InheritanceMarginViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForE1AndE2InBarSample), String.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, 10), 1, targetForE1AndE2InInBarSample)}}) End Function End Class End Namespace
1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Test/Core/Diagnostics/OperationTestAnalyzer.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 Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { // These analyzers are not intended for any actual use. They exist solely to test IOperation support. /// <summary>Analyzer used to test for bad statements and expressions.</summary> public class BadStuffTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor InvalidExpressionDescriptor = new DiagnosticDescriptor( "InvalidExpression", "Invalid Expression", "Invalid expression found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor InvalidStatementDescriptor = new DiagnosticDescriptor( "InvalidStatement", "Invalid Statement", "Invalid statement found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor IsInvalidDescriptor = new DiagnosticDescriptor( "IsInvalid", "Is Invalid", "Operation found that is invalid.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(InvalidExpressionDescriptor, InvalidStatementDescriptor, IsInvalidDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var invalidOperation = (IInvalidOperation)operationContext.Operation; if (invalidOperation.Type == null) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidStatementDescriptor, operationContext.Operation.Syntax.GetLocation())); } else { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidExpressionDescriptor, operationContext.Operation.Syntax.GetLocation())); } }, OperationKind.Invalid); context.RegisterOperationAction( (operationContext) => { if (operationContext.Operation.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { operationContext.ReportDiagnostic(Diagnostic.Create(IsInvalidDescriptor, operationContext.Operation.Syntax.GetLocation())); } }, OperationKind.Invocation, OperationKind.Invalid); } } /// <summary>Analyzer used to test for operations within symbols of certain names.</summary> public class OwningSymbolTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor ExpressionDescriptor = new DiagnosticDescriptor( "Expression", "Expression", "Expression found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(ExpressionDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction( (operationBlockContext) => { if (operationBlockContext.Compilation.Language != "Stumble") { operationBlockContext.RegisterOperationAction( (operationContext) => { if (operationContext.ContainingSymbol.Name.StartsWith("Funky") && operationContext.Compilation.Language != "Mumble") { operationContext.ReportDiagnostic(Diagnostic.Create(ExpressionDescriptor, operationContext.Operation.Syntax.GetLocation())); } }, OperationKind.LocalReference, OperationKind.Literal); } }); } } /// <summary>Analyzer used to test for loop IOperations.</summary> public class BigForTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Reliability".</summary> private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor BigForDescriptor = new DiagnosticDescriptor( "BigForRule", "Big For Loop", "For loop iterates more than one million times", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(BigForDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction(AnalyzeOperation, OperationKind.Loop); } private void AnalyzeOperation(OperationAnalysisContext operationContext) { ILoopOperation loop = (ILoopOperation)operationContext.Operation; if (loop.LoopKind == LoopKind.For) { IForLoopOperation forLoop = (IForLoopOperation)loop; IOperation forCondition = forLoop.Condition; if (forCondition.Kind == OperationKind.Binary) { IBinaryOperation condition = (IBinaryOperation)forCondition; IOperation conditionLeft = condition.LeftOperand; IOperation conditionRight = condition.RightOperand; if (conditionRight.ConstantValue.HasValue && conditionRight.Type.SpecialType == SpecialType.System_Int32 && conditionLeft.Kind == OperationKind.LocalReference) { // Test is known to be a comparison of a local against a constant. int testValue = (int)conditionRight.ConstantValue.Value; ILocalSymbol testVariable = ((ILocalReferenceOperation)conditionLeft).Local; if (forLoop.Before.Length == 1) { IOperation setup = forLoop.Before[0]; if (setup.Kind == OperationKind.ExpressionStatement && ((IExpressionStatementOperation)setup).Operation.Kind == OperationKind.SimpleAssignment) { ISimpleAssignmentOperation setupAssignment = (ISimpleAssignmentOperation)((IExpressionStatementOperation)setup).Operation; if (setupAssignment.Target.Kind == OperationKind.LocalReference && ((ILocalReferenceOperation)setupAssignment.Target).Local == testVariable && setupAssignment.Value.ConstantValue.HasValue && setupAssignment.Value.Type.SpecialType == SpecialType.System_Int32) { // Setup is known to be an assignment of a constant to the local used in the test. int initialValue = (int)setupAssignment.Value.ConstantValue.Value; if (forLoop.AtLoopBottom.Length == 1) { IOperation advance = forLoop.AtLoopBottom[0]; if (advance.Kind == OperationKind.ExpressionStatement) { IOperation advanceExpression = ((IExpressionStatementOperation)advance).Operation; Optional<object> advanceIncrementOpt; BinaryOperatorKind? advanceOperationCode; GetOperationKindAndValue(testVariable, advanceExpression, out advanceOperationCode, out advanceIncrementOpt); if (advanceIncrementOpt.HasValue && advanceOperationCode.HasValue) { var incrementValue = (int)advanceIncrementOpt.Value; if (advanceOperationCode.Value == BinaryOperatorKind.Subtract) { advanceOperationCode = BinaryOperatorKind.Add; incrementValue = -incrementValue; } if (advanceOperationCode.Value == BinaryOperatorKind.Add && incrementValue != 0 && (condition.OperatorKind == BinaryOperatorKind.LessThan || condition.OperatorKind == BinaryOperatorKind.LessThanOrEqual || condition.OperatorKind == BinaryOperatorKind.NotEquals || condition.OperatorKind == BinaryOperatorKind.GreaterThan || condition.OperatorKind == BinaryOperatorKind.GreaterThanOrEqual)) { int iterationCount = (testValue - initialValue) / incrementValue; if (iterationCount >= 1000000) { Report(operationContext, forLoop.Syntax, BigForDescriptor); } } } } } } } } } } } } private void GetOperationKindAndValue( ILocalSymbol testVariable, IOperation advanceExpression, out BinaryOperatorKind? advanceOperationCode, out Optional<object> advanceIncrementOpt) { advanceIncrementOpt = null; advanceOperationCode = null; if (advanceExpression.Kind == OperationKind.SimpleAssignment) { ISimpleAssignmentOperation advanceAssignment = (ISimpleAssignmentOperation)advanceExpression; if (advanceAssignment.Target.Kind == OperationKind.LocalReference && ((ILocalReferenceOperation)advanceAssignment.Target).Local == testVariable && advanceAssignment.Value.Kind == OperationKind.Binary && advanceAssignment.Value.Type.SpecialType == SpecialType.System_Int32) { // Advance is known to be an assignment of a binary operation to the local used in the test. IBinaryOperation advanceOperation = (IBinaryOperation)advanceAssignment.Value; if (advanceOperation.OperatorMethod == null && advanceOperation.LeftOperand.Kind == OperationKind.LocalReference && ((ILocalReferenceOperation)advanceOperation.LeftOperand).Local == testVariable && advanceOperation.RightOperand.ConstantValue.HasValue && advanceOperation.RightOperand.Type.SpecialType == SpecialType.System_Int32) { // Advance binary operation is known to involve a reference to the local used in the test and a constant. advanceIncrementOpt = advanceOperation.RightOperand.ConstantValue; advanceOperationCode = advanceOperation.OperatorKind; } } } else if (advanceExpression.Kind == OperationKind.CompoundAssignment) { ICompoundAssignmentOperation advanceAssignment = (ICompoundAssignmentOperation)advanceExpression; if (advanceAssignment.Target.Kind == OperationKind.LocalReference && ((ILocalReferenceOperation)advanceAssignment.Target).Local == testVariable && advanceAssignment.Value.ConstantValue.HasValue && advanceAssignment.Value.Type.SpecialType == SpecialType.System_Int32) { // Advance binary operation is known to involve a reference to the local used in the test and a constant. advanceIncrementOpt = advanceAssignment.Value.ConstantValue; advanceOperationCode = advanceAssignment.OperatorKind; } } else if (advanceExpression.Kind == OperationKind.Increment) { IIncrementOrDecrementOperation advanceAssignment = (IIncrementOrDecrementOperation)advanceExpression; if (advanceAssignment.Target.Kind == OperationKind.LocalReference && ((ILocalReferenceOperation)advanceAssignment.Target).Local == testVariable) { // Advance binary operation is known to involve a reference to the local used in the test and a constant. advanceIncrementOpt = new Optional<object>(1); advanceOperationCode = BinaryOperatorKind.Add; } } } private static int Abs(int value) { return value < 0 ? -value : value; } private void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test switch IOperations.</summary> public class SwitchTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Reliability".</summary> private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor SparseSwitchDescriptor = new DiagnosticDescriptor( "SparseSwitchRule", "Sparse switch", "Switch has less than one percent density", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor NoDefaultSwitchDescriptor = new DiagnosticDescriptor( "NoDefaultSwitchRule", "No default switch", "Switch has no default case", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor OnlyDefaultSwitchDescriptor = new DiagnosticDescriptor( "OnlyDefaultSwitchRule", "Only default switch", "Switch only has a default case", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(SparseSwitchDescriptor, NoDefaultSwitchDescriptor, OnlyDefaultSwitchDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { ISwitchOperation switchOperation = (ISwitchOperation)operationContext.Operation; long minCaseValue = long.MaxValue; long maxCaseValue = long.MinValue; long caseValueCount = 0; bool hasDefault = false; bool hasNonDefault = false; foreach (ISwitchCaseOperation switchCase in switchOperation.Cases) { foreach (ICaseClauseOperation clause in switchCase.Clauses) { switch (clause.CaseKind) { case CaseKind.SingleValue: { hasNonDefault = true; ISingleValueCaseClauseOperation singleValueClause = (ISingleValueCaseClauseOperation)clause; IOperation singleValueExpression = singleValueClause.Value; if (singleValueExpression != null && singleValueExpression.ConstantValue.HasValue && singleValueExpression.Type.SpecialType == SpecialType.System_Int32) { int singleValue = (int)singleValueExpression.ConstantValue.Value; caseValueCount += IncludeClause(singleValue, singleValue, ref minCaseValue, ref maxCaseValue); } else { return; } break; } case CaseKind.Range: { hasNonDefault = true; IRangeCaseClauseOperation rangeClause = (IRangeCaseClauseOperation)clause; IOperation rangeMinExpression = rangeClause.MinimumValue; IOperation rangeMaxExpression = rangeClause.MaximumValue; if (rangeMinExpression != null && rangeMinExpression.ConstantValue.HasValue && rangeMinExpression.Type.SpecialType == SpecialType.System_Int32 && rangeMaxExpression != null && rangeMaxExpression.ConstantValue.HasValue && rangeMaxExpression.Type.SpecialType == SpecialType.System_Int32) { int rangeMinValue = (int)rangeMinExpression.ConstantValue.Value; int rangeMaxValue = (int)rangeMaxExpression.ConstantValue.Value; caseValueCount += IncludeClause(rangeMinValue, rangeMaxValue, ref minCaseValue, ref maxCaseValue); } else { return; } break; } case CaseKind.Relational: { hasNonDefault = true; IRelationalCaseClauseOperation relationalClause = (IRelationalCaseClauseOperation)clause; IOperation relationalValueExpression = relationalClause.Value; if (relationalValueExpression != null && relationalValueExpression.ConstantValue.HasValue && relationalValueExpression.Type.SpecialType == SpecialType.System_Int32) { int rangeMinValue = int.MaxValue; int rangeMaxValue = int.MinValue; int relationalValue = (int)relationalValueExpression.ConstantValue.Value; switch (relationalClause.Relation) { case BinaryOperatorKind.Equals: rangeMinValue = relationalValue; rangeMaxValue = relationalValue; break; case BinaryOperatorKind.NotEquals: return; case BinaryOperatorKind.LessThan: rangeMinValue = int.MinValue; rangeMaxValue = relationalValue - 1; break; case BinaryOperatorKind.LessThanOrEqual: rangeMinValue = int.MinValue; rangeMaxValue = relationalValue; break; case BinaryOperatorKind.GreaterThanOrEqual: rangeMinValue = relationalValue; rangeMaxValue = int.MaxValue; break; case BinaryOperatorKind.GreaterThan: rangeMinValue = relationalValue + 1; rangeMaxValue = int.MaxValue; break; } caseValueCount += IncludeClause(rangeMinValue, rangeMaxValue, ref minCaseValue, ref maxCaseValue); } else { return; } break; } case CaseKind.Default: { hasDefault = true; break; } } } } long span = maxCaseValue - minCaseValue + 1; if (caseValueCount == 0 && !hasDefault || caseValueCount != 0 && span / caseValueCount > 100) { Report(operationContext, switchOperation.Value.Syntax, SparseSwitchDescriptor); } if (!hasDefault) { Report(operationContext, switchOperation.Value.Syntax, NoDefaultSwitchDescriptor); } if (hasDefault && !hasNonDefault) { Report(operationContext, switchOperation.Value.Syntax, OnlyDefaultSwitchDescriptor); } }, OperationKind.Switch); } private static int IncludeClause(int clauseMinValue, int clauseMaxValue, ref long minCaseValue, ref long maxCaseValue) { if (clauseMinValue < minCaseValue) { minCaseValue = clauseMinValue; } if (clauseMaxValue > maxCaseValue) { maxCaseValue = clauseMaxValue; } return clauseMaxValue - clauseMinValue + 1; } private void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test invocation IOperations.</summary> public class InvocationTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Reliability".</summary> private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor BigParamArrayArgumentsDescriptor = new DiagnosticDescriptor( "BigParamarrayRule", "Big Paramarray", "Paramarray has more than 10 elements", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor OutOfNumericalOrderArgumentsDescriptor = new DiagnosticDescriptor( "OutOfOrderArgumentsRule", "Out of order arguments", "Argument values are not in increasing order", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor UseDefaultArgumentDescriptor = new DiagnosticDescriptor( "UseDefaultArgument", "Use default argument", "Invocation uses default argument {0}", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor InvalidArgumentDescriptor = new DiagnosticDescriptor( "InvalidArgument", "Invalid argument", "Invocation has invalid argument", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(BigParamArrayArgumentsDescriptor, OutOfNumericalOrderArgumentsDescriptor, UseDefaultArgumentDescriptor, InvalidArgumentDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { IInvocationOperation invocation = (IInvocationOperation)operationContext.Operation; long priorArgumentValue = long.MinValue; foreach (IArgumentOperation argument in invocation.Arguments) { if (argument.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidArgumentDescriptor, argument.Syntax.GetLocation())); return; } if (argument.ArgumentKind == ArgumentKind.DefaultValue) { operationContext.ReportDiagnostic(Diagnostic.Create(UseDefaultArgumentDescriptor, invocation.Syntax.GetLocation(), argument.Parameter.Name)); } TestAscendingArgument(operationContext, argument.Value, ref priorArgumentValue); if (argument.ArgumentKind == ArgumentKind.ParamArray) { if (argument.Value is IArrayCreationOperation arrayArgument) { var initializer = arrayArgument.Initializer; if (initializer != null) { if (initializer.ElementValues.Length > 10) { Report(operationContext, invocation.Syntax, BigParamArrayArgumentsDescriptor); } foreach (IOperation element in initializer.ElementValues) { TestAscendingArgument(operationContext, element, ref priorArgumentValue); } } } } } }, OperationKind.Invocation); } private static void TestAscendingArgument(OperationAnalysisContext operationContext, IOperation argument, ref long priorArgumentValue) { Optional<object> argumentValue = argument.ConstantValue; if (argumentValue.HasValue && argument.Type.SpecialType == SpecialType.System_Int32) { int integerArgument = (int)argumentValue.Value; if (integerArgument < priorArgumentValue) { Report(operationContext, argument.Syntax, OutOfNumericalOrderArgumentsDescriptor); } priorArgumentValue = integerArgument; } } private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test various contexts in which IOperations can occur.</summary> public class SeventeenTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Reliability".</summary> private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor SeventeenDescriptor = new DiagnosticDescriptor( "SeventeenRule", "Seventeen", "Seventeen is a recognized value", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(SeventeenDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { ILiteralOperation literal = (ILiteralOperation)operationContext.Operation; if (literal.Type.SpecialType == SpecialType.System_Int32 && literal.ConstantValue.HasValue && (int)literal.ConstantValue.Value == 17) { operationContext.ReportDiagnostic(Diagnostic.Create(SeventeenDescriptor, literal.Syntax.GetLocation())); } }, OperationKind.Literal); } } /// <summary>Analyzer used to test IArgument IOperations.</summary> public class NullArgumentTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Reliability".</summary> private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor NullArgumentsDescriptor = new DiagnosticDescriptor( "NullArgumentRule", "Null Argument", "Value of the argument is null", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(NullArgumentsDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var argument = (IArgumentOperation)operationContext.Operation; if (argument.Value.ConstantValue.HasValue && argument.Value.ConstantValue.Value == null) { Report(operationContext, argument.Syntax, NullArgumentsDescriptor); } }, OperationKind.Argument); } private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test IMemberInitializer IOperations.</summary> public class MemberInitializerTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Reliability".</summary> private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor DoNotUseFieldInitializerDescriptor = new DiagnosticDescriptor( "DoNotUseFieldInitializer", "Do Not Use Field Initializer", "a field initializer is used for object creation", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor DoNotUsePropertyInitializerDescriptor = new DiagnosticDescriptor( "DoNotUsePropertyInitializer", "Do Not Use Property Initializer", "A property initializer is used for object creation", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(DoNotUseFieldInitializerDescriptor, DoNotUsePropertyInitializerDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var initializer = operationContext.Operation; Report(operationContext, initializer.Syntax, initializer.Kind == OperationKind.FieldReference ? DoNotUseFieldInitializerDescriptor : DoNotUsePropertyInitializerDescriptor); }, OperationKind.FieldReference, OperationKind.PropertyReference); } private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test IAssignmentExpression IOperations.</summary> public class AssignmentTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Reliability".</summary> private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor DoNotUseMemberAssignmentDescriptor = new DiagnosticDescriptor( "DoNotUseMemberAssignment", "Do Not Use Member Assignment", "Do not assign values to object members", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(DoNotUseMemberAssignmentDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var assignment = (ISimpleAssignmentOperation)operationContext.Operation; var kind = assignment.Target.Kind; if (kind == OperationKind.FieldReference || kind == OperationKind.PropertyReference) { Report(operationContext, assignment.Syntax, DoNotUseMemberAssignmentDescriptor); } }, OperationKind.SimpleAssignment); } private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test IArrayInitializer IOperations.</summary> public class ArrayInitializerTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Maintainability".</summary> private const string Maintainability = nameof(Maintainability); public static readonly DiagnosticDescriptor DoNotUseLargeListOfArrayInitializersDescriptor = new DiagnosticDescriptor( "DoNotUseLongListToInitializeArray", "Do not use long list to initialize array", "a list of more than 5 elements is used for an array initialization", Maintainability, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(DoNotUseLargeListOfArrayInitializersDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var initializer = (IArrayInitializerOperation)operationContext.Operation; if (initializer.ElementValues.Length > 5) { Report(operationContext, initializer.Syntax, DoNotUseLargeListOfArrayInitializersDescriptor); } }, OperationKind.ArrayInitializer); } private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test IVariableDeclarationStatement IOperations.</summary> public class VariableDeclarationTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Maintainability".</summary> private const string Maintainability = nameof(Maintainability); public static readonly DiagnosticDescriptor TooManyLocalVarDeclarationsDescriptor = new DiagnosticDescriptor( "TooManyLocalVarDeclarations", "Too many local variable declarations", "A declaration statement shouldn't have more than 3 variable declarations", Maintainability, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor LocalVarInitializedDeclarationDescriptor = new DiagnosticDescriptor( "LocalVarInitializedDeclaration", "Local var initialized at declaration", "A local variable is initialized at declaration.", Maintainability, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(TooManyLocalVarDeclarationsDescriptor, LocalVarInitializedDeclarationDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var declarationStatement = (IVariableDeclarationGroupOperation)operationContext.Operation; if (declarationStatement.GetDeclaredVariables().Count() > 3) { Report(operationContext, declarationStatement.Syntax, TooManyLocalVarDeclarationsDescriptor); } foreach (var decl in declarationStatement.Declarations.SelectMany(multiDecl => multiDecl.Declarators)) { var initializer = decl.GetVariableInitializer(); if (initializer != null && !initializer.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { Report(operationContext, decl.Symbol.DeclaringSyntaxReferences.Single().GetSyntax(), LocalVarInitializedDeclarationDescriptor); } } }, OperationKind.VariableDeclarationGroup); } private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test ICase and ICaseClause.</summary> public class CaseTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Maintainability".</summary> private const string Maintainability = nameof(Maintainability); public static readonly DiagnosticDescriptor HasDefaultCaseDescriptor = new DiagnosticDescriptor( "HasDefaultCase", "Has Default Case", "A default case clause is encountered", Maintainability, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor MultipleCaseClausesDescriptor = new DiagnosticDescriptor( "MultipleCaseClauses", "Multiple Case Clauses", "A switch section has multiple case clauses", Maintainability, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(HasDefaultCaseDescriptor, MultipleCaseClausesDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { switch (operationContext.Operation.Kind) { case OperationKind.CaseClause: var caseClause = (ICaseClauseOperation)operationContext.Operation; if (caseClause.CaseKind == CaseKind.Default) { Report(operationContext, caseClause.Syntax, HasDefaultCaseDescriptor); } break; case OperationKind.SwitchCase: var switchSection = (ISwitchCaseOperation)operationContext.Operation; if (!switchSection.HasErrors(operationContext.Compilation, operationContext.CancellationToken) && switchSection.Clauses.Length > 1) { Report(operationContext, switchSection.Syntax, MultipleCaseClausesDescriptor); } break; } }, OperationKind.SwitchCase, OperationKind.CaseClause); } private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test for explicit vs. implicit instance references.</summary> public class ExplicitVsImplicitInstanceAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor ImplicitInstanceDescriptor = new DiagnosticDescriptor( "ImplicitInstance", "Implicit Instance", "Implicit instance found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor ExplicitInstanceDescriptor = new DiagnosticDescriptor( "ExplicitInstance", "Explicit Instance", "Explicit instance found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(ImplicitInstanceDescriptor, ExplicitInstanceDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { IInstanceReferenceOperation instanceReference = (IInstanceReferenceOperation)operationContext.Operation; operationContext.ReportDiagnostic(Diagnostic.Create(instanceReference.IsImplicit ? ImplicitInstanceDescriptor : ExplicitInstanceDescriptor, instanceReference.Syntax.GetLocation())); }, OperationKind.InstanceReference); } } /// <summary>Analyzer used to test for member references.</summary> public class MemberReferenceAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor EventReferenceDescriptor = new DiagnosticDescriptor( "EventReference", "Event Reference", "Event reference found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor InvalidEventDescriptor = new DiagnosticDescriptor( "InvalidEvent", "Invalid Event", "A EventAssignmentExpression with invalid event found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor HandlerAddedDescriptor = new DiagnosticDescriptor( "HandlerAdded", "Handler Added", "Event handler added.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor HandlerRemovedDescriptor = new DiagnosticDescriptor( "HandlerRemoved", "Handler Removed", "Event handler removed.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor PropertyReferenceDescriptor = new DiagnosticDescriptor( "PropertyReference", "Property Reference", "Property reference found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor FieldReferenceDescriptor = new DiagnosticDescriptor( "FieldReference", "Field Reference", "Field reference found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor MethodBindingDescriptor = new DiagnosticDescriptor( "MethodBinding", "Method Binding", "Method binding found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(EventReferenceDescriptor, HandlerAddedDescriptor, HandlerRemovedDescriptor, PropertyReferenceDescriptor, FieldReferenceDescriptor, MethodBindingDescriptor, InvalidEventDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic(Diagnostic.Create(EventReferenceDescriptor, operationContext.Operation.Syntax.GetLocation())); }, OperationKind.EventReference); context.RegisterOperationAction( (operationContext) => { IEventAssignmentOperation eventAssignment = (IEventAssignmentOperation)operationContext.Operation; operationContext.ReportDiagnostic(Diagnostic.Create(eventAssignment.Adds ? HandlerAddedDescriptor : HandlerRemovedDescriptor, operationContext.Operation.Syntax.GetLocation())); if (eventAssignment.EventReference.Kind == OperationKind.Invalid || eventAssignment.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidEventDescriptor, eventAssignment.Syntax.GetLocation())); } }, OperationKind.EventAssignment); context.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic(Diagnostic.Create(PropertyReferenceDescriptor, operationContext.Operation.Syntax.GetLocation())); }, OperationKind.PropertyReference); context.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic(Diagnostic.Create(FieldReferenceDescriptor, operationContext.Operation.Syntax.GetLocation())); }, OperationKind.FieldReference); context.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic(Diagnostic.Create(MethodBindingDescriptor, operationContext.Operation.Syntax.GetLocation())); }, OperationKind.MethodReference); } } /// <summary>Analyzer used to test IOperation treatment of params array arguments.</summary> public class ParamsArrayTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor LongParamsDescriptor = new DiagnosticDescriptor( "LongParams", "Long Params", "Params array argument has more than 3 elements.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor InvalidConstructorDescriptor = new DiagnosticDescriptor( "InvalidConstructor", "Invalid Constructor", "Invalid Constructor.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(LongParamsDescriptor, InvalidConstructorDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { IInvocationOperation invocation = (IInvocationOperation)operationContext.Operation; foreach (IArgumentOperation argument in invocation.Arguments) { if (argument.Parameter.IsParams) { if (argument.Value is IArrayCreationOperation arrayValue) { Optional<object> dimensionSize = arrayValue.DimensionSizes[0].ConstantValue; if (dimensionSize.HasValue && IntegralValue(dimensionSize.Value) > 3) { operationContext.ReportDiagnostic(Diagnostic.Create(LongParamsDescriptor, argument.Value.Syntax.GetLocation())); } } } } }, OperationKind.Invocation); context.RegisterOperationAction( (operationContext) => { IObjectCreationOperation creation = (IObjectCreationOperation)operationContext.Operation; if (creation.Constructor == null) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidConstructorDescriptor, creation.Syntax.GetLocation())); } foreach (IArgumentOperation argument in creation.Arguments) { if (argument.Parameter.IsParams) { if (argument.Value is IArrayCreationOperation arrayValue) { Optional<object> dimensionSize = arrayValue.DimensionSizes[0].ConstantValue; if (dimensionSize.HasValue && IntegralValue(dimensionSize.Value) > 3) { operationContext.ReportDiagnostic(Diagnostic.Create(LongParamsDescriptor, argument.Value.Syntax.GetLocation())); } } } } }, OperationKind.ObjectCreation); } private static long IntegralValue(object value) { if (value is long v) { return v; } if (value is int i) { return i; } return 0; } } /// <summary>Analyzer used to test for initializer constructs for members and parameters.</summary> public class EqualsValueTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor EqualsValueDescriptor = new DiagnosticDescriptor( "EqualsValue", "Equals Value", "Equals value found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(EqualsValueDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { IFieldInitializerOperation equalsValue = (IFieldInitializerOperation)operationContext.Operation; if (equalsValue.InitializedFields[0].Name.StartsWith("F")) { operationContext.ReportDiagnostic(Diagnostic.Create(EqualsValueDescriptor, equalsValue.Syntax.GetLocation())); } }, OperationKind.FieldInitializer); context.RegisterOperationAction( (operationContext) => { IParameterInitializerOperation equalsValue = (IParameterInitializerOperation)operationContext.Operation; if (equalsValue.Parameter.Name.StartsWith("F")) { operationContext.ReportDiagnostic(Diagnostic.Create(EqualsValueDescriptor, equalsValue.Syntax.GetLocation())); } }, OperationKind.ParameterInitializer); } } /// <summary>Analyzer used to test None IOperations.</summary> public class NoneOperationTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; // We should not see this warning triggered by any code public static readonly DiagnosticDescriptor NoneOperationDescriptor = new DiagnosticDescriptor( "NoneOperation", "None operation found", "An IOperation of None kind is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(NoneOperationDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic(Diagnostic.Create(NoneOperationDescriptor, operationContext.Operation.Syntax.GetLocation())); }, // None kind is only supposed to be used internally and will not actually register actions. OperationKind.None); } } public class AddressOfTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor AddressOfDescriptor = new DiagnosticDescriptor( "AddressOfOperation", "AddressOf operation found", "An AddressOf operation found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor InvalidAddressOfReferenceDescriptor = new DiagnosticDescriptor( "InvalidAddressOfReference", "Invalid AddressOf reference found", "An invalid AddressOf reference found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(AddressOfDescriptor, InvalidAddressOfReferenceDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var addressOfOperation = (IAddressOfOperation)operationContext.Operation; operationContext.ReportDiagnostic(Diagnostic.Create(AddressOfDescriptor, addressOfOperation.Syntax.GetLocation())); if (addressOfOperation.Reference.Kind == OperationKind.Invalid && addressOfOperation.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidAddressOfReferenceDescriptor, addressOfOperation.Reference.Syntax.GetLocation())); } }, OperationKind.AddressOf); } } /// <summary>Analyzer used to test LambdaExpression IOperations.</summary> public class LambdaTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor LambdaExpressionDescriptor = new DiagnosticDescriptor( "LambdaExpression", "Lambda expression found", "A Lambda expression is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor TooManyStatementsInLambdaExpressionDescriptor = new DiagnosticDescriptor( "TooManyStatementsInLambdaExpression", "Too many statements in a Lambda expression", "More than 3 statements in a Lambda expression", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); // This warning should never be triggered. public static readonly DiagnosticDescriptor NoneOperationInLambdaExpressionDescriptor = new DiagnosticDescriptor( "NoneOperationInLambdaExpression", "None Operation found in Lambda expression", "None Operation is found Lambda expression", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(LambdaExpressionDescriptor, TooManyStatementsInLambdaExpressionDescriptor, NoneOperationInLambdaExpressionDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var lambdaExpression = (IAnonymousFunctionOperation)operationContext.Operation; operationContext.ReportDiagnostic(Diagnostic.Create(LambdaExpressionDescriptor, operationContext.Operation.Syntax.GetLocation())); var block = lambdaExpression.Body; // TODO: Can this possibly be null? Remove check if not. if (block == null) { return; } if (block.Operations.Length > 3) { operationContext.ReportDiagnostic(Diagnostic.Create(TooManyStatementsInLambdaExpressionDescriptor, operationContext.Operation.Syntax.GetLocation())); } bool flag = false; foreach (var statement in block.Operations) { if (statement.Kind == OperationKind.None) { flag = true; break; } } if (flag) { operationContext.ReportDiagnostic(Diagnostic.Create(NoneOperationInLambdaExpressionDescriptor, operationContext.Operation.Syntax.GetLocation())); } }, OperationKind.AnonymousFunction); } } public class StaticMemberTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor StaticMemberDescriptor = new DiagnosticDescriptor( "StaticMember", "Static member found", "A static member reference expression is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); // We should not see this warning triggered by any code public static readonly DiagnosticDescriptor StaticMemberWithInstanceDescriptor = new DiagnosticDescriptor( "StaticMemberWithInstance", "Static member with non null Instance found", "A static member reference with non null Instance is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(StaticMemberDescriptor, StaticMemberWithInstanceDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var operation = operationContext.Operation; ISymbol memberSymbol; IOperation receiver; switch (operation.Kind) { case OperationKind.FieldReference: memberSymbol = ((IFieldReferenceOperation)operation).Field; receiver = ((IFieldReferenceOperation)operation).Instance; break; case OperationKind.PropertyReference: memberSymbol = ((IPropertyReferenceOperation)operation).Property; receiver = ((IPropertyReferenceOperation)operation).Instance; break; case OperationKind.EventReference: memberSymbol = ((IEventReferenceOperation)operation).Event; receiver = ((IEventReferenceOperation)operation).Instance; break; case OperationKind.MethodReference: memberSymbol = ((IMethodReferenceOperation)operation).Method; receiver = ((IMethodReferenceOperation)operation).Instance; break; case OperationKind.Invocation: memberSymbol = ((IInvocationOperation)operation).TargetMethod; receiver = ((IInvocationOperation)operation).Instance; break; default: throw new ArgumentException(); } if (memberSymbol.IsStatic) { operationContext.ReportDiagnostic(Diagnostic.Create(StaticMemberDescriptor, operation.Syntax.GetLocation())); if (receiver != null) { operationContext.ReportDiagnostic(Diagnostic.Create(StaticMemberWithInstanceDescriptor, operation.Syntax.GetLocation())); } } }, OperationKind.FieldReference, OperationKind.PropertyReference, OperationKind.EventReference, OperationKind.MethodReference, OperationKind.Invocation); } } public class LabelOperationsTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor LabelDescriptor = new DiagnosticDescriptor( "Label", "Label found", "A label was was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor GotoDescriptor = new DiagnosticDescriptor( "Goto", "Goto found", "A goto was was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(LabelDescriptor, GotoDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { ILabelSymbol label = ((ILabeledOperation)operationContext.Operation).Label; if (label.Name == "Wilma" || label.Name == "Betty") { operationContext.ReportDiagnostic(Diagnostic.Create(LabelDescriptor, operationContext.Operation.Syntax.GetLocation())); } }, OperationKind.Labeled); context.RegisterOperationAction( (operationContext) => { IBranchOperation branch = (IBranchOperation)operationContext.Operation; if (branch.BranchKind == BranchKind.GoTo) { ILabelSymbol label = branch.Target; if (label.Name == "Wilma" || label.Name == "Betty") { operationContext.ReportDiagnostic(Diagnostic.Create(GotoDescriptor, branch.Syntax.GetLocation())); } } }, OperationKind.Branch); } } public class UnaryAndBinaryOperationsTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor OperatorAddMethodDescriptor = new DiagnosticDescriptor( "OperatorAddMethod", "Operator Add method found", "An operator Add method was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor OperatorMinusMethodDescriptor = new DiagnosticDescriptor( "OperatorMinusMethod", "Operator Minus method found", "An operator Minus method was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor DoubleMultiplyDescriptor = new DiagnosticDescriptor( "DoubleMultiply", "Double multiply found", "A double multiply was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor BooleanNotDescriptor = new DiagnosticDescriptor( "BooleanNot", "Boolean not found", "A boolean not was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(OperatorAddMethodDescriptor, OperatorMinusMethodDescriptor, DoubleMultiplyDescriptor, BooleanNotDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { IBinaryOperation binary = (IBinaryOperation)operationContext.Operation; if (binary.OperatorKind == BinaryOperatorKind.Add && binary.OperatorMethod != null && binary.OperatorMethod.Name.Contains("Addition")) { operationContext.ReportDiagnostic(Diagnostic.Create(OperatorAddMethodDescriptor, binary.Syntax.GetLocation())); } if (binary.OperatorKind == BinaryOperatorKind.Multiply && binary.Type.SpecialType == SpecialType.System_Double) { operationContext.ReportDiagnostic(Diagnostic.Create(DoubleMultiplyDescriptor, binary.Syntax.GetLocation())); } }, OperationKind.Binary); context.RegisterOperationAction( (operationContext) => { IUnaryOperation unary = (IUnaryOperation)operationContext.Operation; if (unary.OperatorKind == UnaryOperatorKind.Minus && unary.OperatorMethod != null && unary.OperatorMethod.Name.Contains("UnaryNegation")) { operationContext.ReportDiagnostic(Diagnostic.Create(OperatorMinusMethodDescriptor, unary.Syntax.GetLocation())); } if (unary.OperatorKind == UnaryOperatorKind.Not) { operationContext.ReportDiagnostic(Diagnostic.Create(BooleanNotDescriptor, unary.Syntax.GetLocation())); } if (unary.OperatorKind == UnaryOperatorKind.BitwiseNegation) { operationContext.ReportDiagnostic(Diagnostic.Create(BooleanNotDescriptor, unary.Syntax.GetLocation())); } }, OperationKind.Unary); } } public class BinaryOperatorVBTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor BinaryUserDefinedOperatorDescriptor = new DiagnosticDescriptor( "BinaryUserDefinedOperator", "Binary user defined operator found", "A Binary user defined operator {0} is found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(BinaryUserDefinedOperatorDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var binary = (IBinaryOperation)operationContext.Operation; if (binary.OperatorMethod != null) { operationContext.ReportDiagnostic( Diagnostic.Create(BinaryUserDefinedOperatorDescriptor, binary.Syntax.GetLocation(), binary.OperatorKind.ToString())); } }, OperationKind.Binary); } } public class OperatorPropertyPullerTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor BinaryOperatorDescriptor = new DiagnosticDescriptor( "BinaryOperator", "Binary operator found", "A Binary operator {0} was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor UnaryOperatorDescriptor = new DiagnosticDescriptor( "UnaryOperator", "Unary operator found", "A Unary operator {0} was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(BinaryOperatorDescriptor, UnaryOperatorDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var binary = (IBinaryOperation)operationContext.Operation; var left = binary.LeftOperand; var right = binary.RightOperand; if (!left.HasErrors(operationContext.Compilation, operationContext.CancellationToken) && !right.HasErrors(operationContext.Compilation, operationContext.CancellationToken) && binary.OperatorMethod == null) { if (left.Kind == OperationKind.LocalReference) { var leftLocal = ((ILocalReferenceOperation)left).Local; if (leftLocal.Name == "x") { if (right.Kind == OperationKind.Literal) { var rightValue = right.ConstantValue; if (rightValue.HasValue && rightValue.Value is int && (int)rightValue.Value == 10) { operationContext.ReportDiagnostic( Diagnostic.Create(BinaryOperatorDescriptor, binary.Syntax.GetLocation(), binary.OperatorKind.ToString())); } } } } } }, OperationKind.Binary); context.RegisterOperationAction( (operationContext) => { var unary = (IUnaryOperation)operationContext.Operation; var operand = unary.Operand; if (operand.Kind == OperationKind.LocalReference) { var operandLocal = ((ILocalReferenceOperation)operand).Local; if (operandLocal.Name == "x") { if (!operand.HasErrors(operationContext.Compilation, operationContext.CancellationToken) && unary.OperatorMethod == null) { operationContext.ReportDiagnostic( Diagnostic.Create(UnaryOperatorDescriptor, unary.Syntax.GetLocation(), unary.OperatorKind.ToString())); } } } }, OperationKind.Unary); } } public class NullOperationSyntaxTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; // We should not see this warning triggered by any code public static readonly DiagnosticDescriptor NullOperationSyntaxDescriptor = new DiagnosticDescriptor( "NullOperationSyntax", "null operation Syntax found", "An IOperation with Syntax property of value null is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); // since we don't expect to see the first diagnostic, we created this one to make sure // the test didn't pass because the analyzer crashed. public static readonly DiagnosticDescriptor ParamsArrayOperationDescriptor = new DiagnosticDescriptor( "ParamsArray", "Params array argument found", "A params array argument is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(NullOperationSyntaxDescriptor, ParamsArrayOperationDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var nullList = new List<IOperation>(); var paramsList = new List<IOperation>(); var collector = new Walker(nullList, paramsList); collector.Visit(operationContext.Operation); foreach (var nullSyntaxOperation in nullList) { operationContext.ReportDiagnostic( Diagnostic.Create(NullOperationSyntaxDescriptor, null)); } foreach (var paramsarrayArgumentOperation in paramsList) { operationContext.ReportDiagnostic( Diagnostic.Create(ParamsArrayOperationDescriptor, paramsarrayArgumentOperation.Syntax.GetLocation())); } }, OperationKind.Invocation); } // this OperationWalker collect: // 1. all the operation with null Syntax property // 2. all the params array argument operations private sealed class Walker : OperationWalker { private readonly List<IOperation> _nullList; private readonly List<IOperation> _paramsList; public Walker(List<IOperation> nullList, List<IOperation> paramsList) { _nullList = nullList; _paramsList = paramsList; } public override void Visit(IOperation operation) { if (operation != null) { if (operation.Syntax == null) { _nullList.Add(operation); } if (operation.Kind == OperationKind.Argument) { if (((IArgumentOperation)operation).ArgumentKind == ArgumentKind.ParamArray) { _paramsList.Add(operation); } } } base.Visit(operation); } } } public class InvalidOperatorExpressionTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor InvalidBinaryDescriptor = new DiagnosticDescriptor( "InvalidBinary", "Invalid binary expression operation with BinaryOperationKind.Invalid", "An Invalid binary expression operation with BinaryOperationKind.Invalid is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor InvalidUnaryDescriptor = new DiagnosticDescriptor( "InvalidUnary", "Invalid unary expression operation with UnaryOperationKind.Invalid", "An Invalid unary expression operation with UnaryOperationKind.Invalid is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor InvalidIncrementDescriptor = new DiagnosticDescriptor( "InvalidIncrement", "Invalid increment expression operation with ICompoundAssignmentExpression.BinaryOperationKind == BinaryOperationKind.Invalid", "An Invalid increment expression operation with ICompoundAssignmentExpression.BinaryOperationKind == BinaryOperationKind.Invalid is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(InvalidBinaryDescriptor, InvalidUnaryDescriptor, InvalidIncrementDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var operation = operationContext.Operation; if (operation.Kind == OperationKind.Binary) { var binary = (IBinaryOperation)operation; if (binary.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidBinaryDescriptor, binary.Syntax.GetLocation())); } } else if (operation.Kind == OperationKind.Unary) { var unary = (IUnaryOperation)operation; if (unary.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidUnaryDescriptor, unary.Syntax.GetLocation())); } } else if (operation.Kind == OperationKind.Increment) { var inc = (IIncrementOrDecrementOperation)operation; if (inc.HasErrors(operationContext.Compilation)) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidIncrementDescriptor, inc.Syntax.GetLocation())); } } }, OperationKind.Binary, OperationKind.Unary, OperationKind.Increment); } } public class ConditionalAccessOperationTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor ConditionalAccessOperationDescriptor = new DiagnosticDescriptor( "ConditionalAccessOperation", "Conditional access operation found", "Conditional access operation was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor ConditionalAccessInstanceOperationDescriptor = new DiagnosticDescriptor( "ConditionalAccessInstanceOperation", "Conditional access instance operation found", "Conditional access instance operation was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(ConditionalAccessOperationDescriptor, ConditionalAccessInstanceOperationDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { IConditionalAccessOperation conditionalAccess = (IConditionalAccessOperation)operationContext.Operation; if (conditionalAccess.WhenNotNull != null && conditionalAccess.Operation != null) { operationContext.ReportDiagnostic(Diagnostic.Create(ConditionalAccessOperationDescriptor, conditionalAccess.Syntax.GetLocation())); } }, OperationKind.ConditionalAccess); context.RegisterOperationAction( (operationContext) => { IConditionalAccessInstanceOperation conditionalAccessInstance = (IConditionalAccessInstanceOperation)operationContext.Operation; operationContext.ReportDiagnostic(Diagnostic.Create(ConditionalAccessInstanceOperationDescriptor, conditionalAccessInstance.Syntax.GetLocation())); }, OperationKind.ConditionalAccessInstance); // https://github.com/dotnet/roslyn/issues/21294 //context.RegisterOperationAction( // (operationContext) => // { // IPlaceholderExpression placeholder = (IPlaceholderExpression)operationContext.Operation; // operationContext.ReportDiagnostic(Diagnostic.Create(ConditionalAccessInstanceOperationDescriptor, placeholder.Syntax.GetLocation())); // }, // OperationKind.PlaceholderExpression); } } public class ConversionExpressionCSharpTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor InvalidConversionExpressionDescriptor = new DiagnosticDescriptor( "InvalidConversionExpression", "Invalid conversion expression", "Invalid conversion expression.", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(InvalidConversionExpressionDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var conversion = (IConversionOperation)operationContext.Operation; if (conversion.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidConversionExpressionDescriptor, conversion.Syntax.GetLocation())); } }, OperationKind.Conversion); } } public class ForLoopConditionCrashVBTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor ForLoopConditionCrashDescriptor = new DiagnosticDescriptor( "ForLoopConditionCrash", "Ensure ForLoopCondition property doesn't crash", "Ensure ForLoopCondition property doesn't crash", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(ForLoopConditionCrashDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { ILoopOperation loop = (ILoopOperation)operationContext.Operation; if (loop.LoopKind == LoopKind.ForTo) { var forLoop = (IForToLoopOperation)loop; var forCondition = forLoop.LimitValue; if (forCondition.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { // Generate a warning to prove we didn't crash operationContext.ReportDiagnostic(Diagnostic.Create(ForLoopConditionCrashDescriptor, forLoop.LimitValue.Syntax.GetLocation())); } } }, OperationKind.Loop); } } public class TrueFalseUnaryOperationTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor UnaryTrueDescriptor = new DiagnosticDescriptor( "UnaryTrue", "An unary True operation is found", "A unary True operation is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor UnaryFalseDescriptor = new DiagnosticDescriptor( "UnaryFalse", "An unary False operation is found", "A unary False operation is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(UnaryTrueDescriptor, UnaryFalseDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var unary = (IUnaryOperation)operationContext.Operation; if (unary.OperatorKind == UnaryOperatorKind.True) { operationContext.ReportDiagnostic(Diagnostic.Create(UnaryTrueDescriptor, unary.Syntax.GetLocation())); } else if (unary.OperatorKind == UnaryOperatorKind.False) { operationContext.ReportDiagnostic(Diagnostic.Create(UnaryFalseDescriptor, unary.Syntax.GetLocation())); } }, OperationKind.Unary); } } public class AssignmentOperationSyntaxTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor AssignmentOperationDescriptor = new DiagnosticDescriptor( "AssignmentOperation", "An assignment operation is found", "An assignment operation is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor AssignmentSyntaxDescriptor = new DiagnosticDescriptor( "AssignmentSyntax", "An assignment syntax is found", "An assignment syntax is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(AssignmentOperationDescriptor, AssignmentSyntaxDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic(Diagnostic.Create(AssignmentOperationDescriptor, operationContext.Operation.Syntax.GetLocation())); }, OperationKind.SimpleAssignment); context.RegisterSyntaxNodeAction( (syntaxContext) => { syntaxContext.ReportDiagnostic(Diagnostic.Create(AssignmentSyntaxDescriptor, syntaxContext.Node.GetLocation())); }, CSharp.SyntaxKind.SimpleAssignmentExpression); } } public class LiteralTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor LiteralDescriptor = new DiagnosticDescriptor( "Literal", "A literal is found", "A literal of value {0} is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(LiteralDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var literal = (ILiteralOperation)operationContext.Operation; operationContext.ReportDiagnostic(Diagnostic.Create(LiteralDescriptor, literal.Syntax.GetLocation(), literal.Syntax.ToString())); }, OperationKind.Literal); } } // This analyzer is to test operation action registration method in AnalysisContext public class AnalysisContextAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor OperationActionDescriptor = new DiagnosticDescriptor( "AnalysisContext", "An operation related action is invoked", "An {0} action is invoked in {1} context.", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(OperationActionDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic( Diagnostic.Create(OperationActionDescriptor, operationContext.Operation.Syntax.GetLocation(), "Operation", "Analysis")); }, OperationKind.Literal); } } // This analyzer is to test operation action registration method in CompilationStartAnalysisContext public class CompilationStartAnalysisContextAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor OperationActionDescriptor = new DiagnosticDescriptor( "CompilationStartAnalysisContext", "An operation related action is invoked", "An {0} action is invoked in {1} context.", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(OperationActionDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction( (compilationStartContext) => { compilationStartContext.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic( Diagnostic.Create(OperationActionDescriptor, operationContext.Operation.Syntax.GetLocation(), "Operation", "CompilationStart within Analysis")); }, OperationKind.Literal); }); } } // This analyzer is to test GetOperation method in SemanticModel public class SemanticModelAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor GetOperationDescriptor = new DiagnosticDescriptor( "GetOperation", "An IOperation is returned by SemanticModel", "An IOperation is returned by SemanticModel.", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(GetOperationDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction( (syntaxContext) => { var node = syntaxContext.Node; var model = syntaxContext.SemanticModel; if (model.GetOperation(node) != null) { syntaxContext.ReportDiagnostic(Diagnostic.Create(GetOperationDescriptor, node.GetLocation())); } }, Microsoft.CodeAnalysis.CSharp.SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction( (syntaxContext) => { var node = syntaxContext.Node; var model = syntaxContext.SemanticModel; if (model.GetOperation(node) != null) { syntaxContext.ReportDiagnostic(Diagnostic.Create(GetOperationDescriptor, node.GetLocation())); } }, Microsoft.CodeAnalysis.VisualBasic.SyntaxKind.NumericLiteralExpression); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { // These analyzers are not intended for any actual use. They exist solely to test IOperation support. /// <summary>Analyzer used to test for bad statements and expressions.</summary> public class BadStuffTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor InvalidExpressionDescriptor = new DiagnosticDescriptor( "InvalidExpression", "Invalid Expression", "Invalid expression found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor InvalidStatementDescriptor = new DiagnosticDescriptor( "InvalidStatement", "Invalid Statement", "Invalid statement found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor IsInvalidDescriptor = new DiagnosticDescriptor( "IsInvalid", "Is Invalid", "Operation found that is invalid.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(InvalidExpressionDescriptor, InvalidStatementDescriptor, IsInvalidDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var invalidOperation = (IInvalidOperation)operationContext.Operation; if (invalidOperation.Type == null) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidStatementDescriptor, operationContext.Operation.Syntax.GetLocation())); } else { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidExpressionDescriptor, operationContext.Operation.Syntax.GetLocation())); } }, OperationKind.Invalid); context.RegisterOperationAction( (operationContext) => { if (operationContext.Operation.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { operationContext.ReportDiagnostic(Diagnostic.Create(IsInvalidDescriptor, operationContext.Operation.Syntax.GetLocation())); } }, OperationKind.Invocation, OperationKind.Invalid); } } /// <summary>Analyzer used to test for operations within symbols of certain names.</summary> public class OwningSymbolTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor ExpressionDescriptor = new DiagnosticDescriptor( "Expression", "Expression", "Expression found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(ExpressionDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction( (operationBlockContext) => { if (operationBlockContext.Compilation.Language != "Stumble") { operationBlockContext.RegisterOperationAction( (operationContext) => { if (operationContext.ContainingSymbol.Name.StartsWith("Funky") && operationContext.Compilation.Language != "Mumble") { operationContext.ReportDiagnostic(Diagnostic.Create(ExpressionDescriptor, operationContext.Operation.Syntax.GetLocation())); } }, OperationKind.LocalReference, OperationKind.Literal); } }); } } /// <summary>Analyzer used to test for loop IOperations.</summary> public class BigForTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Reliability".</summary> private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor BigForDescriptor = new DiagnosticDescriptor( "BigForRule", "Big For Loop", "For loop iterates more than one million times", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(BigForDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction(AnalyzeOperation, OperationKind.Loop); } private void AnalyzeOperation(OperationAnalysisContext operationContext) { ILoopOperation loop = (ILoopOperation)operationContext.Operation; if (loop.LoopKind == LoopKind.For) { IForLoopOperation forLoop = (IForLoopOperation)loop; IOperation forCondition = forLoop.Condition; if (forCondition.Kind == OperationKind.Binary) { IBinaryOperation condition = (IBinaryOperation)forCondition; IOperation conditionLeft = condition.LeftOperand; IOperation conditionRight = condition.RightOperand; if (conditionRight.ConstantValue.HasValue && conditionRight.Type.SpecialType == SpecialType.System_Int32 && conditionLeft.Kind == OperationKind.LocalReference) { // Test is known to be a comparison of a local against a constant. int testValue = (int)conditionRight.ConstantValue.Value; ILocalSymbol testVariable = ((ILocalReferenceOperation)conditionLeft).Local; if (forLoop.Before.Length == 1) { IOperation setup = forLoop.Before[0]; if (setup.Kind == OperationKind.ExpressionStatement && ((IExpressionStatementOperation)setup).Operation.Kind == OperationKind.SimpleAssignment) { ISimpleAssignmentOperation setupAssignment = (ISimpleAssignmentOperation)((IExpressionStatementOperation)setup).Operation; if (setupAssignment.Target.Kind == OperationKind.LocalReference && ((ILocalReferenceOperation)setupAssignment.Target).Local == testVariable && setupAssignment.Value.ConstantValue.HasValue && setupAssignment.Value.Type.SpecialType == SpecialType.System_Int32) { // Setup is known to be an assignment of a constant to the local used in the test. int initialValue = (int)setupAssignment.Value.ConstantValue.Value; if (forLoop.AtLoopBottom.Length == 1) { IOperation advance = forLoop.AtLoopBottom[0]; if (advance.Kind == OperationKind.ExpressionStatement) { IOperation advanceExpression = ((IExpressionStatementOperation)advance).Operation; Optional<object> advanceIncrementOpt; BinaryOperatorKind? advanceOperationCode; GetOperationKindAndValue(testVariable, advanceExpression, out advanceOperationCode, out advanceIncrementOpt); if (advanceIncrementOpt.HasValue && advanceOperationCode.HasValue) { var incrementValue = (int)advanceIncrementOpt.Value; if (advanceOperationCode.Value == BinaryOperatorKind.Subtract) { advanceOperationCode = BinaryOperatorKind.Add; incrementValue = -incrementValue; } if (advanceOperationCode.Value == BinaryOperatorKind.Add && incrementValue != 0 && (condition.OperatorKind == BinaryOperatorKind.LessThan || condition.OperatorKind == BinaryOperatorKind.LessThanOrEqual || condition.OperatorKind == BinaryOperatorKind.NotEquals || condition.OperatorKind == BinaryOperatorKind.GreaterThan || condition.OperatorKind == BinaryOperatorKind.GreaterThanOrEqual)) { int iterationCount = (testValue - initialValue) / incrementValue; if (iterationCount >= 1000000) { Report(operationContext, forLoop.Syntax, BigForDescriptor); } } } } } } } } } } } } private void GetOperationKindAndValue( ILocalSymbol testVariable, IOperation advanceExpression, out BinaryOperatorKind? advanceOperationCode, out Optional<object> advanceIncrementOpt) { advanceIncrementOpt = null; advanceOperationCode = null; if (advanceExpression.Kind == OperationKind.SimpleAssignment) { ISimpleAssignmentOperation advanceAssignment = (ISimpleAssignmentOperation)advanceExpression; if (advanceAssignment.Target.Kind == OperationKind.LocalReference && ((ILocalReferenceOperation)advanceAssignment.Target).Local == testVariable && advanceAssignment.Value.Kind == OperationKind.Binary && advanceAssignment.Value.Type.SpecialType == SpecialType.System_Int32) { // Advance is known to be an assignment of a binary operation to the local used in the test. IBinaryOperation advanceOperation = (IBinaryOperation)advanceAssignment.Value; if (advanceOperation.OperatorMethod == null && advanceOperation.LeftOperand.Kind == OperationKind.LocalReference && ((ILocalReferenceOperation)advanceOperation.LeftOperand).Local == testVariable && advanceOperation.RightOperand.ConstantValue.HasValue && advanceOperation.RightOperand.Type.SpecialType == SpecialType.System_Int32) { // Advance binary operation is known to involve a reference to the local used in the test and a constant. advanceIncrementOpt = advanceOperation.RightOperand.ConstantValue; advanceOperationCode = advanceOperation.OperatorKind; } } } else if (advanceExpression.Kind == OperationKind.CompoundAssignment) { ICompoundAssignmentOperation advanceAssignment = (ICompoundAssignmentOperation)advanceExpression; if (advanceAssignment.Target.Kind == OperationKind.LocalReference && ((ILocalReferenceOperation)advanceAssignment.Target).Local == testVariable && advanceAssignment.Value.ConstantValue.HasValue && advanceAssignment.Value.Type.SpecialType == SpecialType.System_Int32) { // Advance binary operation is known to involve a reference to the local used in the test and a constant. advanceIncrementOpt = advanceAssignment.Value.ConstantValue; advanceOperationCode = advanceAssignment.OperatorKind; } } else if (advanceExpression.Kind == OperationKind.Increment) { IIncrementOrDecrementOperation advanceAssignment = (IIncrementOrDecrementOperation)advanceExpression; if (advanceAssignment.Target.Kind == OperationKind.LocalReference && ((ILocalReferenceOperation)advanceAssignment.Target).Local == testVariable) { // Advance binary operation is known to involve a reference to the local used in the test and a constant. advanceIncrementOpt = new Optional<object>(1); advanceOperationCode = BinaryOperatorKind.Add; } } } private static int Abs(int value) { return value < 0 ? -value : value; } private void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test switch IOperations.</summary> public class SwitchTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Reliability".</summary> private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor SparseSwitchDescriptor = new DiagnosticDescriptor( "SparseSwitchRule", "Sparse switch", "Switch has less than one percent density", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor NoDefaultSwitchDescriptor = new DiagnosticDescriptor( "NoDefaultSwitchRule", "No default switch", "Switch has no default case", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor OnlyDefaultSwitchDescriptor = new DiagnosticDescriptor( "OnlyDefaultSwitchRule", "Only default switch", "Switch only has a default case", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(SparseSwitchDescriptor, NoDefaultSwitchDescriptor, OnlyDefaultSwitchDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { ISwitchOperation switchOperation = (ISwitchOperation)operationContext.Operation; long minCaseValue = long.MaxValue; long maxCaseValue = long.MinValue; long caseValueCount = 0; bool hasDefault = false; bool hasNonDefault = false; foreach (ISwitchCaseOperation switchCase in switchOperation.Cases) { foreach (ICaseClauseOperation clause in switchCase.Clauses) { switch (clause.CaseKind) { case CaseKind.SingleValue: { hasNonDefault = true; ISingleValueCaseClauseOperation singleValueClause = (ISingleValueCaseClauseOperation)clause; IOperation singleValueExpression = singleValueClause.Value; if (singleValueExpression != null && singleValueExpression.ConstantValue.HasValue && singleValueExpression.Type.SpecialType == SpecialType.System_Int32) { int singleValue = (int)singleValueExpression.ConstantValue.Value; caseValueCount += IncludeClause(singleValue, singleValue, ref minCaseValue, ref maxCaseValue); } else { return; } break; } case CaseKind.Range: { hasNonDefault = true; IRangeCaseClauseOperation rangeClause = (IRangeCaseClauseOperation)clause; IOperation rangeMinExpression = rangeClause.MinimumValue; IOperation rangeMaxExpression = rangeClause.MaximumValue; if (rangeMinExpression != null && rangeMinExpression.ConstantValue.HasValue && rangeMinExpression.Type.SpecialType == SpecialType.System_Int32 && rangeMaxExpression != null && rangeMaxExpression.ConstantValue.HasValue && rangeMaxExpression.Type.SpecialType == SpecialType.System_Int32) { int rangeMinValue = (int)rangeMinExpression.ConstantValue.Value; int rangeMaxValue = (int)rangeMaxExpression.ConstantValue.Value; caseValueCount += IncludeClause(rangeMinValue, rangeMaxValue, ref minCaseValue, ref maxCaseValue); } else { return; } break; } case CaseKind.Relational: { hasNonDefault = true; IRelationalCaseClauseOperation relationalClause = (IRelationalCaseClauseOperation)clause; IOperation relationalValueExpression = relationalClause.Value; if (relationalValueExpression != null && relationalValueExpression.ConstantValue.HasValue && relationalValueExpression.Type.SpecialType == SpecialType.System_Int32) { int rangeMinValue = int.MaxValue; int rangeMaxValue = int.MinValue; int relationalValue = (int)relationalValueExpression.ConstantValue.Value; switch (relationalClause.Relation) { case BinaryOperatorKind.Equals: rangeMinValue = relationalValue; rangeMaxValue = relationalValue; break; case BinaryOperatorKind.NotEquals: return; case BinaryOperatorKind.LessThan: rangeMinValue = int.MinValue; rangeMaxValue = relationalValue - 1; break; case BinaryOperatorKind.LessThanOrEqual: rangeMinValue = int.MinValue; rangeMaxValue = relationalValue; break; case BinaryOperatorKind.GreaterThanOrEqual: rangeMinValue = relationalValue; rangeMaxValue = int.MaxValue; break; case BinaryOperatorKind.GreaterThan: rangeMinValue = relationalValue + 1; rangeMaxValue = int.MaxValue; break; } caseValueCount += IncludeClause(rangeMinValue, rangeMaxValue, ref minCaseValue, ref maxCaseValue); } else { return; } break; } case CaseKind.Default: { hasDefault = true; break; } } } } long span = maxCaseValue - minCaseValue + 1; if (caseValueCount == 0 && !hasDefault || caseValueCount != 0 && span / caseValueCount > 100) { Report(operationContext, switchOperation.Value.Syntax, SparseSwitchDescriptor); } if (!hasDefault) { Report(operationContext, switchOperation.Value.Syntax, NoDefaultSwitchDescriptor); } if (hasDefault && !hasNonDefault) { Report(operationContext, switchOperation.Value.Syntax, OnlyDefaultSwitchDescriptor); } }, OperationKind.Switch); } private static int IncludeClause(int clauseMinValue, int clauseMaxValue, ref long minCaseValue, ref long maxCaseValue) { if (clauseMinValue < minCaseValue) { minCaseValue = clauseMinValue; } if (clauseMaxValue > maxCaseValue) { maxCaseValue = clauseMaxValue; } return clauseMaxValue - clauseMinValue + 1; } private void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test invocation IOperations.</summary> public class InvocationTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Reliability".</summary> private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor BigParamArrayArgumentsDescriptor = new DiagnosticDescriptor( "BigParamarrayRule", "Big Paramarray", "Paramarray has more than 10 elements", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor OutOfNumericalOrderArgumentsDescriptor = new DiagnosticDescriptor( "OutOfOrderArgumentsRule", "Out of order arguments", "Argument values are not in increasing order", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor UseDefaultArgumentDescriptor = new DiagnosticDescriptor( "UseDefaultArgument", "Use default argument", "Invocation uses default argument {0}", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor InvalidArgumentDescriptor = new DiagnosticDescriptor( "InvalidArgument", "Invalid argument", "Invocation has invalid argument", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(BigParamArrayArgumentsDescriptor, OutOfNumericalOrderArgumentsDescriptor, UseDefaultArgumentDescriptor, InvalidArgumentDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { IInvocationOperation invocation = (IInvocationOperation)operationContext.Operation; long priorArgumentValue = long.MinValue; foreach (IArgumentOperation argument in invocation.Arguments) { if (argument.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidArgumentDescriptor, argument.Syntax.GetLocation())); return; } if (argument.ArgumentKind == ArgumentKind.DefaultValue) { operationContext.ReportDiagnostic(Diagnostic.Create(UseDefaultArgumentDescriptor, invocation.Syntax.GetLocation(), argument.Parameter.Name)); } TestAscendingArgument(operationContext, argument.Value, ref priorArgumentValue); if (argument.ArgumentKind == ArgumentKind.ParamArray) { if (argument.Value is IArrayCreationOperation arrayArgument) { var initializer = arrayArgument.Initializer; if (initializer != null) { if (initializer.ElementValues.Length > 10) { Report(operationContext, invocation.Syntax, BigParamArrayArgumentsDescriptor); } foreach (IOperation element in initializer.ElementValues) { TestAscendingArgument(operationContext, element, ref priorArgumentValue); } } } } } }, OperationKind.Invocation); } private static void TestAscendingArgument(OperationAnalysisContext operationContext, IOperation argument, ref long priorArgumentValue) { Optional<object> argumentValue = argument.ConstantValue; if (argumentValue.HasValue && argument.Type.SpecialType == SpecialType.System_Int32) { int integerArgument = (int)argumentValue.Value; if (integerArgument < priorArgumentValue) { Report(operationContext, argument.Syntax, OutOfNumericalOrderArgumentsDescriptor); } priorArgumentValue = integerArgument; } } private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test various contexts in which IOperations can occur.</summary> public class SeventeenTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Reliability".</summary> private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor SeventeenDescriptor = new DiagnosticDescriptor( "SeventeenRule", "Seventeen", "Seventeen is a recognized value", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(SeventeenDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { ILiteralOperation literal = (ILiteralOperation)operationContext.Operation; if (literal.Type.SpecialType == SpecialType.System_Int32 && literal.ConstantValue.HasValue && (int)literal.ConstantValue.Value == 17) { operationContext.ReportDiagnostic(Diagnostic.Create(SeventeenDescriptor, literal.Syntax.GetLocation())); } }, OperationKind.Literal); } } /// <summary>Analyzer used to test IArgument IOperations.</summary> public class NullArgumentTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Reliability".</summary> private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor NullArgumentsDescriptor = new DiagnosticDescriptor( "NullArgumentRule", "Null Argument", "Value of the argument is null", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(NullArgumentsDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var argument = (IArgumentOperation)operationContext.Operation; if (argument.Value.ConstantValue.HasValue && argument.Value.ConstantValue.Value == null) { Report(operationContext, argument.Syntax, NullArgumentsDescriptor); } }, OperationKind.Argument); } private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test IMemberInitializer IOperations.</summary> public class MemberInitializerTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Reliability".</summary> private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor DoNotUseFieldInitializerDescriptor = new DiagnosticDescriptor( "DoNotUseFieldInitializer", "Do Not Use Field Initializer", "a field initializer is used for object creation", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor DoNotUsePropertyInitializerDescriptor = new DiagnosticDescriptor( "DoNotUsePropertyInitializer", "Do Not Use Property Initializer", "A property initializer is used for object creation", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(DoNotUseFieldInitializerDescriptor, DoNotUsePropertyInitializerDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var initializer = operationContext.Operation; Report(operationContext, initializer.Syntax, initializer.Kind == OperationKind.FieldReference ? DoNotUseFieldInitializerDescriptor : DoNotUsePropertyInitializerDescriptor); }, OperationKind.FieldReference, OperationKind.PropertyReference); } private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test IAssignmentExpression IOperations.</summary> public class AssignmentTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Reliability".</summary> private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor DoNotUseMemberAssignmentDescriptor = new DiagnosticDescriptor( "DoNotUseMemberAssignment", "Do Not Use Member Assignment", "Do not assign values to object members", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(DoNotUseMemberAssignmentDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var assignment = (ISimpleAssignmentOperation)operationContext.Operation; var kind = assignment.Target.Kind; if (kind == OperationKind.FieldReference || kind == OperationKind.PropertyReference) { Report(operationContext, assignment.Syntax, DoNotUseMemberAssignmentDescriptor); } }, OperationKind.SimpleAssignment); } private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test IArrayInitializer IOperations.</summary> public class ArrayInitializerTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Maintainability".</summary> private const string Maintainability = nameof(Maintainability); public static readonly DiagnosticDescriptor DoNotUseLargeListOfArrayInitializersDescriptor = new DiagnosticDescriptor( "DoNotUseLongListToInitializeArray", "Do not use long list to initialize array", "a list of more than 5 elements is used for an array initialization", Maintainability, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(DoNotUseLargeListOfArrayInitializersDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var initializer = (IArrayInitializerOperation)operationContext.Operation; if (initializer.ElementValues.Length > 5) { Report(operationContext, initializer.Syntax, DoNotUseLargeListOfArrayInitializersDescriptor); } }, OperationKind.ArrayInitializer); } private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test IVariableDeclarationStatement IOperations.</summary> public class VariableDeclarationTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Maintainability".</summary> private const string Maintainability = nameof(Maintainability); public static readonly DiagnosticDescriptor TooManyLocalVarDeclarationsDescriptor = new DiagnosticDescriptor( "TooManyLocalVarDeclarations", "Too many local variable declarations", "A declaration statement shouldn't have more than 3 variable declarations", Maintainability, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor LocalVarInitializedDeclarationDescriptor = new DiagnosticDescriptor( "LocalVarInitializedDeclaration", "Local var initialized at declaration", "A local variable is initialized at declaration.", Maintainability, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(TooManyLocalVarDeclarationsDescriptor, LocalVarInitializedDeclarationDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var declarationStatement = (IVariableDeclarationGroupOperation)operationContext.Operation; if (declarationStatement.GetDeclaredVariables().Count() > 3) { Report(operationContext, declarationStatement.Syntax, TooManyLocalVarDeclarationsDescriptor); } foreach (var decl in declarationStatement.Declarations.SelectMany(multiDecl => multiDecl.Declarators)) { var initializer = decl.GetVariableInitializer(); if (initializer != null && !initializer.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { Report(operationContext, decl.Symbol.DeclaringSyntaxReferences.Single().GetSyntax(), LocalVarInitializedDeclarationDescriptor); } } }, OperationKind.VariableDeclarationGroup); } private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test ICase and ICaseClause.</summary> public class CaseTestAnalyzer : DiagnosticAnalyzer { /// <summary>Diagnostic category "Maintainability".</summary> private const string Maintainability = nameof(Maintainability); public static readonly DiagnosticDescriptor HasDefaultCaseDescriptor = new DiagnosticDescriptor( "HasDefaultCase", "Has Default Case", "A default case clause is encountered", Maintainability, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor MultipleCaseClausesDescriptor = new DiagnosticDescriptor( "MultipleCaseClauses", "Multiple Case Clauses", "A switch section has multiple case clauses", Maintainability, DiagnosticSeverity.Warning, isEnabledByDefault: true); /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary> public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(HasDefaultCaseDescriptor, MultipleCaseClausesDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { switch (operationContext.Operation.Kind) { case OperationKind.CaseClause: var caseClause = (ICaseClauseOperation)operationContext.Operation; if (caseClause.CaseKind == CaseKind.Default) { Report(operationContext, caseClause.Syntax, HasDefaultCaseDescriptor); } break; case OperationKind.SwitchCase: var switchSection = (ISwitchCaseOperation)operationContext.Operation; if (!switchSection.HasErrors(operationContext.Compilation, operationContext.CancellationToken) && switchSection.Clauses.Length > 1) { Report(operationContext, switchSection.Syntax, MultipleCaseClausesDescriptor); } break; } }, OperationKind.SwitchCase, OperationKind.CaseClause); } private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor) { context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation())); } } /// <summary>Analyzer used to test for explicit vs. implicit instance references.</summary> public class ExplicitVsImplicitInstanceAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor ImplicitInstanceDescriptor = new DiagnosticDescriptor( "ImplicitInstance", "Implicit Instance", "Implicit instance found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor ExplicitInstanceDescriptor = new DiagnosticDescriptor( "ExplicitInstance", "Explicit Instance", "Explicit instance found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(ImplicitInstanceDescriptor, ExplicitInstanceDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { IInstanceReferenceOperation instanceReference = (IInstanceReferenceOperation)operationContext.Operation; operationContext.ReportDiagnostic(Diagnostic.Create(instanceReference.IsImplicit ? ImplicitInstanceDescriptor : ExplicitInstanceDescriptor, instanceReference.Syntax.GetLocation())); }, OperationKind.InstanceReference); } } /// <summary>Analyzer used to test for member references.</summary> public class MemberReferenceAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor EventReferenceDescriptor = new DiagnosticDescriptor( "EventReference", "Event Reference", "Event reference found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor InvalidEventDescriptor = new DiagnosticDescriptor( "InvalidEvent", "Invalid Event", "A EventAssignmentExpression with invalid event found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor HandlerAddedDescriptor = new DiagnosticDescriptor( "HandlerAdded", "Handler Added", "Event handler added.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor HandlerRemovedDescriptor = new DiagnosticDescriptor( "HandlerRemoved", "Handler Removed", "Event handler removed.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor PropertyReferenceDescriptor = new DiagnosticDescriptor( "PropertyReference", "Property Reference", "Property reference found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor FieldReferenceDescriptor = new DiagnosticDescriptor( "FieldReference", "Field Reference", "Field reference found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor MethodBindingDescriptor = new DiagnosticDescriptor( "MethodBinding", "Method Binding", "Method binding found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(EventReferenceDescriptor, HandlerAddedDescriptor, HandlerRemovedDescriptor, PropertyReferenceDescriptor, FieldReferenceDescriptor, MethodBindingDescriptor, InvalidEventDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic(Diagnostic.Create(EventReferenceDescriptor, operationContext.Operation.Syntax.GetLocation())); }, OperationKind.EventReference); context.RegisterOperationAction( (operationContext) => { IEventAssignmentOperation eventAssignment = (IEventAssignmentOperation)operationContext.Operation; operationContext.ReportDiagnostic(Diagnostic.Create(eventAssignment.Adds ? HandlerAddedDescriptor : HandlerRemovedDescriptor, operationContext.Operation.Syntax.GetLocation())); if (eventAssignment.EventReference.Kind == OperationKind.Invalid || eventAssignment.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidEventDescriptor, eventAssignment.Syntax.GetLocation())); } }, OperationKind.EventAssignment); context.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic(Diagnostic.Create(PropertyReferenceDescriptor, operationContext.Operation.Syntax.GetLocation())); }, OperationKind.PropertyReference); context.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic(Diagnostic.Create(FieldReferenceDescriptor, operationContext.Operation.Syntax.GetLocation())); }, OperationKind.FieldReference); context.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic(Diagnostic.Create(MethodBindingDescriptor, operationContext.Operation.Syntax.GetLocation())); }, OperationKind.MethodReference); } } /// <summary>Analyzer used to test IOperation treatment of params array arguments.</summary> public class ParamsArrayTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor LongParamsDescriptor = new DiagnosticDescriptor( "LongParams", "Long Params", "Params array argument has more than 3 elements.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor InvalidConstructorDescriptor = new DiagnosticDescriptor( "InvalidConstructor", "Invalid Constructor", "Invalid Constructor.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(LongParamsDescriptor, InvalidConstructorDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { IInvocationOperation invocation = (IInvocationOperation)operationContext.Operation; foreach (IArgumentOperation argument in invocation.Arguments) { if (argument.Parameter.IsParams) { if (argument.Value is IArrayCreationOperation arrayValue) { Optional<object> dimensionSize = arrayValue.DimensionSizes[0].ConstantValue; if (dimensionSize.HasValue && IntegralValue(dimensionSize.Value) > 3) { operationContext.ReportDiagnostic(Diagnostic.Create(LongParamsDescriptor, argument.Value.Syntax.GetLocation())); } } } } }, OperationKind.Invocation); context.RegisterOperationAction( (operationContext) => { IObjectCreationOperation creation = (IObjectCreationOperation)operationContext.Operation; if (creation.Constructor == null) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidConstructorDescriptor, creation.Syntax.GetLocation())); } foreach (IArgumentOperation argument in creation.Arguments) { if (argument.Parameter.IsParams) { if (argument.Value is IArrayCreationOperation arrayValue) { Optional<object> dimensionSize = arrayValue.DimensionSizes[0].ConstantValue; if (dimensionSize.HasValue && IntegralValue(dimensionSize.Value) > 3) { operationContext.ReportDiagnostic(Diagnostic.Create(LongParamsDescriptor, argument.Value.Syntax.GetLocation())); } } } } }, OperationKind.ObjectCreation); } private static long IntegralValue(object value) { if (value is long v) { return v; } if (value is int i) { return i; } return 0; } } /// <summary>Analyzer used to test for initializer constructs for members and parameters.</summary> public class EqualsValueTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor EqualsValueDescriptor = new DiagnosticDescriptor( "EqualsValue", "Equals Value", "Equals value found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(EqualsValueDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { IFieldInitializerOperation equalsValue = (IFieldInitializerOperation)operationContext.Operation; if (equalsValue.InitializedFields[0].Name.StartsWith("F")) { operationContext.ReportDiagnostic(Diagnostic.Create(EqualsValueDescriptor, equalsValue.Syntax.GetLocation())); } }, OperationKind.FieldInitializer); context.RegisterOperationAction( (operationContext) => { IParameterInitializerOperation equalsValue = (IParameterInitializerOperation)operationContext.Operation; if (equalsValue.Parameter.Name.StartsWith("F")) { operationContext.ReportDiagnostic(Diagnostic.Create(EqualsValueDescriptor, equalsValue.Syntax.GetLocation())); } }, OperationKind.ParameterInitializer); } } /// <summary>Analyzer used to test None IOperations.</summary> public class NoneOperationTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; // We should not see this warning triggered by any code public static readonly DiagnosticDescriptor NoneOperationDescriptor = new DiagnosticDescriptor( "NoneOperation", "None operation found", "An IOperation of None kind is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(NoneOperationDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic(Diagnostic.Create(NoneOperationDescriptor, operationContext.Operation.Syntax.GetLocation())); }, // None kind is only supposed to be used internally and will not actually register actions. OperationKind.None); } } public class AddressOfTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor AddressOfDescriptor = new DiagnosticDescriptor( "AddressOfOperation", "AddressOf operation found", "An AddressOf operation found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor InvalidAddressOfReferenceDescriptor = new DiagnosticDescriptor( "InvalidAddressOfReference", "Invalid AddressOf reference found", "An invalid AddressOf reference found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(AddressOfDescriptor, InvalidAddressOfReferenceDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var addressOfOperation = (IAddressOfOperation)operationContext.Operation; operationContext.ReportDiagnostic(Diagnostic.Create(AddressOfDescriptor, addressOfOperation.Syntax.GetLocation())); if (addressOfOperation.Reference.Kind == OperationKind.Invalid && addressOfOperation.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidAddressOfReferenceDescriptor, addressOfOperation.Reference.Syntax.GetLocation())); } }, OperationKind.AddressOf); } } /// <summary>Analyzer used to test LambdaExpression IOperations.</summary> public class LambdaTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor LambdaExpressionDescriptor = new DiagnosticDescriptor( "LambdaExpression", "Lambda expression found", "A Lambda expression is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor TooManyStatementsInLambdaExpressionDescriptor = new DiagnosticDescriptor( "TooManyStatementsInLambdaExpression", "Too many statements in a Lambda expression", "More than 3 statements in a Lambda expression", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); // This warning should never be triggered. public static readonly DiagnosticDescriptor NoneOperationInLambdaExpressionDescriptor = new DiagnosticDescriptor( "NoneOperationInLambdaExpression", "None Operation found in Lambda expression", "None Operation is found Lambda expression", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(LambdaExpressionDescriptor, TooManyStatementsInLambdaExpressionDescriptor, NoneOperationInLambdaExpressionDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var lambdaExpression = (IAnonymousFunctionOperation)operationContext.Operation; operationContext.ReportDiagnostic(Diagnostic.Create(LambdaExpressionDescriptor, operationContext.Operation.Syntax.GetLocation())); var block = lambdaExpression.Body; // TODO: Can this possibly be null? Remove check if not. if (block == null) { return; } if (block.Operations.Length > 3) { operationContext.ReportDiagnostic(Diagnostic.Create(TooManyStatementsInLambdaExpressionDescriptor, operationContext.Operation.Syntax.GetLocation())); } bool flag = false; foreach (var statement in block.Operations) { if (statement.Kind == OperationKind.None) { flag = true; break; } } if (flag) { operationContext.ReportDiagnostic(Diagnostic.Create(NoneOperationInLambdaExpressionDescriptor, operationContext.Operation.Syntax.GetLocation())); } }, OperationKind.AnonymousFunction); } } public class StaticMemberTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor StaticMemberDescriptor = new DiagnosticDescriptor( "StaticMember", "Static member found", "A static member reference expression is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); // We should not see this warning triggered by any code public static readonly DiagnosticDescriptor StaticMemberWithInstanceDescriptor = new DiagnosticDescriptor( "StaticMemberWithInstance", "Static member with non null Instance found", "A static member reference with non null Instance is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(StaticMemberDescriptor, StaticMemberWithInstanceDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var operation = operationContext.Operation; ISymbol memberSymbol; IOperation receiver; switch (operation.Kind) { case OperationKind.FieldReference: memberSymbol = ((IFieldReferenceOperation)operation).Field; receiver = ((IFieldReferenceOperation)operation).Instance; break; case OperationKind.PropertyReference: memberSymbol = ((IPropertyReferenceOperation)operation).Property; receiver = ((IPropertyReferenceOperation)operation).Instance; break; case OperationKind.EventReference: memberSymbol = ((IEventReferenceOperation)operation).Event; receiver = ((IEventReferenceOperation)operation).Instance; break; case OperationKind.MethodReference: memberSymbol = ((IMethodReferenceOperation)operation).Method; receiver = ((IMethodReferenceOperation)operation).Instance; break; case OperationKind.Invocation: memberSymbol = ((IInvocationOperation)operation).TargetMethod; receiver = ((IInvocationOperation)operation).Instance; break; default: throw new ArgumentException(); } if (memberSymbol.IsStatic) { operationContext.ReportDiagnostic(Diagnostic.Create(StaticMemberDescriptor, operation.Syntax.GetLocation())); if (receiver != null) { operationContext.ReportDiagnostic(Diagnostic.Create(StaticMemberWithInstanceDescriptor, operation.Syntax.GetLocation())); } } }, OperationKind.FieldReference, OperationKind.PropertyReference, OperationKind.EventReference, OperationKind.MethodReference, OperationKind.Invocation); } } public class LabelOperationsTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor LabelDescriptor = new DiagnosticDescriptor( "Label", "Label found", "A label was was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor GotoDescriptor = new DiagnosticDescriptor( "Goto", "Goto found", "A goto was was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(LabelDescriptor, GotoDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { ILabelSymbol label = ((ILabeledOperation)operationContext.Operation).Label; if (label.Name == "Wilma" || label.Name == "Betty") { operationContext.ReportDiagnostic(Diagnostic.Create(LabelDescriptor, operationContext.Operation.Syntax.GetLocation())); } }, OperationKind.Labeled); context.RegisterOperationAction( (operationContext) => { IBranchOperation branch = (IBranchOperation)operationContext.Operation; if (branch.BranchKind == BranchKind.GoTo) { ILabelSymbol label = branch.Target; if (label.Name == "Wilma" || label.Name == "Betty") { operationContext.ReportDiagnostic(Diagnostic.Create(GotoDescriptor, branch.Syntax.GetLocation())); } } }, OperationKind.Branch); } } public class UnaryAndBinaryOperationsTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor OperatorAddMethodDescriptor = new DiagnosticDescriptor( "OperatorAddMethod", "Operator Add method found", "An operator Add method was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor OperatorMinusMethodDescriptor = new DiagnosticDescriptor( "OperatorMinusMethod", "Operator Minus method found", "An operator Minus method was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor DoubleMultiplyDescriptor = new DiagnosticDescriptor( "DoubleMultiply", "Double multiply found", "A double multiply was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor BooleanNotDescriptor = new DiagnosticDescriptor( "BooleanNot", "Boolean not found", "A boolean not was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(OperatorAddMethodDescriptor, OperatorMinusMethodDescriptor, DoubleMultiplyDescriptor, BooleanNotDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { IBinaryOperation binary = (IBinaryOperation)operationContext.Operation; if (binary.OperatorKind == BinaryOperatorKind.Add && binary.OperatorMethod != null && binary.OperatorMethod.Name.Contains("Addition")) { operationContext.ReportDiagnostic(Diagnostic.Create(OperatorAddMethodDescriptor, binary.Syntax.GetLocation())); } if (binary.OperatorKind == BinaryOperatorKind.Multiply && binary.Type.SpecialType == SpecialType.System_Double) { operationContext.ReportDiagnostic(Diagnostic.Create(DoubleMultiplyDescriptor, binary.Syntax.GetLocation())); } }, OperationKind.Binary); context.RegisterOperationAction( (operationContext) => { IUnaryOperation unary = (IUnaryOperation)operationContext.Operation; if (unary.OperatorKind == UnaryOperatorKind.Minus && unary.OperatorMethod != null && unary.OperatorMethod.Name.Contains("UnaryNegation")) { operationContext.ReportDiagnostic(Diagnostic.Create(OperatorMinusMethodDescriptor, unary.Syntax.GetLocation())); } if (unary.OperatorKind == UnaryOperatorKind.Not) { operationContext.ReportDiagnostic(Diagnostic.Create(BooleanNotDescriptor, unary.Syntax.GetLocation())); } if (unary.OperatorKind == UnaryOperatorKind.BitwiseNegation) { operationContext.ReportDiagnostic(Diagnostic.Create(BooleanNotDescriptor, unary.Syntax.GetLocation())); } }, OperationKind.Unary); } } public class BinaryOperatorVBTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor BinaryUserDefinedOperatorDescriptor = new DiagnosticDescriptor( "BinaryUserDefinedOperator", "Binary user defined operator found", "A Binary user defined operator {0} is found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(BinaryUserDefinedOperatorDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var binary = (IBinaryOperation)operationContext.Operation; if (binary.OperatorMethod != null) { operationContext.ReportDiagnostic( Diagnostic.Create(BinaryUserDefinedOperatorDescriptor, binary.Syntax.GetLocation(), binary.OperatorKind.ToString())); } }, OperationKind.Binary); } } public class OperatorPropertyPullerTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor BinaryOperatorDescriptor = new DiagnosticDescriptor( "BinaryOperator", "Binary operator found", "A Binary operator {0} was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor UnaryOperatorDescriptor = new DiagnosticDescriptor( "UnaryOperator", "Unary operator found", "A Unary operator {0} was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(BinaryOperatorDescriptor, UnaryOperatorDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var binary = (IBinaryOperation)operationContext.Operation; var left = binary.LeftOperand; var right = binary.RightOperand; if (!left.HasErrors(operationContext.Compilation, operationContext.CancellationToken) && !right.HasErrors(operationContext.Compilation, operationContext.CancellationToken) && binary.OperatorMethod == null) { if (left.Kind == OperationKind.LocalReference) { var leftLocal = ((ILocalReferenceOperation)left).Local; if (leftLocal.Name == "x") { if (right.Kind == OperationKind.Literal) { var rightValue = right.ConstantValue; if (rightValue.HasValue && rightValue.Value is int && (int)rightValue.Value == 10) { operationContext.ReportDiagnostic( Diagnostic.Create(BinaryOperatorDescriptor, binary.Syntax.GetLocation(), binary.OperatorKind.ToString())); } } } } } }, OperationKind.Binary); context.RegisterOperationAction( (operationContext) => { var unary = (IUnaryOperation)operationContext.Operation; var operand = unary.Operand; if (operand.Kind == OperationKind.LocalReference) { var operandLocal = ((ILocalReferenceOperation)operand).Local; if (operandLocal.Name == "x") { if (!operand.HasErrors(operationContext.Compilation, operationContext.CancellationToken) && unary.OperatorMethod == null) { operationContext.ReportDiagnostic( Diagnostic.Create(UnaryOperatorDescriptor, unary.Syntax.GetLocation(), unary.OperatorKind.ToString())); } } } }, OperationKind.Unary); } } public class NullOperationSyntaxTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; // We should not see this warning triggered by any code public static readonly DiagnosticDescriptor NullOperationSyntaxDescriptor = new DiagnosticDescriptor( "NullOperationSyntax", "null operation Syntax found", "An IOperation with Syntax property of value null is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); // since we don't expect to see the first diagnostic, we created this one to make sure // the test didn't pass because the analyzer crashed. public static readonly DiagnosticDescriptor ParamsArrayOperationDescriptor = new DiagnosticDescriptor( "ParamsArray", "Params array argument found", "A params array argument is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(NullOperationSyntaxDescriptor, ParamsArrayOperationDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var nullList = new List<IOperation>(); var paramsList = new List<IOperation>(); var collector = new Walker(nullList, paramsList); collector.Visit(operationContext.Operation); foreach (var nullSyntaxOperation in nullList) { operationContext.ReportDiagnostic( Diagnostic.Create(NullOperationSyntaxDescriptor, null)); } foreach (var paramsarrayArgumentOperation in paramsList) { operationContext.ReportDiagnostic( Diagnostic.Create(ParamsArrayOperationDescriptor, paramsarrayArgumentOperation.Syntax.GetLocation())); } }, OperationKind.Invocation); } // this OperationWalker collect: // 1. all the operation with null Syntax property // 2. all the params array argument operations private sealed class Walker : OperationWalker { private readonly List<IOperation> _nullList; private readonly List<IOperation> _paramsList; public Walker(List<IOperation> nullList, List<IOperation> paramsList) { _nullList = nullList; _paramsList = paramsList; } public override void Visit(IOperation operation) { if (operation != null) { if (operation.Syntax == null) { _nullList.Add(operation); } if (operation.Kind == OperationKind.Argument) { if (((IArgumentOperation)operation).ArgumentKind == ArgumentKind.ParamArray) { _paramsList.Add(operation); } } } base.Visit(operation); } } } public class InvalidOperatorExpressionTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor InvalidBinaryDescriptor = new DiagnosticDescriptor( "InvalidBinary", "Invalid binary expression operation with BinaryOperationKind.Invalid", "An Invalid binary expression operation with BinaryOperationKind.Invalid is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor InvalidUnaryDescriptor = new DiagnosticDescriptor( "InvalidUnary", "Invalid unary expression operation with UnaryOperationKind.Invalid", "An Invalid unary expression operation with UnaryOperationKind.Invalid is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor InvalidIncrementDescriptor = new DiagnosticDescriptor( "InvalidIncrement", "Invalid increment expression operation with ICompoundAssignmentExpression.BinaryOperationKind == BinaryOperationKind.Invalid", "An Invalid increment expression operation with ICompoundAssignmentExpression.BinaryOperationKind == BinaryOperationKind.Invalid is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(InvalidBinaryDescriptor, InvalidUnaryDescriptor, InvalidIncrementDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var operation = operationContext.Operation; if (operation.Kind == OperationKind.Binary) { var binary = (IBinaryOperation)operation; if (binary.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidBinaryDescriptor, binary.Syntax.GetLocation())); } } else if (operation.Kind == OperationKind.Unary) { var unary = (IUnaryOperation)operation; if (unary.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidUnaryDescriptor, unary.Syntax.GetLocation())); } } else if (operation.Kind == OperationKind.Increment) { var inc = (IIncrementOrDecrementOperation)operation; if (inc.HasErrors(operationContext.Compilation)) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidIncrementDescriptor, inc.Syntax.GetLocation())); } } }, OperationKind.Binary, OperationKind.Unary, OperationKind.Increment); } } public class ConditionalAccessOperationTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor ConditionalAccessOperationDescriptor = new DiagnosticDescriptor( "ConditionalAccessOperation", "Conditional access operation found", "Conditional access operation was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor ConditionalAccessInstanceOperationDescriptor = new DiagnosticDescriptor( "ConditionalAccessInstanceOperation", "Conditional access instance operation found", "Conditional access instance operation was found", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(ConditionalAccessOperationDescriptor, ConditionalAccessInstanceOperationDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { IConditionalAccessOperation conditionalAccess = (IConditionalAccessOperation)operationContext.Operation; if (conditionalAccess.WhenNotNull != null && conditionalAccess.Operation != null) { operationContext.ReportDiagnostic(Diagnostic.Create(ConditionalAccessOperationDescriptor, conditionalAccess.Syntax.GetLocation())); } }, OperationKind.ConditionalAccess); context.RegisterOperationAction( (operationContext) => { IConditionalAccessInstanceOperation conditionalAccessInstance = (IConditionalAccessInstanceOperation)operationContext.Operation; operationContext.ReportDiagnostic(Diagnostic.Create(ConditionalAccessInstanceOperationDescriptor, conditionalAccessInstance.Syntax.GetLocation())); }, OperationKind.ConditionalAccessInstance); // https://github.com/dotnet/roslyn/issues/21294 //context.RegisterOperationAction( // (operationContext) => // { // IPlaceholderExpression placeholder = (IPlaceholderExpression)operationContext.Operation; // operationContext.ReportDiagnostic(Diagnostic.Create(ConditionalAccessInstanceOperationDescriptor, placeholder.Syntax.GetLocation())); // }, // OperationKind.PlaceholderExpression); } } public class ConversionExpressionCSharpTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor InvalidConversionExpressionDescriptor = new DiagnosticDescriptor( "InvalidConversionExpression", "Invalid conversion expression", "Invalid conversion expression.", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(InvalidConversionExpressionDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var conversion = (IConversionOperation)operationContext.Operation; if (conversion.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { operationContext.ReportDiagnostic(Diagnostic.Create(InvalidConversionExpressionDescriptor, conversion.Syntax.GetLocation())); } }, OperationKind.Conversion); } } public class ForLoopConditionCrashVBTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor ForLoopConditionCrashDescriptor = new DiagnosticDescriptor( "ForLoopConditionCrash", "Ensure ForLoopCondition property doesn't crash", "Ensure ForLoopCondition property doesn't crash", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(ForLoopConditionCrashDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { ILoopOperation loop = (ILoopOperation)operationContext.Operation; if (loop.LoopKind == LoopKind.ForTo) { var forLoop = (IForToLoopOperation)loop; var forCondition = forLoop.LimitValue; if (forCondition.HasErrors(operationContext.Compilation, operationContext.CancellationToken)) { // Generate a warning to prove we didn't crash operationContext.ReportDiagnostic(Diagnostic.Create(ForLoopConditionCrashDescriptor, forLoop.LimitValue.Syntax.GetLocation())); } } }, OperationKind.Loop); } } public class TrueFalseUnaryOperationTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor UnaryTrueDescriptor = new DiagnosticDescriptor( "UnaryTrue", "An unary True operation is found", "A unary True operation is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor UnaryFalseDescriptor = new DiagnosticDescriptor( "UnaryFalse", "An unary False operation is found", "A unary False operation is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(UnaryTrueDescriptor, UnaryFalseDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var unary = (IUnaryOperation)operationContext.Operation; if (unary.OperatorKind == UnaryOperatorKind.True) { operationContext.ReportDiagnostic(Diagnostic.Create(UnaryTrueDescriptor, unary.Syntax.GetLocation())); } else if (unary.OperatorKind == UnaryOperatorKind.False) { operationContext.ReportDiagnostic(Diagnostic.Create(UnaryFalseDescriptor, unary.Syntax.GetLocation())); } }, OperationKind.Unary); } } public class AssignmentOperationSyntaxTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor AssignmentOperationDescriptor = new DiagnosticDescriptor( "AssignmentOperation", "An assignment operation is found", "An assignment operation is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor AssignmentSyntaxDescriptor = new DiagnosticDescriptor( "AssignmentSyntax", "An assignment syntax is found", "An assignment syntax is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(AssignmentOperationDescriptor, AssignmentSyntaxDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic(Diagnostic.Create(AssignmentOperationDescriptor, operationContext.Operation.Syntax.GetLocation())); }, OperationKind.SimpleAssignment); context.RegisterSyntaxNodeAction( (syntaxContext) => { syntaxContext.ReportDiagnostic(Diagnostic.Create(AssignmentSyntaxDescriptor, syntaxContext.Node.GetLocation())); }, CSharp.SyntaxKind.SimpleAssignmentExpression); } } public class LiteralTestAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor LiteralDescriptor = new DiagnosticDescriptor( "Literal", "A literal is found", "A literal of value {0} is found", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(LiteralDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { var literal = (ILiteralOperation)operationContext.Operation; operationContext.ReportDiagnostic(Diagnostic.Create(LiteralDescriptor, literal.Syntax.GetLocation(), literal.Syntax.ToString())); }, OperationKind.Literal); } } // This analyzer is to test operation action registration method in AnalysisContext public class AnalysisContextAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor OperationActionDescriptor = new DiagnosticDescriptor( "AnalysisContext", "An operation related action is invoked", "An {0} action is invoked in {1} context.", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(OperationActionDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic( Diagnostic.Create(OperationActionDescriptor, operationContext.Operation.Syntax.GetLocation(), "Operation", "Analysis")); }, OperationKind.Literal); } } // This analyzer is to test operation action registration method in CompilationStartAnalysisContext public class CompilationStartAnalysisContextAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor OperationActionDescriptor = new DiagnosticDescriptor( "CompilationStartAnalysisContext", "An operation related action is invoked", "An {0} action is invoked in {1} context.", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(OperationActionDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction( (compilationStartContext) => { compilationStartContext.RegisterOperationAction( (operationContext) => { operationContext.ReportDiagnostic( Diagnostic.Create(OperationActionDescriptor, operationContext.Operation.Syntax.GetLocation(), "Operation", "CompilationStart within Analysis")); }, OperationKind.Literal); }); } } // This analyzer is to test GetOperation method in SemanticModel public class SemanticModelAnalyzer : DiagnosticAnalyzer { private const string ReliabilityCategory = "Reliability"; public static readonly DiagnosticDescriptor GetOperationDescriptor = new DiagnosticDescriptor( "GetOperation", "An IOperation is returned by SemanticModel", "An IOperation is returned by SemanticModel.", ReliabilityCategory, DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(GetOperationDescriptor); public sealed override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction( (syntaxContext) => { var node = syntaxContext.Node; var model = syntaxContext.SemanticModel; if (model.GetOperation(node) != null) { syntaxContext.ReportDiagnostic(Diagnostic.Create(GetOperationDescriptor, node.GetLocation())); } }, Microsoft.CodeAnalysis.CSharp.SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction( (syntaxContext) => { var node = syntaxContext.Node; var model = syntaxContext.SemanticModel; if (model.GetOperation(node) != null) { syntaxContext.ReportDiagnostic(Diagnostic.Create(GetOperationDescriptor, node.GetLocation())); } }, Microsoft.CodeAnalysis.VisualBasic.SyntaxKind.NumericLiteralExpression); } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/TestUtilities/Structure/AbstractSyntaxNodeStructureProviderTests.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { public abstract class AbstractSyntaxNodeStructureProviderTests<TSyntaxNode> : AbstractSyntaxStructureProviderTests where TSyntaxNode : SyntaxNode { internal abstract AbstractSyntaxStructureProvider CreateProvider(); internal sealed override async Task<ImmutableArray<BlockSpan>> GetBlockSpansWorkerAsync(Document document, int position) { var root = await document.GetSyntaxRootAsync(CancellationToken.None); var token = root.FindToken(position, findInsideTrivia: true); var node = token.Parent.FirstAncestorOrSelf<TSyntaxNode>(); Assert.NotNull(node); // We prefer ancestor nodes if the position is on the edge of the located node's span. while (node.Parent is TSyntaxNode) { if ((position == node.SpanStart && position == node.Parent.SpanStart) || (position == node.Span.End && position == node.Parent.Span.End)) { node = (TSyntaxNode)node.Parent; } else { break; } } var outliner = CreateProvider(); using var actualRegions = TemporaryArray<BlockSpan>.Empty; var optionProvider = new BlockStructureOptionProvider( document.Project.Solution.Options, isMetadataAsSource: document.Project.Solution.Workspace.Kind == CodeAnalysis.WorkspaceKind.MetadataAsSource); outliner.CollectBlockSpans(node, ref actualRegions.AsRef(), optionProvider, CancellationToken.None); // TODO: Determine why we get null outlining spans. return actualRegions.ToImmutableAndClear(); } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { public abstract class AbstractSyntaxNodeStructureProviderTests<TSyntaxNode> : AbstractSyntaxStructureProviderTests where TSyntaxNode : SyntaxNode { internal abstract AbstractSyntaxStructureProvider CreateProvider(); internal sealed override async Task<ImmutableArray<BlockSpan>> GetBlockSpansWorkerAsync(Document document, int position) { var root = await document.GetSyntaxRootAsync(CancellationToken.None); var token = root.FindToken(position, findInsideTrivia: true); var node = token.Parent.FirstAncestorOrSelf<TSyntaxNode>(); Assert.NotNull(node); // We prefer ancestor nodes if the position is on the edge of the located node's span. while (node.Parent is TSyntaxNode) { if ((position == node.SpanStart && position == node.Parent.SpanStart) || (position == node.Span.End && position == node.Parent.Span.End)) { node = (TSyntaxNode)node.Parent; } else { break; } } var outliner = CreateProvider(); using var actualRegions = TemporaryArray<BlockSpan>.Empty; var optionProvider = new BlockStructureOptionProvider( document.Project.Solution.Options, isMetadataAsSource: document.Project.Solution.Workspace.Kind == CodeAnalysis.WorkspaceKind.MetadataAsSource); outliner.CollectBlockSpans(node, ref actualRegions.AsRef(), optionProvider, CancellationToken.None); // TODO: Determine why we get null outlining spans. return actualRegions.ToImmutableAndClear(); } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Impl/CodeModel/MethodXml/AbstractMethodXmlBuilder.AttributeInfo.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.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal abstract partial class AbstractMethodXmlBuilder { private struct AttributeInfo { public static readonly AttributeInfo Empty = new AttributeInfo(); public readonly string Name; public readonly string Value; public AttributeInfo(string name, string value) { this.Name = name; this.Value = value; } public bool IsEmpty { get { return this.Name == null && this.Value == 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. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal abstract partial class AbstractMethodXmlBuilder { private struct AttributeInfo { public static readonly AttributeInfo Empty = new AttributeInfo(); public readonly string Name; public readonly string Value; public AttributeInfo(string name, string value) { this.Name = name; this.Value = value; } public bool IsEmpty { get { return this.Name == null && this.Value == null; } } } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Symbols/Source/SourceNamespaceSymbol_Completion.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal partial class SourceNamespaceSymbol { internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = _state.NextIncompletePart; switch (incompletePart) { case CompletionPart.NameToMembersMap: { var tmp = GetNameToMembersMap(); } break; case CompletionPart.MembersCompleted: { SingleNamespaceDeclaration targetDeclarationWithImports = null; // ensure relevant imports are complete. foreach (var declaration in _mergedDeclaration.Declarations) { if (locationOpt == null || locationOpt.SourceTree == declaration.SyntaxReference.SyntaxTree) { if (declaration.HasGlobalUsings || declaration.HasUsings || declaration.HasExternAliases) { targetDeclarationWithImports = declaration; _aliasesAndUsings[declaration].Complete(this, declaration.SyntaxReference, cancellationToken); } } } if (IsGlobalNamespace && (locationOpt is null || targetDeclarationWithImports is object)) { GetMergedGlobalAliasesAndUsings(basesBeingResolved: null, cancellationToken).Complete(this, cancellationToken); } var members = this.GetMembers(); bool allCompleted = true; if (this.DeclaringCompilation.Options.ConcurrentBuild) { RoslynParallel.For( 0, members.Length, UICultureUtilities.WithCurrentUICulture<int>(i => ForceCompleteMemberByLocation(locationOpt, members[i], cancellationToken)), cancellationToken); foreach (var member in members) { if (!member.HasComplete(CompletionPart.All)) { allCompleted = false; break; } } } else { foreach (var member in members) { ForceCompleteMemberByLocation(locationOpt, member, cancellationToken); allCompleted = allCompleted && member.HasComplete(CompletionPart.All); } } if (allCompleted) { _state.NotePartComplete(CompletionPart.MembersCompleted); break; } else { // NOTE: we're going to kick out of the completion part loop after this, // so not making progress isn't a problem. goto done; } } case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols _state.NotePartComplete(CompletionPart.All & ~CompletionPart.NamespaceSymbolAll); break; } _state.SpinWaitComplete(incompletePart, cancellationToken); } done: // Don't return until we've seen all of the CompletionParts. This ensures all // diagnostics have been reported (not necessarily on this thread). CompletionPart allParts = (locationOpt == null) ? CompletionPart.NamespaceSymbolAll : CompletionPart.NamespaceSymbolAll & ~CompletionPart.MembersCompleted; _state.SpinWaitComplete(allParts, cancellationToken); } internal override bool HasComplete(CompletionPart part) { return _state.HasComplete(part); } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal partial class SourceNamespaceSymbol { internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = _state.NextIncompletePart; switch (incompletePart) { case CompletionPart.NameToMembersMap: { var tmp = GetNameToMembersMap(); } break; case CompletionPart.MembersCompleted: { SingleNamespaceDeclaration targetDeclarationWithImports = null; // ensure relevant imports are complete. foreach (var declaration in _mergedDeclaration.Declarations) { if (locationOpt == null || locationOpt.SourceTree == declaration.SyntaxReference.SyntaxTree) { if (declaration.HasGlobalUsings || declaration.HasUsings || declaration.HasExternAliases) { targetDeclarationWithImports = declaration; _aliasesAndUsings[declaration].Complete(this, declaration.SyntaxReference, cancellationToken); } } } if (IsGlobalNamespace && (locationOpt is null || targetDeclarationWithImports is object)) { GetMergedGlobalAliasesAndUsings(basesBeingResolved: null, cancellationToken).Complete(this, cancellationToken); } var members = this.GetMembers(); bool allCompleted = true; if (this.DeclaringCompilation.Options.ConcurrentBuild) { RoslynParallel.For( 0, members.Length, UICultureUtilities.WithCurrentUICulture<int>(i => ForceCompleteMemberByLocation(locationOpt, members[i], cancellationToken)), cancellationToken); foreach (var member in members) { if (!member.HasComplete(CompletionPart.All)) { allCompleted = false; break; } } } else { foreach (var member in members) { ForceCompleteMemberByLocation(locationOpt, member, cancellationToken); allCompleted = allCompleted && member.HasComplete(CompletionPart.All); } } if (allCompleted) { _state.NotePartComplete(CompletionPart.MembersCompleted); break; } else { // NOTE: we're going to kick out of the completion part loop after this, // so not making progress isn't a problem. goto done; } } case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols _state.NotePartComplete(CompletionPart.All & ~CompletionPart.NamespaceSymbolAll); break; } _state.SpinWaitComplete(incompletePart, cancellationToken); } done: // Don't return until we've seen all of the CompletionParts. This ensures all // diagnostics have been reported (not necessarily on this thread). CompletionPart allParts = (locationOpt == null) ? CompletionPart.NamespaceSymbolAll : CompletionPart.NamespaceSymbolAll & ~CompletionPart.MembersCompleted; _state.SpinWaitComplete(allParts, cancellationToken); } internal override bool HasComplete(CompletionPart part) { return _state.HasComplete(part); } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.Tagger.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 Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal partial class AbstractAsynchronousTaggerProvider<TTag> { /// <summary> /// <see cref="Tagger"/> is a thin wrapper we create around the single shared <see cref="TagSource"/>. /// Clients can request and dispose these at will. Once the last wrapper is disposed, the underlying /// <see cref="TagSource"/> will finally be disposed as well. /// </summary> private sealed partial class Tagger : ITagger<TTag>, IDisposable { private readonly TagSource _tagSource; public Tagger(TagSource tagSource) { _tagSource = tagSource; _tagSource.OnTaggerAdded(this); } public event EventHandler<SnapshotSpanEventArgs> TagsChanged { add => _tagSource.TagsChanged += value; remove => _tagSource.TagsChanged -= value; } public void Dispose() => _tagSource.OnTaggerDisposed(this); public IEnumerable<ITagSpan<TTag>> GetTags(NormalizedSnapshotSpanCollection requestedSpans) => _tagSource.GetTags(requestedSpans); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal partial class AbstractAsynchronousTaggerProvider<TTag> { /// <summary> /// <see cref="Tagger"/> is a thin wrapper we create around the single shared <see cref="TagSource"/>. /// Clients can request and dispose these at will. Once the last wrapper is disposed, the underlying /// <see cref="TagSource"/> will finally be disposed as well. /// </summary> private sealed partial class Tagger : ITagger<TTag>, IDisposable { private readonly TagSource _tagSource; public Tagger(TagSource tagSource) { _tagSource = tagSource; _tagSource.OnTaggerAdded(this); } public event EventHandler<SnapshotSpanEventArgs> TagsChanged { add => _tagSource.TagsChanged += value; remove => _tagSource.TagsChanged -= value; } public void Dispose() => _tagSource.OnTaggerDisposed(this); public IEnumerable<ITagSpan<TTag>> GetTags(NormalizedSnapshotSpanCollection requestedSpans) => _tagSource.GetTags(requestedSpans); } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/Common/AbstractProjectExtensionProvider`2.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.Immutable; using System.Reflection; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal abstract class AbstractProjectExtensionProvider<TExtension, TExportAttribute> where TExportAttribute : Attribute { private readonly AnalyzerReference _reference; private ImmutableDictionary<string, ImmutableArray<TExtension>> _extensionsPerLanguage; public AbstractProjectExtensionProvider(AnalyzerReference reference) { _reference = reference; _extensionsPerLanguage = ImmutableDictionary<string, ImmutableArray<TExtension>>.Empty; } protected abstract bool SupportsLanguage(TExportAttribute exportAttribute, string language); protected abstract bool TryGetExtensionsFromReference(AnalyzerReference reference, out ImmutableArray<TExtension> extensions); public ImmutableArray<TExtension> GetExtensions(string language) { return ImmutableInterlocked.GetOrAdd(ref _extensionsPerLanguage, language, (language, provider) => provider.CreateExtensions(language), this); } private ImmutableArray<TExtension> CreateExtensions(string language) { // check whether the analyzer reference knows how to return extensions directly. if (TryGetExtensionsFromReference(_reference, out var extensions)) { return extensions; } // otherwise, see whether we can pick it up from reference itself if (_reference is not AnalyzerFileReference analyzerFileReference) { return ImmutableArray<TExtension>.Empty; } using var _ = ArrayBuilder<TExtension>.GetInstance(out var builder); try { var analyzerAssembly = analyzerFileReference.GetAssembly(); var typeInfos = analyzerAssembly.DefinedTypes; foreach (var typeInfo in typeInfos) { if (typeInfo.IsSubclassOf(typeof(TExtension))) { try { var attribute = typeInfo.GetCustomAttribute<TExportAttribute>(); if (attribute is object && SupportsLanguage(attribute, language)) { builder.Add((TExtension)Activator.CreateInstance(typeInfo.AsType())); } } catch { } } } } catch { // REVIEW: is the below message right? // NOTE: We could report "unable to load analyzer" exception here but it should have been already reported by DiagnosticService. } return builder.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more 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.Immutable; using System.Reflection; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal abstract class AbstractProjectExtensionProvider<TExtension, TExportAttribute> where TExportAttribute : Attribute { private readonly AnalyzerReference _reference; private ImmutableDictionary<string, ImmutableArray<TExtension>> _extensionsPerLanguage; public AbstractProjectExtensionProvider(AnalyzerReference reference) { _reference = reference; _extensionsPerLanguage = ImmutableDictionary<string, ImmutableArray<TExtension>>.Empty; } protected abstract bool SupportsLanguage(TExportAttribute exportAttribute, string language); protected abstract bool TryGetExtensionsFromReference(AnalyzerReference reference, out ImmutableArray<TExtension> extensions); public ImmutableArray<TExtension> GetExtensions(string language) { return ImmutableInterlocked.GetOrAdd(ref _extensionsPerLanguage, language, (language, provider) => provider.CreateExtensions(language), this); } private ImmutableArray<TExtension> CreateExtensions(string language) { // check whether the analyzer reference knows how to return extensions directly. if (TryGetExtensionsFromReference(_reference, out var extensions)) { return extensions; } // otherwise, see whether we can pick it up from reference itself if (_reference is not AnalyzerFileReference analyzerFileReference) { return ImmutableArray<TExtension>.Empty; } using var _ = ArrayBuilder<TExtension>.GetInstance(out var builder); try { var analyzerAssembly = analyzerFileReference.GetAssembly(); var typeInfos = analyzerAssembly.DefinedTypes; foreach (var typeInfo in typeInfos) { if (typeInfo.IsSubclassOf(typeof(TExtension))) { try { var attribute = typeInfo.GetCustomAttribute<TExportAttribute>(); if (attribute is object && SupportsLanguage(attribute, language)) { builder.Add((TExtension)Activator.CreateInstance(typeInfo.AsType())); } } catch { } } } } catch { // REVIEW: is the below message right? // NOTE: We could report "unable to load analyzer" exception here but it should have been already reported by DiagnosticService. } return builder.ToImmutable(); } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Remote/Core/SolutionAssetStorage.Scope.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal partial class SolutionAssetStorage { internal readonly struct Scope : IDisposable { private readonly SolutionAssetStorage _storages; public readonly PinnedSolutionInfo SolutionInfo; public Scope(SolutionAssetStorage storages, PinnedSolutionInfo solutionInfo) { _storages = storages; SolutionInfo = solutionInfo; } public void Dispose() { Contract.ThrowIfFalse(_storages._solutionStates.TryRemove(SolutionInfo.ScopeId, out var entry)); entry.ReplicationContext.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal partial class SolutionAssetStorage { internal readonly struct Scope : IDisposable { private readonly SolutionAssetStorage _storages; public readonly PinnedSolutionInfo SolutionInfo; public Scope(SolutionAssetStorage storages, PinnedSolutionInfo solutionInfo) { _storages = storages; SolutionInfo = solutionInfo; } public void Dispose() { Contract.ThrowIfFalse(_storages._solutionStates.TryRemove(SolutionInfo.ScopeId, out var entry)); entry.ReplicationContext.Dispose(); } } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/CharsetModifierKeywordRecommenderTests.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.Declarations Public Class CharsetModifierKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AutoAfterDeclareTest() VerifyRecommendationsContain(<ClassDeclaration>Declare |</ClassDeclaration>, "Auto") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AnsiAfterDeclareTest() VerifyRecommendationsContain(<ClassDeclaration>Declare |</ClassDeclaration>, "Ansi") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub UnicodeAfterDeclareTest() VerifyRecommendationsContain(<ClassDeclaration>Declare |</ClassDeclaration>, "Unicode") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AutoNotAfterAnotherCharsetModifier1Test() VerifyRecommendationsMissing(<ClassDeclaration>Declare Ansi |</ClassDeclaration>, "Auto") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AutoNotAfterAnotherCharsetModifier2Test() VerifyRecommendationsMissing(<ClassDeclaration>Declare Auto |</ClassDeclaration>, "Auto") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AutoNotAfterAnotherCharsetModifier3Test() VerifyRecommendationsMissing(<ClassDeclaration>Declare Unicode |</ClassDeclaration>, "Auto") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterColonTest() VerifyRecommendationsMissing(<ClassDeclaration>Declare : |</ClassDeclaration>, "Unicode") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <ClassDeclaration>Declare |</ClassDeclaration>, "Unicode") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <ClassDeclaration>Declare _ |</ClassDeclaration>, "Unicode") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <ClassDeclaration>Declare _ ' Test |</ClassDeclaration>, "Unicode") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuationt() VerifyRecommendationsContain( <ClassDeclaration>Declare _ |</ClassDeclaration>, "Unicode") 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.Declarations Public Class CharsetModifierKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AutoAfterDeclareTest() VerifyRecommendationsContain(<ClassDeclaration>Declare |</ClassDeclaration>, "Auto") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AnsiAfterDeclareTest() VerifyRecommendationsContain(<ClassDeclaration>Declare |</ClassDeclaration>, "Ansi") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub UnicodeAfterDeclareTest() VerifyRecommendationsContain(<ClassDeclaration>Declare |</ClassDeclaration>, "Unicode") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AutoNotAfterAnotherCharsetModifier1Test() VerifyRecommendationsMissing(<ClassDeclaration>Declare Ansi |</ClassDeclaration>, "Auto") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AutoNotAfterAnotherCharsetModifier2Test() VerifyRecommendationsMissing(<ClassDeclaration>Declare Auto |</ClassDeclaration>, "Auto") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AutoNotAfterAnotherCharsetModifier3Test() VerifyRecommendationsMissing(<ClassDeclaration>Declare Unicode |</ClassDeclaration>, "Auto") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterColonTest() VerifyRecommendationsMissing(<ClassDeclaration>Declare : |</ClassDeclaration>, "Unicode") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <ClassDeclaration>Declare |</ClassDeclaration>, "Unicode") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <ClassDeclaration>Declare _ |</ClassDeclaration>, "Unicode") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <ClassDeclaration>Declare _ ' Test |</ClassDeclaration>, "Unicode") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuationt() VerifyRecommendationsContain( <ClassDeclaration>Declare _ |</ClassDeclaration>, "Unicode") End Sub End Class End Namespace
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.RemoveSuppressionCodeAction_Attribute.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.CodeFixes.Suppression { internal abstract partial class AbstractSuppressionCodeFixProvider : IConfigurationFixProvider { internal abstract partial class RemoveSuppressionCodeAction { /// <summary> /// Code action to remove suppress message attributes for remove suppression. /// </summary> private sealed class AttributeRemoveAction : RemoveSuppressionCodeAction { private readonly Project _project; private readonly AttributeData _attribute; public static AttributeRemoveAction Create( AttributeData attribute, Project project, Diagnostic diagnostic, AbstractSuppressionCodeFixProvider fixer) { return new AttributeRemoveAction(attribute, project, diagnostic, fixer); } private AttributeRemoveAction( AttributeData attribute, Project project, Diagnostic diagnostic, AbstractSuppressionCodeFixProvider fixer, bool forFixMultipleContext = false) : base(diagnostic, fixer, forFixMultipleContext) { _project = project; _attribute = attribute; } public override RemoveSuppressionCodeAction CloneForFixMultipleContext() => new AttributeRemoveAction(_attribute, _project, _diagnostic, Fixer, forFixMultipleContext: true); public override SyntaxTree SyntaxTreeToModify => _attribute.ApplicationSyntaxReference.SyntaxTree; public async Task<SyntaxNode> GetAttributeToRemoveAsync(CancellationToken cancellationToken) { var attributeNode = await _attribute.ApplicationSyntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); return Fixer.IsSingleAttributeInAttributeList(attributeNode) ? attributeNode.Parent : attributeNode; } protected override async Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken) { var attributeNode = await GetAttributeToRemoveAsync(cancellationToken).ConfigureAwait(false); var documentWithAttribute = _project.GetDocument(attributeNode.SyntaxTree); if (documentWithAttribute == null) { return _project.Solution; } var editor = await DocumentEditor.CreateAsync(documentWithAttribute, cancellationToken).ConfigureAwait(false); editor.RemoveNode(attributeNode); return editor.GetChangedDocument().Project.Solution; } } } } }
// Licensed to the .NET Foundation under one or more 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.CodeFixes.Suppression { internal abstract partial class AbstractSuppressionCodeFixProvider : IConfigurationFixProvider { internal abstract partial class RemoveSuppressionCodeAction { /// <summary> /// Code action to remove suppress message attributes for remove suppression. /// </summary> private sealed class AttributeRemoveAction : RemoveSuppressionCodeAction { private readonly Project _project; private readonly AttributeData _attribute; public static AttributeRemoveAction Create( AttributeData attribute, Project project, Diagnostic diagnostic, AbstractSuppressionCodeFixProvider fixer) { return new AttributeRemoveAction(attribute, project, diagnostic, fixer); } private AttributeRemoveAction( AttributeData attribute, Project project, Diagnostic diagnostic, AbstractSuppressionCodeFixProvider fixer, bool forFixMultipleContext = false) : base(diagnostic, fixer, forFixMultipleContext) { _project = project; _attribute = attribute; } public override RemoveSuppressionCodeAction CloneForFixMultipleContext() => new AttributeRemoveAction(_attribute, _project, _diagnostic, Fixer, forFixMultipleContext: true); public override SyntaxTree SyntaxTreeToModify => _attribute.ApplicationSyntaxReference.SyntaxTree; public async Task<SyntaxNode> GetAttributeToRemoveAsync(CancellationToken cancellationToken) { var attributeNode = await _attribute.ApplicationSyntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); return Fixer.IsSingleAttributeInAttributeList(attributeNode) ? attributeNode.Parent : attributeNode; } protected override async Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken) { var attributeNode = await GetAttributeToRemoveAsync(cancellationToken).ConfigureAwait(false); var documentWithAttribute = _project.GetDocument(attributeNode.SyntaxTree); if (documentWithAttribute == null) { return _project.Solution; } var editor = await DocumentEditor.CreateAsync(documentWithAttribute, cancellationToken).ConfigureAwait(false); editor.RemoveNode(attributeNode); return editor.GetChangedDocument().Project.Solution; } } } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Impl/Options/OptionLogger.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.Internal.Log; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal static class OptionLogger { private const string Name = nameof(Name); private const string Language = nameof(Language); private const string Change = nameof(Change); private const string All = nameof(All); public static void Log(OptionSet oldOptions, OptionSet newOptions) { foreach (var optionKey in newOptions.GetChangedOptions(oldOptions)) { var oldValue = oldOptions.GetOption(optionKey); var currentValue = newOptions.GetOption(optionKey); Logger.Log(FunctionId.Run_Environment_Options, Create(optionKey, oldValue, currentValue)); } } private static KeyValueLogMessage Create(OptionKey optionKey, object oldValue, object currentValue) { return KeyValueLogMessage.Create(m => { m[Name] = optionKey.Option.Name; m[Language] = optionKey.Language ?? All; m[Change] = CreateOptionValue(oldValue, currentValue); }); } private static string CreateOptionValue(object oldValue, object currentValue) { var oldString = GetOptionValue(oldValue); var newString = GetOptionValue(currentValue); return oldString + "->" + newString; } private static string GetOptionValue(object oldValue) => oldValue == null ? "[null]" : oldValue.ToString(); } }
// Licensed to the .NET Foundation under one or more 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.Internal.Log; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal static class OptionLogger { private const string Name = nameof(Name); private const string Language = nameof(Language); private const string Change = nameof(Change); private const string All = nameof(All); public static void Log(OptionSet oldOptions, OptionSet newOptions) { foreach (var optionKey in newOptions.GetChangedOptions(oldOptions)) { var oldValue = oldOptions.GetOption(optionKey); var currentValue = newOptions.GetOption(optionKey); Logger.Log(FunctionId.Run_Environment_Options, Create(optionKey, oldValue, currentValue)); } } private static KeyValueLogMessage Create(OptionKey optionKey, object oldValue, object currentValue) { return KeyValueLogMessage.Create(m => { m[Name] = optionKey.Option.Name; m[Language] = optionKey.Language ?? All; m[Change] = CreateOptionValue(oldValue, currentValue); }); } private static string CreateOptionValue(object oldValue, object currentValue) { var oldString = GetOptionValue(oldValue); var newString = GetOptionValue(currentValue); return oldString + "->" + newString; } private static string GetOptionValue(object oldValue) => oldValue == null ? "[null]" : oldValue.ToString(); } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/LanguageServer/Protocol/Handler/Commands/ProvidesCommandAttribute.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.Composition; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Commands { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] internal class ProvidesCommandAttribute : ProvidesMethodAttribute { public ProvidesCommandAttribute(string command) : base(AbstractExecuteWorkspaceCommandHandler.GetRequestNameForCommandName(command)) { } } }
// Licensed to the .NET Foundation under one or more 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.Composition; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Commands { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] internal class ProvidesCommandAttribute : ProvidesMethodAttribute { public ProvidesCommandAttribute(string command) : base(AbstractExecuteWorkspaceCommandHandler.GetRequestNameForCommandName(command)) { } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/LanguageServer/ProtocolUnitTests/Diagnostics/PullDiagnosticTests.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Test; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Diagnostics { public class PullDiagnosticTests : AbstractLanguageServerProtocolTests { #region Document Diagnostics [Fact] public async Task TestNoDocumentDiagnosticsForClosedFilesWithFSAOff() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results); } [Fact] public async Task TestDocumentDiagnosticsForOpenFilesWithFSAOff() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); } [Fact] public async Task TestNoDocumentDiagnosticsForOpenFilesWithFSAOffIfInPushMode() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects, pullDiagnostics: false); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results.Single().Diagnostics); } [Fact] public async Task TestNoDocumentDiagnosticsForOpenFilesIfDefaultAndFeatureFlagOff() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects, DiagnosticMode.Default); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); // Ensure we get no diagnostics when feature flag is off. var testExperimentationService = (TestExperimentationService)testLspServer.TestWorkspace.Services.GetRequiredService<IExperimentationService>(); testExperimentationService.SetExperimentOption(WellKnownExperimentNames.LspPullDiagnosticsFeatureFlag, false); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results.Single().Diagnostics); } [Fact] public async Task TestDocumentDiagnosticsForOpenFilesIfDefaultAndFeatureFlagOn() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects, DiagnosticMode.Default); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var testExperimentationService = (TestExperimentationService)testLspServer.TestWorkspace.Services.GetRequiredService<IExperimentationService>(); testExperimentationService.SetExperimentOption(WellKnownExperimentNames.LspPullDiagnosticsFeatureFlag, true); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); } [Fact] public async Task TestDocumentDiagnosticsForRemovedDocument() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); var workspace = testLspServer.TestWorkspace; // Calling GetTextBuffer will effectively open the file. workspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); // Get the diagnostics for the solution containing the doc. var solution = document.Project.Solution; await OpenDocumentAsync(testLspServer, document); await WaitForDiagnosticsAsync(workspace); var results = await testLspServer.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( MSLSPMethods.DocumentPullDiagnosticName, CreateDocumentDiagnosticParams(document.GetURI()), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); // Now remove the doc. workspace.OnDocumentRemoved(workspace.Documents.Single().Id); await CloseDocumentAsync(testLspServer, document); // And get diagnostic again, using the same doc-id as before. await WaitForDiagnosticsAsync(workspace); results = await testLspServer.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( MSLSPMethods.DocumentPullDiagnosticName, new DocumentDiagnosticsParams { PreviousResultId = results.Single().ResultId, TextDocument = ProtocolConversions.DocumentToTextDocumentIdentifier(document) }, new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); Assert.Null(results.Single().Diagnostics); Assert.Null(results.Single().ResultId); } [Fact] public async Task TestNoChangeIfDocumentDiagnosticsCalledTwice() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); var resultId = results.Single().ResultId; results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI(), previousResultId: resultId); Assert.Null(results.Single().Diagnostics); Assert.Equal(resultId, results.Single().ResultId); } [Fact] public async Task TestDocumentDiagnosticsRemovedAfterErrorIsFixed() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. var buffer = testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); await InsertTextAsync(testLspServer, document, buffer.CurrentSnapshot.Length, "}"); results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results[0].Diagnostics); } [Fact] public async Task TestDocumentDiagnosticsRemainAfterErrorIsNotFixed() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. var buffer = testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); buffer.Insert(0, " "); await InsertTextAsync(testLspServer, document, position: 0, text: " "); results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI(), previousResultId: results[0].ResultId); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 10 }, results[0].Diagnostics.Single().Range.Start); } [Fact] public async Task TestDocumentDiagnosticsAreNotMapped() { var markup = @"#line 1 ""test.txt"" class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); Assert.Equal(1, results.Single().Diagnostics.Single().Range.Start.Line); } private static async Task InsertTextAsync( TestLspServer testLspServer, Document document, int position, string text) { var sourceText = await document.GetTextAsync(); var lineInfo = sourceText.Lines.GetLinePositionSpan(new TextSpan(position, 0)); await testLspServer.InsertTextAsync(document.GetURI(), (lineInfo.Start.Line, lineInfo.Start.Character, text)); } private static Task OpenDocumentAsync(TestLspServer testLspServer, Document document) => testLspServer.OpenDocumentAsync(document.GetURI()); private static Task CloseDocumentAsync(TestLspServer testLspServer, Document document) => testLspServer.CloseDocumentAsync(document.GetURI()); [Fact] public async Task TestStreamingDocumentDiagnostics() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var progress = BufferedProgress.Create<DiagnosticReport>(null); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI(), progress: progress); Assert.Null(results); Assert.Equal("CS1513", progress.GetValues()!.Single().Diagnostics.Single().Code); } [Fact] public async Task TestDocumentDiagnosticsForOpenFilesUsesActiveContext() { var documentText = @"#if ONE class A { #endif class B {"; var workspaceXml = @$"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""C:\C.cs"">{documentText}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1"">{documentText}</Document> </Project> </Workspace>"; using var testLspServer = CreateTestWorkspaceFromXml(workspaceXml, BackgroundAnalysisScope.OpenFilesAndProjects); var csproj1Document = testLspServer.GetCurrentSolution().Projects.Where(p => p.Name == "CSProj1").Single().Documents.First(); var csproj2Document = testLspServer.GetCurrentSolution().Projects.Where(p => p.Name == "CSProj2").Single().Documents.First(); // Open either of the documents via LSP, we're tracking the URI and text. await OpenDocumentAsync(testLspServer, csproj1Document); // This opens all documents in the workspace and ensures buffers are created. testLspServer.TestWorkspace.GetTestDocument(csproj1Document.Id).GetTextBuffer(); // Set CSProj2 as the active context and get diagnostics. testLspServer.TestWorkspace.SetDocumentContext(csproj2Document.Id); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, csproj2Document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); var vsDiagnostic = (LSP.VSDiagnostic)results.Single().Diagnostics.Single(); Assert.Equal("CSProj2", vsDiagnostic.Projects.Single().ProjectName); // Set CSProj1 as the active context and get diagnostics. testLspServer.TestWorkspace.SetDocumentContext(csproj1Document.Id); results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, csproj1Document.GetURI()); Assert.Equal(2, results.Single().Diagnostics!.Length); Assert.All(results.Single().Diagnostics, d => Assert.Equal("CS1513", d.Code)); Assert.All(results.Single().Diagnostics, d => Assert.Equal("CSProj1", ((VSDiagnostic)d).Projects.Single().ProjectName)); } #endregion #region Workspace Diagnostics [Fact] public async Task TestNoWorkspaceDiagnosticsForClosedFilesWithFSAOff() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.OpenFilesAndProjects); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Empty(results); } [Fact] public async Task TestWorkspaceDiagnosticsForClosedFilesWithFSAOn() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); } [Fact] public async Task TestNoWorkspaceDiagnosticsForClosedFilesWithFSAOnAndInPushMode() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution, pullDiagnostics: false); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Empty(results[0].Diagnostics); Assert.Empty(results[1].Diagnostics); } [Fact] public async Task TestWorkspaceDiagnosticsForRemovedDocument() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); testLspServer.TestWorkspace.OnDocumentRemoved(testLspServer.TestWorkspace.Documents.First().Id); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); // First doc should show up as removed. Assert.Equal(2, results2.Length); Assert.Null(results2[0].Diagnostics); Assert.Null(results2[0].ResultId); // Second doc should show up as unchanged. Assert.Null(results2[1].Diagnostics); Assert.Equal(results[1].ResultId, results2[1].ResultId); } private static DiagnosticParams[] CreateDiagnosticParamsFromPreviousReports(WorkspaceDiagnosticReport[] results) { return results.Select(r => new DiagnosticParams { TextDocument = r.TextDocument, PreviousResultId = r.ResultId }).ToArray(); } [Fact] public async Task TestNoChangeIfWorkspaceDiagnosticsCalledTwice() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); Assert.Equal(2, results2.Length); Assert.Null(results2[0].Diagnostics); Assert.Null(results2[1].Diagnostics); Assert.Equal(results[0].ResultId, results2[0].ResultId); Assert.Equal(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestWorkspaceDiagnosticsRemovedAfterErrorIsFixed() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); var buffer = testLspServer.TestWorkspace.Documents.First().GetTextBuffer(); buffer.Insert(buffer.CurrentSnapshot.Length, "}"); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); Assert.Equal(2, results2.Length); Assert.Empty(results2[0].Diagnostics); Assert.Null(results2[1].Diagnostics); Assert.NotEqual(results[0].ResultId, results2[0].ResultId); Assert.Equal(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestWorkspaceDiagnosticsRemainAfterErrorIsNotFixed() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); Assert.Empty(results[1].Diagnostics); var buffer = testLspServer.TestWorkspace.Documents.First().GetTextBuffer(); buffer.Insert(0, " "); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.First(); var text = await document.GetTextAsync(); // Hacky, but we need to close the document manually since editing the text-buffer will open it in the // test-workspace. testLspServer.TestWorkspace.OnDocumentClosed( document.Id, TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create()))); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal("CS1513", results2[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 10 }, results2[0].Diagnostics.Single().Range.Start); Assert.Empty(results2[1].Diagnostics); Assert.NotEqual(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestStreamingWorkspaceDiagnostics() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); var progress = BufferedProgress.Create<DiagnosticReport>(null); results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, progress: progress); Assert.Null(results); Assert.Equal("CS1513", progress.GetValues()![0].Diagnostics![0].Code); } [Fact] public async Task TestWorkspaceDiagnosticsAreNotMapped() { var markup1 = @"#line 1 ""test.txt"" class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal(new Uri("C:/test1.cs"), results[0].TextDocument!.Uri); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(1, results[0].Diagnostics.Single().Range.Start.Line); Assert.Empty(results[1].Diagnostics); } #endregion private static async Task<DiagnosticReport[]> RunGetDocumentPullDiagnosticsAsync( TestLspServer testLspServer, Uri uri, string? previousResultId = null, IProgress<DiagnosticReport[]>? progress = null) { await WaitForDiagnosticsAsync(testLspServer.TestWorkspace); var result = await testLspServer.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( MSLSPMethods.DocumentPullDiagnosticName, CreateDocumentDiagnosticParams(uri, previousResultId, progress), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); return result; } private static async Task<WorkspaceDiagnosticReport[]> RunGetWorkspacePullDiagnosticsAsync( TestLspServer testLspServer, DiagnosticParams[]? previousResults = null, IProgress<WorkspaceDiagnosticReport[]>? progress = null) { await WaitForDiagnosticsAsync(testLspServer.TestWorkspace); var result = await testLspServer.ExecuteRequestAsync<WorkspaceDocumentDiagnosticsParams, WorkspaceDiagnosticReport[]>( MSLSPMethods.WorkspacePullDiagnosticName, CreateWorkspaceDiagnosticParams(previousResults, progress), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); return result; } private static async Task WaitForDiagnosticsAsync(TestWorkspace workspace) { var listenerProvider = workspace.GetService<IAsynchronousOperationListenerProvider>(); await listenerProvider.GetWaiter(FeatureAttribute.Workspace).ExpeditedWaitAsync(); await listenerProvider.GetWaiter(FeatureAttribute.SolutionCrawler).ExpeditedWaitAsync(); await listenerProvider.GetWaiter(FeatureAttribute.DiagnosticService).ExpeditedWaitAsync(); } private static DocumentDiagnosticsParams CreateDocumentDiagnosticParams( Uri uri, string? previousResultId = null, IProgress<DiagnosticReport[]>? progress = null) { return new DocumentDiagnosticsParams { TextDocument = new LSP.TextDocumentIdentifier { Uri = uri }, PreviousResultId = previousResultId, PartialResultToken = progress, }; } private static WorkspaceDocumentDiagnosticsParams CreateWorkspaceDiagnosticParams( DiagnosticParams[]? previousResults = null, IProgress<WorkspaceDiagnosticReport[]>? progress = null) { return new WorkspaceDocumentDiagnosticsParams { PreviousResults = previousResults, PartialResultToken = progress, }; } private TestLspServer CreateTestWorkspaceWithDiagnostics(string markup, BackgroundAnalysisScope scope, bool pullDiagnostics = true) => CreateTestWorkspaceWithDiagnostics(markup, scope, pullDiagnostics ? DiagnosticMode.Pull : DiagnosticMode.Push); private TestLspServer CreateTestWorkspaceWithDiagnostics(string markup, BackgroundAnalysisScope scope, DiagnosticMode mode) { var testLspServer = CreateTestLspServer(markup, out _); InitializeDiagnostics(scope, testLspServer.TestWorkspace, mode); return testLspServer; } private TestLspServer CreateTestWorkspaceFromXml(string xmlMarkup, BackgroundAnalysisScope scope, bool pullDiagnostics = true) { var testLspServer = CreateXmlTestLspServer(xmlMarkup, out _); InitializeDiagnostics(scope, testLspServer.TestWorkspace, pullDiagnostics ? DiagnosticMode.Pull : DiagnosticMode.Push); return testLspServer; } private TestLspServer CreateTestWorkspaceWithDiagnostics(string[] markups, BackgroundAnalysisScope scope, bool pullDiagnostics = true) { var testLspServer = CreateTestLspServer(markups, out _); InitializeDiagnostics(scope, testLspServer.TestWorkspace, pullDiagnostics ? DiagnosticMode.Pull : DiagnosticMode.Push); return testLspServer; } private static void InitializeDiagnostics(BackgroundAnalysisScope scope, TestWorkspace workspace, DiagnosticMode diagnosticMode) { workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions( workspace.Options .WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, scope) .WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.VisualBasic, scope) .WithChangedOption(InternalDiagnosticsOptions.NormalDiagnosticMode, diagnosticMode))); var analyzerReference = new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var registrationService = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registrationService.Register(workspace); var diagnosticService = (DiagnosticService)workspace.ExportProvider.GetExportedValue<IDiagnosticService>(); diagnosticService.Register(new TestHostDiagnosticUpdateSource(workspace)); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Test; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Diagnostics { public class PullDiagnosticTests : AbstractLanguageServerProtocolTests { #region Document Diagnostics [Fact] public async Task TestNoDocumentDiagnosticsForClosedFilesWithFSAOff() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results); } [Fact] public async Task TestDocumentDiagnosticsForOpenFilesWithFSAOff() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); } [Fact] public async Task TestNoDocumentDiagnosticsForOpenFilesWithFSAOffIfInPushMode() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects, pullDiagnostics: false); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results.Single().Diagnostics); } [Fact] public async Task TestNoDocumentDiagnosticsForOpenFilesIfDefaultAndFeatureFlagOff() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects, DiagnosticMode.Default); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); // Ensure we get no diagnostics when feature flag is off. var testExperimentationService = (TestExperimentationService)testLspServer.TestWorkspace.Services.GetRequiredService<IExperimentationService>(); testExperimentationService.SetExperimentOption(WellKnownExperimentNames.LspPullDiagnosticsFeatureFlag, false); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results.Single().Diagnostics); } [Fact] public async Task TestDocumentDiagnosticsForOpenFilesIfDefaultAndFeatureFlagOn() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects, DiagnosticMode.Default); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var testExperimentationService = (TestExperimentationService)testLspServer.TestWorkspace.Services.GetRequiredService<IExperimentationService>(); testExperimentationService.SetExperimentOption(WellKnownExperimentNames.LspPullDiagnosticsFeatureFlag, true); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); } [Fact] public async Task TestDocumentDiagnosticsForRemovedDocument() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); var workspace = testLspServer.TestWorkspace; // Calling GetTextBuffer will effectively open the file. workspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); // Get the diagnostics for the solution containing the doc. var solution = document.Project.Solution; await OpenDocumentAsync(testLspServer, document); await WaitForDiagnosticsAsync(workspace); var results = await testLspServer.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( MSLSPMethods.DocumentPullDiagnosticName, CreateDocumentDiagnosticParams(document.GetURI()), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); // Now remove the doc. workspace.OnDocumentRemoved(workspace.Documents.Single().Id); await CloseDocumentAsync(testLspServer, document); // And get diagnostic again, using the same doc-id as before. await WaitForDiagnosticsAsync(workspace); results = await testLspServer.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( MSLSPMethods.DocumentPullDiagnosticName, new DocumentDiagnosticsParams { PreviousResultId = results.Single().ResultId, TextDocument = ProtocolConversions.DocumentToTextDocumentIdentifier(document) }, new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); Assert.Null(results.Single().Diagnostics); Assert.Null(results.Single().ResultId); } [Fact] public async Task TestNoChangeIfDocumentDiagnosticsCalledTwice() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); var resultId = results.Single().ResultId; results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI(), previousResultId: resultId); Assert.Null(results.Single().Diagnostics); Assert.Equal(resultId, results.Single().ResultId); } [Fact] public async Task TestDocumentDiagnosticsRemovedAfterErrorIsFixed() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. var buffer = testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); await InsertTextAsync(testLspServer, document, buffer.CurrentSnapshot.Length, "}"); results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Empty(results[0].Diagnostics); } [Fact] public async Task TestDocumentDiagnosticsRemainAfterErrorIsNotFixed() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. var buffer = testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI()); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); buffer.Insert(0, " "); await InsertTextAsync(testLspServer, document, position: 0, text: " "); results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI(), previousResultId: results[0].ResultId); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 10 }, results[0].Diagnostics.Single().Range.Start); } [Fact] public async Task TestDocumentDiagnosticsAreNotMapped() { var markup = @"#line 1 ""test.txt"" class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var results = await RunGetDocumentPullDiagnosticsAsync( testLspServer, document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); Assert.Equal(1, results.Single().Diagnostics.Single().Range.Start.Line); } private static async Task InsertTextAsync( TestLspServer testLspServer, Document document, int position, string text) { var sourceText = await document.GetTextAsync(); var lineInfo = sourceText.Lines.GetLinePositionSpan(new TextSpan(position, 0)); await testLspServer.InsertTextAsync(document.GetURI(), (lineInfo.Start.Line, lineInfo.Start.Character, text)); } private static Task OpenDocumentAsync(TestLspServer testLspServer, Document document) => testLspServer.OpenDocumentAsync(document.GetURI()); private static Task CloseDocumentAsync(TestLspServer testLspServer, Document document) => testLspServer.CloseDocumentAsync(document.GetURI()); [Fact] public async Task TestStreamingDocumentDiagnostics() { var markup = @"class A {"; using var testLspServer = CreateTestWorkspaceWithDiagnostics(markup, BackgroundAnalysisScope.OpenFilesAndProjects); // Calling GetTextBuffer will effectively open the file. testLspServer.TestWorkspace.Documents.Single().GetTextBuffer(); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.Single(); await OpenDocumentAsync(testLspServer, document); var progress = BufferedProgress.Create<DiagnosticReport>(null); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, document.GetURI(), progress: progress); Assert.Null(results); Assert.Equal("CS1513", progress.GetValues()!.Single().Diagnostics.Single().Code); } [Fact] public async Task TestDocumentDiagnosticsForOpenFilesUsesActiveContext() { var documentText = @"#if ONE class A { #endif class B {"; var workspaceXml = @$"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""C:\C.cs"">{documentText}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1"">{documentText}</Document> </Project> </Workspace>"; using var testLspServer = CreateTestWorkspaceFromXml(workspaceXml, BackgroundAnalysisScope.OpenFilesAndProjects); var csproj1Document = testLspServer.GetCurrentSolution().Projects.Where(p => p.Name == "CSProj1").Single().Documents.First(); var csproj2Document = testLspServer.GetCurrentSolution().Projects.Where(p => p.Name == "CSProj2").Single().Documents.First(); // Open either of the documents via LSP, we're tracking the URI and text. await OpenDocumentAsync(testLspServer, csproj1Document); // This opens all documents in the workspace and ensures buffers are created. testLspServer.TestWorkspace.GetTestDocument(csproj1Document.Id).GetTextBuffer(); // Set CSProj2 as the active context and get diagnostics. testLspServer.TestWorkspace.SetDocumentContext(csproj2Document.Id); var results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, csproj2Document.GetURI()); Assert.Equal("CS1513", results.Single().Diagnostics.Single().Code); var vsDiagnostic = (LSP.VSDiagnostic)results.Single().Diagnostics.Single(); Assert.Equal("CSProj2", vsDiagnostic.Projects.Single().ProjectName); // Set CSProj1 as the active context and get diagnostics. testLspServer.TestWorkspace.SetDocumentContext(csproj1Document.Id); results = await RunGetDocumentPullDiagnosticsAsync(testLspServer, csproj1Document.GetURI()); Assert.Equal(2, results.Single().Diagnostics!.Length); Assert.All(results.Single().Diagnostics, d => Assert.Equal("CS1513", d.Code)); Assert.All(results.Single().Diagnostics, d => Assert.Equal("CSProj1", ((VSDiagnostic)d).Projects.Single().ProjectName)); } #endregion #region Workspace Diagnostics [Fact] public async Task TestNoWorkspaceDiagnosticsForClosedFilesWithFSAOff() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.OpenFilesAndProjects); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Empty(results); } [Fact] public async Task TestWorkspaceDiagnosticsForClosedFilesWithFSAOn() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); } [Fact] public async Task TestNoWorkspaceDiagnosticsForClosedFilesWithFSAOnAndInPushMode() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution, pullDiagnostics: false); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Empty(results[0].Diagnostics); Assert.Empty(results[1].Diagnostics); } [Fact] public async Task TestWorkspaceDiagnosticsForRemovedDocument() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); testLspServer.TestWorkspace.OnDocumentRemoved(testLspServer.TestWorkspace.Documents.First().Id); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); // First doc should show up as removed. Assert.Equal(2, results2.Length); Assert.Null(results2[0].Diagnostics); Assert.Null(results2[0].ResultId); // Second doc should show up as unchanged. Assert.Null(results2[1].Diagnostics); Assert.Equal(results[1].ResultId, results2[1].ResultId); } private static DiagnosticParams[] CreateDiagnosticParamsFromPreviousReports(WorkspaceDiagnosticReport[] results) { return results.Select(r => new DiagnosticParams { TextDocument = r.TextDocument, PreviousResultId = r.ResultId }).ToArray(); } [Fact] public async Task TestNoChangeIfWorkspaceDiagnosticsCalledTwice() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); Assert.Equal(2, results2.Length); Assert.Null(results2[0].Diagnostics); Assert.Null(results2[1].Diagnostics); Assert.Equal(results[0].ResultId, results2[0].ResultId); Assert.Equal(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestWorkspaceDiagnosticsRemovedAfterErrorIsFixed() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Empty(results[1].Diagnostics); var buffer = testLspServer.TestWorkspace.Documents.First().GetTextBuffer(); buffer.Insert(buffer.CurrentSnapshot.Length, "}"); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, previousResults: CreateDiagnosticParamsFromPreviousReports(results)); Assert.Equal(2, results2.Length); Assert.Empty(results2[0].Diagnostics); Assert.Null(results2[1].Diagnostics); Assert.NotEqual(results[0].ResultId, results2[0].ResultId); Assert.Equal(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestWorkspaceDiagnosticsRemainAfterErrorIsNotFixed() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); Assert.Empty(results[1].Diagnostics); var buffer = testLspServer.TestWorkspace.Documents.First().GetTextBuffer(); buffer.Insert(0, " "); var document = testLspServer.GetCurrentSolution().Projects.Single().Documents.First(); var text = await document.GetTextAsync(); // Hacky, but we need to close the document manually since editing the text-buffer will open it in the // test-workspace. testLspServer.TestWorkspace.OnDocumentClosed( document.Id, TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create()))); var results2 = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal("CS1513", results2[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 10 }, results2[0].Diagnostics.Single().Range.Start); Assert.Empty(results2[1].Diagnostics); Assert.NotEqual(results[1].ResultId, results2[1].ResultId); } [Fact] public async Task TestStreamingWorkspaceDiagnostics() { var markup1 = @"class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(new Position { Line = 0, Character = 9 }, results[0].Diagnostics.Single().Range.Start); var progress = BufferedProgress.Create<DiagnosticReport>(null); results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer, progress: progress); Assert.Null(results); Assert.Equal("CS1513", progress.GetValues()![0].Diagnostics![0].Code); } [Fact] public async Task TestWorkspaceDiagnosticsAreNotMapped() { var markup1 = @"#line 1 ""test.txt"" class A {"; var markup2 = ""; using var testLspServer = CreateTestWorkspaceWithDiagnostics( new[] { markup1, markup2 }, BackgroundAnalysisScope.FullSolution); var results = await RunGetWorkspacePullDiagnosticsAsync(testLspServer); Assert.Equal(2, results.Length); Assert.Equal(new Uri("C:/test1.cs"), results[0].TextDocument!.Uri); Assert.Equal("CS1513", results[0].Diagnostics.Single().Code); Assert.Equal(1, results[0].Diagnostics.Single().Range.Start.Line); Assert.Empty(results[1].Diagnostics); } #endregion private static async Task<DiagnosticReport[]> RunGetDocumentPullDiagnosticsAsync( TestLspServer testLspServer, Uri uri, string? previousResultId = null, IProgress<DiagnosticReport[]>? progress = null) { await WaitForDiagnosticsAsync(testLspServer.TestWorkspace); var result = await testLspServer.ExecuteRequestAsync<DocumentDiagnosticsParams, DiagnosticReport[]>( MSLSPMethods.DocumentPullDiagnosticName, CreateDocumentDiagnosticParams(uri, previousResultId, progress), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); return result; } private static async Task<WorkspaceDiagnosticReport[]> RunGetWorkspacePullDiagnosticsAsync( TestLspServer testLspServer, DiagnosticParams[]? previousResults = null, IProgress<WorkspaceDiagnosticReport[]>? progress = null) { await WaitForDiagnosticsAsync(testLspServer.TestWorkspace); var result = await testLspServer.ExecuteRequestAsync<WorkspaceDocumentDiagnosticsParams, WorkspaceDiagnosticReport[]>( MSLSPMethods.WorkspacePullDiagnosticName, CreateWorkspaceDiagnosticParams(previousResults, progress), new LSP.ClientCapabilities(), clientName: null, CancellationToken.None); return result; } private static async Task WaitForDiagnosticsAsync(TestWorkspace workspace) { var listenerProvider = workspace.GetService<IAsynchronousOperationListenerProvider>(); await listenerProvider.GetWaiter(FeatureAttribute.Workspace).ExpeditedWaitAsync(); await listenerProvider.GetWaiter(FeatureAttribute.SolutionCrawler).ExpeditedWaitAsync(); await listenerProvider.GetWaiter(FeatureAttribute.DiagnosticService).ExpeditedWaitAsync(); } private static DocumentDiagnosticsParams CreateDocumentDiagnosticParams( Uri uri, string? previousResultId = null, IProgress<DiagnosticReport[]>? progress = null) { return new DocumentDiagnosticsParams { TextDocument = new LSP.TextDocumentIdentifier { Uri = uri }, PreviousResultId = previousResultId, PartialResultToken = progress, }; } private static WorkspaceDocumentDiagnosticsParams CreateWorkspaceDiagnosticParams( DiagnosticParams[]? previousResults = null, IProgress<WorkspaceDiagnosticReport[]>? progress = null) { return new WorkspaceDocumentDiagnosticsParams { PreviousResults = previousResults, PartialResultToken = progress, }; } private TestLspServer CreateTestWorkspaceWithDiagnostics(string markup, BackgroundAnalysisScope scope, bool pullDiagnostics = true) => CreateTestWorkspaceWithDiagnostics(markup, scope, pullDiagnostics ? DiagnosticMode.Pull : DiagnosticMode.Push); private TestLspServer CreateTestWorkspaceWithDiagnostics(string markup, BackgroundAnalysisScope scope, DiagnosticMode mode) { var testLspServer = CreateTestLspServer(markup, out _); InitializeDiagnostics(scope, testLspServer.TestWorkspace, mode); return testLspServer; } private TestLspServer CreateTestWorkspaceFromXml(string xmlMarkup, BackgroundAnalysisScope scope, bool pullDiagnostics = true) { var testLspServer = CreateXmlTestLspServer(xmlMarkup, out _); InitializeDiagnostics(scope, testLspServer.TestWorkspace, pullDiagnostics ? DiagnosticMode.Pull : DiagnosticMode.Push); return testLspServer; } private TestLspServer CreateTestWorkspaceWithDiagnostics(string[] markups, BackgroundAnalysisScope scope, bool pullDiagnostics = true) { var testLspServer = CreateTestLspServer(markups, out _); InitializeDiagnostics(scope, testLspServer.TestWorkspace, pullDiagnostics ? DiagnosticMode.Pull : DiagnosticMode.Push); return testLspServer; } private static void InitializeDiagnostics(BackgroundAnalysisScope scope, TestWorkspace workspace, DiagnosticMode diagnosticMode) { workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions( workspace.Options .WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, scope) .WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.VisualBasic, scope) .WithChangedOption(InternalDiagnosticsOptions.NormalDiagnosticMode, diagnosticMode))); var analyzerReference = new TestAnalyzerReferenceByLanguage(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var registrationService = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registrationService.Register(workspace); var diagnosticService = (DiagnosticService)workspace.ExportProvider.GetExportedValue<IDiagnosticService>(); diagnosticService.Register(new TestHostDiagnosticUpdateSource(workspace)); } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Semantic/Semantics/NonTrailingNamedArgumentsTests.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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { [CompilerTrait(CompilerFeature.NonTrailingNamedArgs)] public class NonTrailingNamedArgumentsTests : CompilingTestBase { [Fact] public void TestSimple() { var source = @" class C { static void M(int a, int b) { System.Console.Write($""First {a} {b}. ""); } static void M(long b, long a) { System.Console.Write($""Second {b} {a}. ""); } static void Main() { M(a: 1, 2); M(3, a: 4); } }"; var verifier = CompileAndVerify(source, expectedOutput: "First 1 2. Second 3 4.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); var tree = verifier.Compilation.SyntaxTrees.First(); var model = verifier.Compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var firstInvocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(2); Assert.Equal("M(a: 1, 2)", firstInvocation.ToString()); Assert.Equal("void C.M(System.Int32 a, System.Int32 b)", model.GetSymbolInfo(firstInvocation).Symbol.ToTestDisplayString()); var firstNamedArgA = nodes.OfType<NameColonSyntax>().ElementAt(0); Assert.Equal("a: 1", firstNamedArgA.Parent.ToString()); var firstASymbol = model.GetSymbolInfo(firstNamedArgA.Name); Assert.Equal(SymbolKind.Parameter, firstASymbol.Symbol.Kind); Assert.Equal("a", firstASymbol.Symbol.Name); Assert.Equal("void C.M(System.Int32 a, System.Int32 b)", firstASymbol.Symbol.ContainingSymbol.ToTestDisplayString()); var secondInvocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(3); Assert.Equal("M(3, a: 4)", secondInvocation.ToString()); Assert.Equal("void C.M(System.Int64 b, System.Int64 a)", model.GetSymbolInfo(secondInvocation).Symbol.ToTestDisplayString()); var secondNamedArgA = nodes.OfType<NameColonSyntax>().ElementAt(1); Assert.Equal("a: 4", secondNamedArgA.Parent.ToString()); var secondASymbol = model.GetSymbolInfo(secondNamedArgA.Name); Assert.Equal(SymbolKind.Parameter, secondASymbol.Symbol.Kind); Assert.Equal("a", secondASymbol.Symbol.Name); Assert.Equal("void C.M(System.Int64 b, System.Int64 a)", secondASymbol.Symbol.ContainingSymbol.ToTestDisplayString()); } [Fact] public void TestSimpleConstructor() { var source = @" class C { C(int a, int b) { System.Console.Write($""{a} {b}.""); } static void Main() { new C(a: 1, 2); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1 2.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics( // (10,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // new C(a: 1, 2); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(10, 21) ); } [Fact] public void TestSimpleThis() { var source = @" class C { C(int a, int b) { System.Console.Write($""{a} {b}.""); } C() : this(a: 1, 2) { } static void Main() { new C(); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1 2.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); } [Fact] public void TestSimpleBase() { var source = @" public class C { public C(int a, int b) { System.Console.Write($""{a} {b}.""); } } class Derived : C { Derived() : base(a: 1, 2) { } static void Main() { new Derived(); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1 2.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); } [Fact] public void TestSimpleExtension() { var source = @" public static class Extension { public static void M(this C c, int a, int b) { System.Console.Write($""{a} {b}.""); } } public class C { static void Main() { var c = new C(); c.M(a: 1, 2); } }"; var verifier = CompileAndVerifyWithMscorlib40(source, expectedOutput: "1 2.", parseOptions: TestOptions.Regular7_2, references: new[] { TestMetadata.Net40.SystemCore }); verifier.VerifyDiagnostics(); var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7_1, references: new[] { TestMetadata.Net40.SystemCore }); comp.VerifyDiagnostics( // (14,19): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // c.M(a: 1, 2); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(14, 19) ); } [Fact] public void TestSimpleDelegate() { var source = @" class C { delegate void MyDelegate(int a, int b); event MyDelegate e; static void M(int a, int b) { System.Console.Write($""{a} {b}. ""); } static void Main() { var c = new C(); c.e += M; c.e.Invoke(a: 1, 2); c.e(a: 1, 2); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1 2. 1 2.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics( // (16,26): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // c.e.Invoke(a: 1, 2); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(16, 26), // (17,19): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // c.e(a: 1, 2); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(17, 19) ); } [Fact] public void TestSimpleLocalFunction() { var source = @" class C { static void Main() { var c = new C(); local(a: 1, 2); void local(int a, int b) { System.Console.Write($""{a} {b}.""); } } }"; var verifier = CompileAndVerify(source, expectedOutput: "1 2.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics( // (7,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // local(a: 1, 2); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(7, 21) ); } [Fact] public void TestSimpleIndexer() { var source = @" class C { int this[int a, int b] { get { System.Console.Write($""Get {a} {b}. ""); return 0; } set { System.Console.Write($""Set {a} {b} {value}.""); } } static void Main() { var c = new C(); _ = c[a: 1, 2]; c[a: 3, 4] = 5; } }"; var verifier = CompileAndVerify(source, expectedOutput: "Get 1 2. Set 3 4 5.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics( // (19,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // _ = c[a: 1, 2]; Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(19, 21), // (20,17): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // c[a: 3, 4] = 5; Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "4").WithArguments("7.2").WithLocation(20, 17) ); } [Fact] public void TestSimpleError() { var source = @" class C { int this[int a, int b] { get { throw null; } } C(int a, int b) { } static void Main() { var c = new C(b: 1, 2); _ = c[b: 1, 2]; local(b: 1, 2); void local(int a, int b) { } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (16,23): error CS8322: Named argument 'b' is used out-of-position but is followed by an unnamed argument // var c = new C(b: 1, 2); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "b").WithArguments("b").WithLocation(16, 23), // (17,15): error CS8322: Named argument 'b' is used out-of-position but is followed by an unnamed argument // _ = c[b: 1, 2]; Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "b").WithArguments("b").WithLocation(17, 15), // (18,15): error CS8322: Named argument 'b' is used out-of-position but is followed by an unnamed argument // local(b: 1, 2); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "b").WithArguments("b").WithLocation(18, 15) ); } [Fact] public void TestMetadataAndPESymbols() { var lib_cs = @" public class C { public static void M(int a, int b) { System.Console.Write($""{a} {b}.""); } }"; var source = @" class D { static void Main() { C.M(a: 1, 2); } }"; var lib = CreateCompilation(lib_cs, parseOptions: TestOptions.Regular7); var verifier1 = CompileAndVerify(source, expectedOutput: "1 2.", parseOptions: TestOptions.Regular7_2, references: new[] { lib.ToMetadataReference() }); verifier1.VerifyDiagnostics(); var verifier2 = CompileAndVerify(source, expectedOutput: "1 2.", parseOptions: TestOptions.Regular7_2, references: new[] { lib.EmitToImageReference() }); verifier2.VerifyDiagnostics(); } [Fact] public void TestPositionalUnaffected() { var source = @" class C { static void M(int first, int other) { System.Console.Write($""{first} {other}""); } static void Main() { M(1, first: 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,14): error CS1744: Named argument 'first' specifies a parameter for which a positional argument has already been given // M(1, first: 2); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "first").WithArguments("first").WithLocation(10, 14) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(1); Assert.Equal("M(1, first: 2)", invocation.ToString()); Assert.Null(model.GetSymbolInfo(invocation).Symbol); } [Fact] public void TestGenericInference() { var source = @" class C { static void M<T1, T2>(T1 a, T2 b) { System.Console.Write($""{a} {b}.""); } static void Main() { C.M(a: 1, ""hi""); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1 hi.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); var tree = verifier.Compilation.SyntaxTrees.First(); var model = verifier.Compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(1); Assert.Equal(@"C.M(a: 1, ""hi"")", invocation.ToString()); Assert.Equal("void C.M<System.Int32, System.String>(System.Int32 a, System.String b)", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString()); } [Fact] public void TestPositionalUnaffected2() { var source = @" class C { static void M(int a, int b, int c = 1) { System.Console.Write($""M {a} {b}""); } static void Main() { M(c: 1, 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,11): error CS8321: Named argument 'c' is used out-of-position but is followed by an unnamed argument // M(c: 1, 2); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "c").WithArguments("c").WithLocation(10, 11) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(1); Assert.Equal("M(c: 1, 2)", invocation.ToString()); SymbolInfo symbol = model.GetSymbolInfo(invocation); AssertEx.Equal(new[] { "void C.M(System.Int32 a, System.Int32 b, [System.Int32 c = 1])" }, symbol.CandidateSymbols.Select(c => c.ToTestDisplayString())); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbol.CandidateReason); } [Fact] public void TestNamedParams() { var source = @" class C { static void M(params int[] x) { } static void Main() { M(x: 1, 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS1501: No overload for method 'M' takes 2 arguments // M(x: 1, 2); Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "2").WithLocation(9, 9) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("M(x: 1, 2)", invocation.ToString()); Assert.Null(model.GetSymbolInfo(invocation).Symbol); } [Fact] public void TestNamedParams2() { var source = @" class C { static void M(params int[] x) { } static void Main() { M(1, x: 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,14): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given // M(1, x: 2); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(9, 14) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("M(1, x: 2)", invocation.ToString()); Assert.Null(model.GetSymbolInfo(invocation).Symbol); } [Fact] public void TestNamedParamsVariousForms() { var source = @" class C { static void M(int x, params string[] y) { System.Console.Write($""{x} {string.Join("","", y)}. ""); } static void Main() { M(x: 1, y: ""2""); M(x: 2, ""3""); M(x: 3, new[] { ""4"", ""5"" }); } }"; var comp = CompileAndVerify(source, expectedOutput: "1 2. 2 3. 3 4,5."); comp.VerifyDiagnostics(); } [Fact] public void TestTwiceNamedParams() { var source = @" class C { static void M(params int[] x) { } static void Main() { M(x: 1, x: 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,17): error CS1740: Named argument 'x' cannot be specified multiple times // M(x: 1, x: 2); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "x").WithArguments("x").WithLocation(9, 17) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("M(x: 1, x: 2)", invocation.ToString()); var symbolInfo = model.GetSymbolInfo(invocation); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal("void C.M(params System.Int32[] x)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); } [Fact] public void TestTwiceNamedParamsWithOldLangVer() { var source = @" class C { static void M(int x, int y, int z) { } static void Main() { M(x: 1, x: 2, 3); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics( // (9,23): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // M(x: 1, x: 2, 3); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "3").WithArguments("7.2").WithLocation(9, 23), // (9,17): error CS8323: Named argument 'x' is used out-of-position but is followed by an unnamed argument // M(x: 1, x: 2, 3); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "x").WithArguments("x").WithLocation(9, 17)); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("M(x: 1, x: 2, 3)", invocation.ToString()); Assert.Null(model.GetSymbolInfo(invocation).Symbol); } [Fact] public void TestNamedParams3() { var source = @" class C { static void M(int x, params int[] y) { } static void Main() { M(y: 1, 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,11): error CS8321: Named argument 'y' is used out-of-position but is followed by an unnamed argument // M(y: 1, 2); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "y").WithArguments("y").WithLocation(9, 11) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("M(y: 1, 2)", invocation.ToString()); Assert.Null(model.GetSymbolInfo(invocation).Symbol); } [Fact] public void TestNamedParams4() { var source = @" class C { static void M(int x, params int[] y) { } static void Main() { M(x: 1, y: 2, 3); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS1501: No overload for method 'M' takes 3 arguments // M(x: 1, y: 2, 3); Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "3").WithLocation(9, 9) ); } [Fact] public void TestNamedInvalidParams() { var source = @" class C { static void M(params int[] x, int y) { } static void Main() { M(x: 1, 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,19): error CS0231: A params parameter must be the last parameter in a formal parameter list // static void M(params int[] x, int y) Diagnostic(ErrorCode.ERR_ParamsLast, "params int[] x").WithLocation(4, 19), // (9,14): error CS1503: Argument 1: cannot convert from 'int' to 'params int[]' // M(x: 1, 2); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "params int[]").WithLocation(9, 14) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("M(x: 1, 2)", invocation.ToString()); Assert.Null(model.GetSymbolInfo(invocation).Symbol); } [Fact] public void TestNamedParams5() { var source = @" class C { static void M(int x, params int[] y) { System.Console.Write($""x={x} y[0]={y[0]} y.Length={y.Length}""); } static void Main() { M(y: 1, x: 2); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "x=2 y[0]=1 y.Length=1"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(1); Assert.Equal("M(y: 1, x: 2)", invocation.ToString()); Assert.Equal("void C.M(System.Int32 x, params System.Int32[] y)", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString()); } [Fact] public void TestBadNonTrailing() { var source = @" class C { static void M(int a = 1, int b = 2, int c = 3) { } static void Main() { int valueB = 2; int valueC = 3; M(c: valueC, valueB); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,11): error CS8321: Named argument 'c' is used out-of-position but is followed by an unnamed argument // M(c: valueC, valueB); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "c").WithArguments("c").WithLocation(11, 11) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var firstInvocation = nodes.OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("M(c: valueC, valueB)", firstInvocation.ToString()); Assert.Null(model.GetSymbolInfo(firstInvocation).Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, model.GetSymbolInfo(firstInvocation).CandidateReason); Assert.Equal("void C.M([System.Int32 a = 1], [System.Int32 b = 2], [System.Int32 c = 3])", model.GetSymbolInfo(firstInvocation).CandidateSymbols.Single().ToTestDisplayString()); } [Fact] public void TestPickGoodOverload() { var source = @" class C { static void M(int a = 1, int b = 2, int c = 3) { } static void M(long c = 1, long b = 2) { System.Console.Write($""Second {c} {b}. ""); } static void Main() { int valueB = 2; int valueC = 3; M(c: valueC, valueB); } }"; var verifier = CompileAndVerify(source, expectedOutput: "Second 3 2."); verifier.VerifyDiagnostics(); var tree = verifier.Compilation.SyntaxTrees.First(); var model = verifier.Compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(1); Assert.Equal("M(c: valueC, valueB)", invocation.ToString()); Assert.Equal("void C.M([System.Int64 c = 1], [System.Int64 b = 2])", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString()); } [Fact] public void TestPickGoodOverload2() { var source = @" class C { static void M(long a = 1, long b = 2, long c = 3) { } static void M(int c = 1, int b = 2) { System.Console.Write($""Second {c} {b}.""); } static void Main() { int valueB = 2; int valueC = 3; M(c: valueC, valueB); } }"; var verifier = CompileAndVerify(source, expectedOutput: "Second 3 2."); verifier.VerifyDiagnostics(); var tree = verifier.Compilation.SyntaxTrees.First(); var model = verifier.Compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(1); Assert.Equal("M(c: valueC, valueB)", invocation.ToString()); Assert.Equal("void C.M([System.Int32 c = 1], [System.Int32 b = 2])", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString()); } [Fact] public void TestOptionalValues() { var source = @" class C { static void M(int a, int b, int c = 42) { System.Console.Write(c); } static void Main() { M(a: 1, 2); } }"; var comp = CompileAndVerify(source, expectedOutput: "42"); comp.VerifyDiagnostics(); } [Fact] public void TestDynamicInvocation() { var source = @" class C { void M() { dynamic d = new object(); d.M(a: 1, 2); d.M(1, 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (7,19): error CS8323: Named argument specifications must appear after all fixed arguments have been specified in a dynamic invocation. // d.M(a: 1, 2); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation, "2").WithLocation(7, 19) ); var comp2 = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp2.VerifyDiagnostics( // (7,19): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // d.M(a: 1, 2); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(7, 19) ); } [Fact] public void TestInvocationWithDynamicInLocalFunctionParams() { var source = @" class C { void M() { dynamic d = new object[] { 0 }; local(x: 1, d); void local(int x, params object[] y) { } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (7,9): error CS8108: Cannot pass argument with dynamic type to params parameter 'y' of local function 'local'. // local(x: 1, d); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionParamsParameter, "local(x: 1, d)").WithArguments("y", "local").WithLocation(7, 9), // (7,21): error CS8323: Named argument specifications must appear after all fixed arguments have been specified in a dynamic invocation. // local(x: 1, d); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation, "d").WithLocation(7, 21) ); } [Fact] public void TestDynamicWhenNotInvocation() { var source = @" class C { int this[int a, int b] { get { System.Console.Write($""{a} {b}.""); return 0; } } void M(C c) { dynamic d = new object(); c[a: 1, d] = d; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void TestParams() { var source = @" class C { static void M(int a, int b, params int[] c) { } static void Main() { M(b: 2, 3, 4); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,11): error CS8321: Named argument 'b' is used out-of-position but is followed by an unnamed argument // M(b: 2, 3, 4); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "b").WithArguments("b").WithLocation(9, 11) ); } [Fact] public void TestParams2() { var source = @" class C { static void M(int a, int b, params int[] c) { System.Console.Write($""{a} {b} {c[0]} {c[1]} Length:{c.Length}""); } static void Main() { M(1, b: 2, 3, 4); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1 2 3 4 Length:2"); verifier.VerifyDiagnostics(); } [Fact] public void TestInAttribute() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class MyAttribute : Attribute { public int P { get; set; } public MyAttribute(bool condition, int other) { } } [MyAttribute(condition: true, 42)] [MyAttribute(condition: true, P = 1, 42)] [MyAttribute(42, condition: true)] public class C { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,38): error CS1016: Named attribute argument expected // [MyAttribute(condition: true, P = 1, 42)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "42").WithLocation(12, 38), // (13,18): error CS1744: Named argument 'condition' specifies a parameter for which a positional argument has already been given // [MyAttribute(42, condition: true)] Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "condition").WithArguments("condition").WithLocation(13, 18) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<AttributeSyntax>().ElementAt(1); Assert.Equal("MyAttribute(condition: true, 42)", invocation.ToString()); Assert.Equal("MyAttribute..ctor(System.Boolean condition, System.Int32 other)", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString()); } [Fact] public void TestInAttributeWithOldLangVersion() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class MyAttribute : Attribute { public int P { get; set; } public MyAttribute(bool condition, int other) { } } [MyAttribute(condition: true, 42)] [MyAttribute(condition: true, P = 1, 42)] [MyAttribute(42, condition: true)] public class C { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics( // (11,31): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // [MyAttribute(condition: true, 42)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "42").WithArguments("7.2").WithLocation(11, 31), // (12,38): error CS1016: Named attribute argument expected // [MyAttribute(condition: true, P = 1, 42)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "42").WithLocation(12, 38), // (12,38): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // [MyAttribute(condition: true, P = 1, 42)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "42").WithArguments("7.2").WithLocation(12, 38), // (13,18): error CS1744: Named argument 'condition' specifies a parameter for which a positional argument has already been given // [MyAttribute(42, condition: true)] Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "condition").WithArguments("condition").WithLocation(13, 18) ); } [Fact] public void TestInAttribute2() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class MyAttribute : Attribute { public int P { get; set; } public MyAttribute(int a = 1, int b = 2, int c = 3) { } } [MyAttribute(c:3, 2)] [MyAttribute(P=1, c:3, 2)] public class C { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,14): error CS8321: Named argument 'c' is used out-of-position but is followed by an unnamed argument // [MyAttribute(c:3, 2)] Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "c").WithArguments("c").WithLocation(11, 14), // (12,21): error CS1016: Named attribute argument expected // [MyAttribute(P=1, c:3, 2)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "3").WithLocation(12, 21), // (12,24): error CS1016: Named attribute argument expected // [MyAttribute(P=1, c:3, 2)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "2").WithLocation(12, 24), // (12,19): error CS8321: Named argument 'c' is used out-of-position but is followed by an unnamed argument // [MyAttribute(P=1, c:3, 2)] Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "c").WithArguments("c").WithLocation(12, 19) ); } [Fact] public void TestErrorsDoNotCascadeInInvocation() { var source = @" class C { static void M() { M(x: 1, x: 2, __arglist()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,11): error CS1739: The best overload for 'M' does not have a parameter named 'x' // M(x: 1, x: 2, __arglist()); Diagnostic(ErrorCode.ERR_BadNamedArgument, "x").WithArguments("M", "x").WithLocation(6, 11)); } [Fact] public void TestErrorsDoNotCascadeInArglist() { var source = @" class C { static void M() { M(__arglist(x: 1, x: 2, __arglist())); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,33): error CS0226: An __arglist expression may only appear inside of a call or new expression // M(__arglist(x: 1, x: 2, __arglist())); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist()").WithLocation(6, 33)); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void TestSimpleArglist() { var source = @" using System; class C { static void M(int x, int y, __arglist) { System.Console.Write($""{x} {y} {ArgListToString(new ArgIterator(__arglist))}. ""); } static void Main() { M(1, 2, __arglist(3, 4)); M(x: 1, 2, __arglist(5, 6)); } static string ArgListToString(ArgIterator args) { int argCount = args.GetRemainingCount(); string result = """"; for (int i = 0; i < argCount; i++) { TypedReference tr = args.GetNextArg(); result += TypedReference.ToObject(tr); } return result; } }"; var comp = CompileAndVerify(source, expectedOutput: "1 2 34. 1 2 56."); comp.VerifyDiagnostics(); } [Fact] public void TestSimpleArglistAfterOutOfPositionArg() { var source = @" class C { static void M(int x, int y, __arglist) { M(y: 1, x: 2, __arglist(3)); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,11): error CS8322: Named argument 'y' is used out-of-position but is followed by an unnamed argument // M(y: 1, x: 2, __arglist(3)); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "y").WithArguments("y").WithLocation(6, 11) ); } [Fact] public void TestErrorsDoNotCascadeInConstructorInitializer() { var source = @" class C { C() : this(x: 1, x: 2, 3) { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS1739: The best overload for '.ctor' does not have a parameter named 'x' // C() : this(x: 1, x: 2, 3) { } Diagnostic(ErrorCode.ERR_BadNamedArgument, "x").WithArguments(".ctor", "x").WithLocation(4, 16)); } [Fact] public void TestErrorsDoNotCascadeInObjectCreation() { var source = @" class C { void M() { new C(x: 1, x: 2, 3); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,15): error CS1739: The best overload for 'C' does not have a parameter named 'x' // new C(x: 1, x: 2, 3); Diagnostic(ErrorCode.ERR_BadNamedArgument, "x").WithArguments("C", "x").WithLocation(6, 15)); } [Fact] public void TestErrorsDoNotCascadeInElementAccess() { var source = @" class C { int this[int i] { get { throw null; } set { throw null; } } void M() { var c = new C(); System.Console.Write(c[x: 1, x: 2, 3]); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,32): error CS1739: The best overload for 'this' does not have a parameter named 'x' // System.Console.Write(c[x: 1, x: 2, 3]); Diagnostic(ErrorCode.ERR_BadNamedArgument, "x").WithArguments("this", "x").WithLocation(8, 32)); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { [CompilerTrait(CompilerFeature.NonTrailingNamedArgs)] public class NonTrailingNamedArgumentsTests : CompilingTestBase { [Fact] public void TestSimple() { var source = @" class C { static void M(int a, int b) { System.Console.Write($""First {a} {b}. ""); } static void M(long b, long a) { System.Console.Write($""Second {b} {a}. ""); } static void Main() { M(a: 1, 2); M(3, a: 4); } }"; var verifier = CompileAndVerify(source, expectedOutput: "First 1 2. Second 3 4.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); var tree = verifier.Compilation.SyntaxTrees.First(); var model = verifier.Compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var firstInvocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(2); Assert.Equal("M(a: 1, 2)", firstInvocation.ToString()); Assert.Equal("void C.M(System.Int32 a, System.Int32 b)", model.GetSymbolInfo(firstInvocation).Symbol.ToTestDisplayString()); var firstNamedArgA = nodes.OfType<NameColonSyntax>().ElementAt(0); Assert.Equal("a: 1", firstNamedArgA.Parent.ToString()); var firstASymbol = model.GetSymbolInfo(firstNamedArgA.Name); Assert.Equal(SymbolKind.Parameter, firstASymbol.Symbol.Kind); Assert.Equal("a", firstASymbol.Symbol.Name); Assert.Equal("void C.M(System.Int32 a, System.Int32 b)", firstASymbol.Symbol.ContainingSymbol.ToTestDisplayString()); var secondInvocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(3); Assert.Equal("M(3, a: 4)", secondInvocation.ToString()); Assert.Equal("void C.M(System.Int64 b, System.Int64 a)", model.GetSymbolInfo(secondInvocation).Symbol.ToTestDisplayString()); var secondNamedArgA = nodes.OfType<NameColonSyntax>().ElementAt(1); Assert.Equal("a: 4", secondNamedArgA.Parent.ToString()); var secondASymbol = model.GetSymbolInfo(secondNamedArgA.Name); Assert.Equal(SymbolKind.Parameter, secondASymbol.Symbol.Kind); Assert.Equal("a", secondASymbol.Symbol.Name); Assert.Equal("void C.M(System.Int64 b, System.Int64 a)", secondASymbol.Symbol.ContainingSymbol.ToTestDisplayString()); } [Fact] public void TestSimpleConstructor() { var source = @" class C { C(int a, int b) { System.Console.Write($""{a} {b}.""); } static void Main() { new C(a: 1, 2); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1 2.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics( // (10,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // new C(a: 1, 2); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(10, 21) ); } [Fact] public void TestSimpleThis() { var source = @" class C { C(int a, int b) { System.Console.Write($""{a} {b}.""); } C() : this(a: 1, 2) { } static void Main() { new C(); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1 2.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); } [Fact] public void TestSimpleBase() { var source = @" public class C { public C(int a, int b) { System.Console.Write($""{a} {b}.""); } } class Derived : C { Derived() : base(a: 1, 2) { } static void Main() { new Derived(); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1 2.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); } [Fact] public void TestSimpleExtension() { var source = @" public static class Extension { public static void M(this C c, int a, int b) { System.Console.Write($""{a} {b}.""); } } public class C { static void Main() { var c = new C(); c.M(a: 1, 2); } }"; var verifier = CompileAndVerifyWithMscorlib40(source, expectedOutput: "1 2.", parseOptions: TestOptions.Regular7_2, references: new[] { TestMetadata.Net40.SystemCore }); verifier.VerifyDiagnostics(); var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7_1, references: new[] { TestMetadata.Net40.SystemCore }); comp.VerifyDiagnostics( // (14,19): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // c.M(a: 1, 2); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(14, 19) ); } [Fact] public void TestSimpleDelegate() { var source = @" class C { delegate void MyDelegate(int a, int b); event MyDelegate e; static void M(int a, int b) { System.Console.Write($""{a} {b}. ""); } static void Main() { var c = new C(); c.e += M; c.e.Invoke(a: 1, 2); c.e(a: 1, 2); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1 2. 1 2.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics( // (16,26): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // c.e.Invoke(a: 1, 2); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(16, 26), // (17,19): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // c.e(a: 1, 2); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(17, 19) ); } [Fact] public void TestSimpleLocalFunction() { var source = @" class C { static void Main() { var c = new C(); local(a: 1, 2); void local(int a, int b) { System.Console.Write($""{a} {b}.""); } } }"; var verifier = CompileAndVerify(source, expectedOutput: "1 2.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics( // (7,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // local(a: 1, 2); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(7, 21) ); } [Fact] public void TestSimpleIndexer() { var source = @" class C { int this[int a, int b] { get { System.Console.Write($""Get {a} {b}. ""); return 0; } set { System.Console.Write($""Set {a} {b} {value}.""); } } static void Main() { var c = new C(); _ = c[a: 1, 2]; c[a: 3, 4] = 5; } }"; var verifier = CompileAndVerify(source, expectedOutput: "Get 1 2. Set 3 4 5.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics( // (19,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // _ = c[a: 1, 2]; Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(19, 21), // (20,17): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // c[a: 3, 4] = 5; Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "4").WithArguments("7.2").WithLocation(20, 17) ); } [Fact] public void TestSimpleError() { var source = @" class C { int this[int a, int b] { get { throw null; } } C(int a, int b) { } static void Main() { var c = new C(b: 1, 2); _ = c[b: 1, 2]; local(b: 1, 2); void local(int a, int b) { } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (16,23): error CS8322: Named argument 'b' is used out-of-position but is followed by an unnamed argument // var c = new C(b: 1, 2); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "b").WithArguments("b").WithLocation(16, 23), // (17,15): error CS8322: Named argument 'b' is used out-of-position but is followed by an unnamed argument // _ = c[b: 1, 2]; Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "b").WithArguments("b").WithLocation(17, 15), // (18,15): error CS8322: Named argument 'b' is used out-of-position but is followed by an unnamed argument // local(b: 1, 2); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "b").WithArguments("b").WithLocation(18, 15) ); } [Fact] public void TestMetadataAndPESymbols() { var lib_cs = @" public class C { public static void M(int a, int b) { System.Console.Write($""{a} {b}.""); } }"; var source = @" class D { static void Main() { C.M(a: 1, 2); } }"; var lib = CreateCompilation(lib_cs, parseOptions: TestOptions.Regular7); var verifier1 = CompileAndVerify(source, expectedOutput: "1 2.", parseOptions: TestOptions.Regular7_2, references: new[] { lib.ToMetadataReference() }); verifier1.VerifyDiagnostics(); var verifier2 = CompileAndVerify(source, expectedOutput: "1 2.", parseOptions: TestOptions.Regular7_2, references: new[] { lib.EmitToImageReference() }); verifier2.VerifyDiagnostics(); } [Fact] public void TestPositionalUnaffected() { var source = @" class C { static void M(int first, int other) { System.Console.Write($""{first} {other}""); } static void Main() { M(1, first: 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,14): error CS1744: Named argument 'first' specifies a parameter for which a positional argument has already been given // M(1, first: 2); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "first").WithArguments("first").WithLocation(10, 14) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(1); Assert.Equal("M(1, first: 2)", invocation.ToString()); Assert.Null(model.GetSymbolInfo(invocation).Symbol); } [Fact] public void TestGenericInference() { var source = @" class C { static void M<T1, T2>(T1 a, T2 b) { System.Console.Write($""{a} {b}.""); } static void Main() { C.M(a: 1, ""hi""); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1 hi.", parseOptions: TestOptions.Regular7_2); verifier.VerifyDiagnostics(); var tree = verifier.Compilation.SyntaxTrees.First(); var model = verifier.Compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(1); Assert.Equal(@"C.M(a: 1, ""hi"")", invocation.ToString()); Assert.Equal("void C.M<System.Int32, System.String>(System.Int32 a, System.String b)", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString()); } [Fact] public void TestPositionalUnaffected2() { var source = @" class C { static void M(int a, int b, int c = 1) { System.Console.Write($""M {a} {b}""); } static void Main() { M(c: 1, 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,11): error CS8321: Named argument 'c' is used out-of-position but is followed by an unnamed argument // M(c: 1, 2); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "c").WithArguments("c").WithLocation(10, 11) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(1); Assert.Equal("M(c: 1, 2)", invocation.ToString()); SymbolInfo symbol = model.GetSymbolInfo(invocation); AssertEx.Equal(new[] { "void C.M(System.Int32 a, System.Int32 b, [System.Int32 c = 1])" }, symbol.CandidateSymbols.Select(c => c.ToTestDisplayString())); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbol.CandidateReason); } [Fact] public void TestNamedParams() { var source = @" class C { static void M(params int[] x) { } static void Main() { M(x: 1, 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS1501: No overload for method 'M' takes 2 arguments // M(x: 1, 2); Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "2").WithLocation(9, 9) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("M(x: 1, 2)", invocation.ToString()); Assert.Null(model.GetSymbolInfo(invocation).Symbol); } [Fact] public void TestNamedParams2() { var source = @" class C { static void M(params int[] x) { } static void Main() { M(1, x: 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,14): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given // M(1, x: 2); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(9, 14) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("M(1, x: 2)", invocation.ToString()); Assert.Null(model.GetSymbolInfo(invocation).Symbol); } [Fact] public void TestNamedParamsVariousForms() { var source = @" class C { static void M(int x, params string[] y) { System.Console.Write($""{x} {string.Join("","", y)}. ""); } static void Main() { M(x: 1, y: ""2""); M(x: 2, ""3""); M(x: 3, new[] { ""4"", ""5"" }); } }"; var comp = CompileAndVerify(source, expectedOutput: "1 2. 2 3. 3 4,5."); comp.VerifyDiagnostics(); } [Fact] public void TestTwiceNamedParams() { var source = @" class C { static void M(params int[] x) { } static void Main() { M(x: 1, x: 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,17): error CS1740: Named argument 'x' cannot be specified multiple times // M(x: 1, x: 2); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "x").WithArguments("x").WithLocation(9, 17) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("M(x: 1, x: 2)", invocation.ToString()); var symbolInfo = model.GetSymbolInfo(invocation); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal("void C.M(params System.Int32[] x)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); } [Fact] public void TestTwiceNamedParamsWithOldLangVer() { var source = @" class C { static void M(int x, int y, int z) { } static void Main() { M(x: 1, x: 2, 3); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics( // (9,23): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // M(x: 1, x: 2, 3); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "3").WithArguments("7.2").WithLocation(9, 23), // (9,17): error CS8323: Named argument 'x' is used out-of-position but is followed by an unnamed argument // M(x: 1, x: 2, 3); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "x").WithArguments("x").WithLocation(9, 17)); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("M(x: 1, x: 2, 3)", invocation.ToString()); Assert.Null(model.GetSymbolInfo(invocation).Symbol); } [Fact] public void TestNamedParams3() { var source = @" class C { static void M(int x, params int[] y) { } static void Main() { M(y: 1, 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,11): error CS8321: Named argument 'y' is used out-of-position but is followed by an unnamed argument // M(y: 1, 2); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "y").WithArguments("y").WithLocation(9, 11) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("M(y: 1, 2)", invocation.ToString()); Assert.Null(model.GetSymbolInfo(invocation).Symbol); } [Fact] public void TestNamedParams4() { var source = @" class C { static void M(int x, params int[] y) { } static void Main() { M(x: 1, y: 2, 3); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS1501: No overload for method 'M' takes 3 arguments // M(x: 1, y: 2, 3); Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "3").WithLocation(9, 9) ); } [Fact] public void TestNamedInvalidParams() { var source = @" class C { static void M(params int[] x, int y) { } static void Main() { M(x: 1, 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,19): error CS0231: A params parameter must be the last parameter in a formal parameter list // static void M(params int[] x, int y) Diagnostic(ErrorCode.ERR_ParamsLast, "params int[] x").WithLocation(4, 19), // (9,14): error CS1503: Argument 1: cannot convert from 'int' to 'params int[]' // M(x: 1, 2); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "params int[]").WithLocation(9, 14) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("M(x: 1, 2)", invocation.ToString()); Assert.Null(model.GetSymbolInfo(invocation).Symbol); } [Fact] public void TestNamedParams5() { var source = @" class C { static void M(int x, params int[] y) { System.Console.Write($""x={x} y[0]={y[0]} y.Length={y.Length}""); } static void Main() { M(y: 1, x: 2); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "x=2 y[0]=1 y.Length=1"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(1); Assert.Equal("M(y: 1, x: 2)", invocation.ToString()); Assert.Equal("void C.M(System.Int32 x, params System.Int32[] y)", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString()); } [Fact] public void TestBadNonTrailing() { var source = @" class C { static void M(int a = 1, int b = 2, int c = 3) { } static void Main() { int valueB = 2; int valueC = 3; M(c: valueC, valueB); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,11): error CS8321: Named argument 'c' is used out-of-position but is followed by an unnamed argument // M(c: valueC, valueB); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "c").WithArguments("c").WithLocation(11, 11) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var firstInvocation = nodes.OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("M(c: valueC, valueB)", firstInvocation.ToString()); Assert.Null(model.GetSymbolInfo(firstInvocation).Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, model.GetSymbolInfo(firstInvocation).CandidateReason); Assert.Equal("void C.M([System.Int32 a = 1], [System.Int32 b = 2], [System.Int32 c = 3])", model.GetSymbolInfo(firstInvocation).CandidateSymbols.Single().ToTestDisplayString()); } [Fact] public void TestPickGoodOverload() { var source = @" class C { static void M(int a = 1, int b = 2, int c = 3) { } static void M(long c = 1, long b = 2) { System.Console.Write($""Second {c} {b}. ""); } static void Main() { int valueB = 2; int valueC = 3; M(c: valueC, valueB); } }"; var verifier = CompileAndVerify(source, expectedOutput: "Second 3 2."); verifier.VerifyDiagnostics(); var tree = verifier.Compilation.SyntaxTrees.First(); var model = verifier.Compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(1); Assert.Equal("M(c: valueC, valueB)", invocation.ToString()); Assert.Equal("void C.M([System.Int64 c = 1], [System.Int64 b = 2])", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString()); } [Fact] public void TestPickGoodOverload2() { var source = @" class C { static void M(long a = 1, long b = 2, long c = 3) { } static void M(int c = 1, int b = 2) { System.Console.Write($""Second {c} {b}.""); } static void Main() { int valueB = 2; int valueC = 3; M(c: valueC, valueB); } }"; var verifier = CompileAndVerify(source, expectedOutput: "Second 3 2."); verifier.VerifyDiagnostics(); var tree = verifier.Compilation.SyntaxTrees.First(); var model = verifier.Compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<InvocationExpressionSyntax>().ElementAt(1); Assert.Equal("M(c: valueC, valueB)", invocation.ToString()); Assert.Equal("void C.M([System.Int32 c = 1], [System.Int32 b = 2])", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString()); } [Fact] public void TestOptionalValues() { var source = @" class C { static void M(int a, int b, int c = 42) { System.Console.Write(c); } static void Main() { M(a: 1, 2); } }"; var comp = CompileAndVerify(source, expectedOutput: "42"); comp.VerifyDiagnostics(); } [Fact] public void TestDynamicInvocation() { var source = @" class C { void M() { dynamic d = new object(); d.M(a: 1, 2); d.M(1, 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (7,19): error CS8323: Named argument specifications must appear after all fixed arguments have been specified in a dynamic invocation. // d.M(a: 1, 2); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation, "2").WithLocation(7, 19) ); var comp2 = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp2.VerifyDiagnostics( // (7,19): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // d.M(a: 1, 2); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(7, 19) ); } [Fact] public void TestInvocationWithDynamicInLocalFunctionParams() { var source = @" class C { void M() { dynamic d = new object[] { 0 }; local(x: 1, d); void local(int x, params object[] y) { } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (7,9): error CS8108: Cannot pass argument with dynamic type to params parameter 'y' of local function 'local'. // local(x: 1, d); Diagnostic(ErrorCode.ERR_DynamicLocalFunctionParamsParameter, "local(x: 1, d)").WithArguments("y", "local").WithLocation(7, 9), // (7,21): error CS8323: Named argument specifications must appear after all fixed arguments have been specified in a dynamic invocation. // local(x: 1, d); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation, "d").WithLocation(7, 21) ); } [Fact] public void TestDynamicWhenNotInvocation() { var source = @" class C { int this[int a, int b] { get { System.Console.Write($""{a} {b}.""); return 0; } } void M(C c) { dynamic d = new object(); c[a: 1, d] = d; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void TestParams() { var source = @" class C { static void M(int a, int b, params int[] c) { } static void Main() { M(b: 2, 3, 4); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,11): error CS8321: Named argument 'b' is used out-of-position but is followed by an unnamed argument // M(b: 2, 3, 4); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "b").WithArguments("b").WithLocation(9, 11) ); } [Fact] public void TestParams2() { var source = @" class C { static void M(int a, int b, params int[] c) { System.Console.Write($""{a} {b} {c[0]} {c[1]} Length:{c.Length}""); } static void Main() { M(1, b: 2, 3, 4); } }"; var verifier = CompileAndVerify(source, expectedOutput: "1 2 3 4 Length:2"); verifier.VerifyDiagnostics(); } [Fact] public void TestInAttribute() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class MyAttribute : Attribute { public int P { get; set; } public MyAttribute(bool condition, int other) { } } [MyAttribute(condition: true, 42)] [MyAttribute(condition: true, P = 1, 42)] [MyAttribute(42, condition: true)] public class C { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,38): error CS1016: Named attribute argument expected // [MyAttribute(condition: true, P = 1, 42)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "42").WithLocation(12, 38), // (13,18): error CS1744: Named argument 'condition' specifies a parameter for which a positional argument has already been given // [MyAttribute(42, condition: true)] Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "condition").WithArguments("condition").WithLocation(13, 18) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation = nodes.OfType<AttributeSyntax>().ElementAt(1); Assert.Equal("MyAttribute(condition: true, 42)", invocation.ToString()); Assert.Equal("MyAttribute..ctor(System.Boolean condition, System.Int32 other)", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString()); } [Fact] public void TestInAttributeWithOldLangVersion() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class MyAttribute : Attribute { public int P { get; set; } public MyAttribute(bool condition, int other) { } } [MyAttribute(condition: true, 42)] [MyAttribute(condition: true, P = 1, 42)] [MyAttribute(42, condition: true)] public class C { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics( // (11,31): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // [MyAttribute(condition: true, 42)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "42").WithArguments("7.2").WithLocation(11, 31), // (12,38): error CS1016: Named attribute argument expected // [MyAttribute(condition: true, P = 1, 42)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "42").WithLocation(12, 38), // (12,38): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // [MyAttribute(condition: true, P = 1, 42)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "42").WithArguments("7.2").WithLocation(12, 38), // (13,18): error CS1744: Named argument 'condition' specifies a parameter for which a positional argument has already been given // [MyAttribute(42, condition: true)] Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "condition").WithArguments("condition").WithLocation(13, 18) ); } [Fact] public void TestInAttribute2() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class MyAttribute : Attribute { public int P { get; set; } public MyAttribute(int a = 1, int b = 2, int c = 3) { } } [MyAttribute(c:3, 2)] [MyAttribute(P=1, c:3, 2)] public class C { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,14): error CS8321: Named argument 'c' is used out-of-position but is followed by an unnamed argument // [MyAttribute(c:3, 2)] Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "c").WithArguments("c").WithLocation(11, 14), // (12,21): error CS1016: Named attribute argument expected // [MyAttribute(P=1, c:3, 2)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "3").WithLocation(12, 21), // (12,24): error CS1016: Named attribute argument expected // [MyAttribute(P=1, c:3, 2)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "2").WithLocation(12, 24), // (12,19): error CS8321: Named argument 'c' is used out-of-position but is followed by an unnamed argument // [MyAttribute(P=1, c:3, 2)] Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "c").WithArguments("c").WithLocation(12, 19) ); } [Fact] public void TestErrorsDoNotCascadeInInvocation() { var source = @" class C { static void M() { M(x: 1, x: 2, __arglist()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,11): error CS1739: The best overload for 'M' does not have a parameter named 'x' // M(x: 1, x: 2, __arglist()); Diagnostic(ErrorCode.ERR_BadNamedArgument, "x").WithArguments("M", "x").WithLocation(6, 11)); } [Fact] public void TestErrorsDoNotCascadeInArglist() { var source = @" class C { static void M() { M(__arglist(x: 1, x: 2, __arglist())); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,33): error CS0226: An __arglist expression may only appear inside of a call or new expression // M(__arglist(x: 1, x: 2, __arglist())); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist()").WithLocation(6, 33)); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void TestSimpleArglist() { var source = @" using System; class C { static void M(int x, int y, __arglist) { System.Console.Write($""{x} {y} {ArgListToString(new ArgIterator(__arglist))}. ""); } static void Main() { M(1, 2, __arglist(3, 4)); M(x: 1, 2, __arglist(5, 6)); } static string ArgListToString(ArgIterator args) { int argCount = args.GetRemainingCount(); string result = """"; for (int i = 0; i < argCount; i++) { TypedReference tr = args.GetNextArg(); result += TypedReference.ToObject(tr); } return result; } }"; var comp = CompileAndVerify(source, expectedOutput: "1 2 34. 1 2 56."); comp.VerifyDiagnostics(); } [Fact] public void TestSimpleArglistAfterOutOfPositionArg() { var source = @" class C { static void M(int x, int y, __arglist) { M(y: 1, x: 2, __arglist(3)); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,11): error CS8322: Named argument 'y' is used out-of-position but is followed by an unnamed argument // M(y: 1, x: 2, __arglist(3)); Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "y").WithArguments("y").WithLocation(6, 11) ); } [Fact] public void TestErrorsDoNotCascadeInConstructorInitializer() { var source = @" class C { C() : this(x: 1, x: 2, 3) { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS1739: The best overload for '.ctor' does not have a parameter named 'x' // C() : this(x: 1, x: 2, 3) { } Diagnostic(ErrorCode.ERR_BadNamedArgument, "x").WithArguments(".ctor", "x").WithLocation(4, 16)); } [Fact] public void TestErrorsDoNotCascadeInObjectCreation() { var source = @" class C { void M() { new C(x: 1, x: 2, 3); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,15): error CS1739: The best overload for 'C' does not have a parameter named 'x' // new C(x: 1, x: 2, 3); Diagnostic(ErrorCode.ERR_BadNamedArgument, "x").WithArguments("C", "x").WithLocation(6, 15)); } [Fact] public void TestErrorsDoNotCascadeInElementAccess() { var source = @" class C { int this[int i] { get { throw null; } set { throw null; } } void M() { var c = new C(); System.Console.Write(c[x: 1, x: 2, 3]); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,32): error CS1739: The best overload for 'this' does not have a parameter named 'x' // System.Console.Write(c[x: 1, x: 2, 3]); Diagnostic(ErrorCode.ERR_BadNamedArgument, "x").WithArguments("this", "x").WithLocation(8, 32)); } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisResult.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 Microsoft.CodeAnalysis.Diagnostics.Telemetry; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Stores the results of analyzer execution: /// 1. Local and non-local diagnostics, per-analyzer. /// 2. Analyzer execution times, if requested. /// </summary> public class AnalysisResult { internal AnalysisResult( ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableDictionary<SyntaxTree, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>> localSyntaxDiagnostics, ImmutableDictionary<SyntaxTree, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>> localSemanticDiagnostics, ImmutableDictionary<AdditionalText, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>> localAdditionalFileDiagnostics, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>> nonLocalDiagnostics, ImmutableDictionary<DiagnosticAnalyzer, AnalyzerTelemetryInfo> analyzerTelemetryInfo) { Analyzers = analyzers; SyntaxDiagnostics = localSyntaxDiagnostics; SemanticDiagnostics = localSemanticDiagnostics; AdditionalFileDiagnostics = localAdditionalFileDiagnostics; CompilationDiagnostics = nonLocalDiagnostics; AnalyzerTelemetryInfo = analyzerTelemetryInfo; } /// <summary> /// Analyzers corresponding to this analysis result. /// </summary> public ImmutableArray<DiagnosticAnalyzer> Analyzers { get; } /// <summary> /// Syntax diagnostics reported by the <see cref="Analyzers"/>. /// </summary> public ImmutableDictionary<SyntaxTree, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>> SyntaxDiagnostics { get; } /// <summary> /// Semantic diagnostics reported by the <see cref="Analyzers"/>. /// </summary> public ImmutableDictionary<SyntaxTree, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>> SemanticDiagnostics { get; } /// <summary> /// Diagnostics in additional files reported by the <see cref="Analyzers"/>. /// </summary> public ImmutableDictionary<AdditionalText, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>> AdditionalFileDiagnostics { get; } /// <summary> /// Compilation diagnostics reported by the <see cref="Analyzers"/>. /// </summary> public ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>> CompilationDiagnostics { get; } /// <summary> /// Analyzer telemetry info (register action counts and execution times). /// </summary> public ImmutableDictionary<DiagnosticAnalyzer, AnalyzerTelemetryInfo> AnalyzerTelemetryInfo { get; } /// <summary> /// Gets all the diagnostics reported by the given <paramref name="analyzer"/>. /// </summary> public ImmutableArray<Diagnostic> GetAllDiagnostics(DiagnosticAnalyzer analyzer) { if (!Analyzers.Contains(analyzer)) { throw new ArgumentException(CodeAnalysisResources.UnsupportedAnalyzerInstance, nameof(analyzer)); } return GetDiagnostics(SpecializedCollections.SingletonEnumerable(analyzer)); } /// <summary> /// Gets all the diagnostics reported by all the <see cref="Analyzers"/>. /// </summary> public ImmutableArray<Diagnostic> GetAllDiagnostics() { return GetDiagnostics(Analyzers); } private ImmutableArray<Diagnostic> GetDiagnostics(IEnumerable<DiagnosticAnalyzer> analyzers) { var excludedAnalyzers = Analyzers.Except(analyzers); var excludedAnalyzersSet = excludedAnalyzers.Any() ? excludedAnalyzers.ToImmutableHashSet() : ImmutableHashSet<DiagnosticAnalyzer>.Empty; return GetDiagnostics(excludedAnalyzersSet); } private ImmutableArray<Diagnostic> GetDiagnostics(ImmutableHashSet<DiagnosticAnalyzer> excludedAnalyzers) { if (SyntaxDiagnostics.Count > 0 || SemanticDiagnostics.Count > 0 || AdditionalFileDiagnostics.Count > 0 || CompilationDiagnostics.Count > 0) { var builder = ImmutableArray.CreateBuilder<Diagnostic>(); AddLocalDiagnostics(SyntaxDiagnostics, excludedAnalyzers, builder); AddLocalDiagnostics(SemanticDiagnostics, excludedAnalyzers, builder); AddLocalDiagnostics(AdditionalFileDiagnostics, excludedAnalyzers, builder); AddNonLocalDiagnostics(CompilationDiagnostics, excludedAnalyzers, builder); return builder.ToImmutable(); } return ImmutableArray<Diagnostic>.Empty; } private static void AddLocalDiagnostics<T>( ImmutableDictionary<T, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>> localDiagnostics, ImmutableHashSet<DiagnosticAnalyzer> excludedAnalyzers, ImmutableArray<Diagnostic>.Builder builder) where T : notnull { foreach (var diagnosticsByTree in localDiagnostics) { foreach (var diagnosticsByAnalyzer in diagnosticsByTree.Value) { if (excludedAnalyzers.Contains(diagnosticsByAnalyzer.Key)) { continue; } builder.AddRange(diagnosticsByAnalyzer.Value); } } } private static void AddNonLocalDiagnostics( ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>> nonLocalDiagnostics, ImmutableHashSet<DiagnosticAnalyzer> excludedAnalyzers, ImmutableArray<Diagnostic>.Builder builder) { foreach (var diagnosticsByAnalyzer in nonLocalDiagnostics) { if (excludedAnalyzers.Contains(diagnosticsByAnalyzer.Key)) { continue; } builder.AddRange(diagnosticsByAnalyzer.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.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics.Telemetry; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Stores the results of analyzer execution: /// 1. Local and non-local diagnostics, per-analyzer. /// 2. Analyzer execution times, if requested. /// </summary> public class AnalysisResult { internal AnalysisResult( ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableDictionary<SyntaxTree, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>> localSyntaxDiagnostics, ImmutableDictionary<SyntaxTree, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>> localSemanticDiagnostics, ImmutableDictionary<AdditionalText, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>> localAdditionalFileDiagnostics, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>> nonLocalDiagnostics, ImmutableDictionary<DiagnosticAnalyzer, AnalyzerTelemetryInfo> analyzerTelemetryInfo) { Analyzers = analyzers; SyntaxDiagnostics = localSyntaxDiagnostics; SemanticDiagnostics = localSemanticDiagnostics; AdditionalFileDiagnostics = localAdditionalFileDiagnostics; CompilationDiagnostics = nonLocalDiagnostics; AnalyzerTelemetryInfo = analyzerTelemetryInfo; } /// <summary> /// Analyzers corresponding to this analysis result. /// </summary> public ImmutableArray<DiagnosticAnalyzer> Analyzers { get; } /// <summary> /// Syntax diagnostics reported by the <see cref="Analyzers"/>. /// </summary> public ImmutableDictionary<SyntaxTree, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>> SyntaxDiagnostics { get; } /// <summary> /// Semantic diagnostics reported by the <see cref="Analyzers"/>. /// </summary> public ImmutableDictionary<SyntaxTree, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>> SemanticDiagnostics { get; } /// <summary> /// Diagnostics in additional files reported by the <see cref="Analyzers"/>. /// </summary> public ImmutableDictionary<AdditionalText, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>> AdditionalFileDiagnostics { get; } /// <summary> /// Compilation diagnostics reported by the <see cref="Analyzers"/>. /// </summary> public ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>> CompilationDiagnostics { get; } /// <summary> /// Analyzer telemetry info (register action counts and execution times). /// </summary> public ImmutableDictionary<DiagnosticAnalyzer, AnalyzerTelemetryInfo> AnalyzerTelemetryInfo { get; } /// <summary> /// Gets all the diagnostics reported by the given <paramref name="analyzer"/>. /// </summary> public ImmutableArray<Diagnostic> GetAllDiagnostics(DiagnosticAnalyzer analyzer) { if (!Analyzers.Contains(analyzer)) { throw new ArgumentException(CodeAnalysisResources.UnsupportedAnalyzerInstance, nameof(analyzer)); } return GetDiagnostics(SpecializedCollections.SingletonEnumerable(analyzer)); } /// <summary> /// Gets all the diagnostics reported by all the <see cref="Analyzers"/>. /// </summary> public ImmutableArray<Diagnostic> GetAllDiagnostics() { return GetDiagnostics(Analyzers); } private ImmutableArray<Diagnostic> GetDiagnostics(IEnumerable<DiagnosticAnalyzer> analyzers) { var excludedAnalyzers = Analyzers.Except(analyzers); var excludedAnalyzersSet = excludedAnalyzers.Any() ? excludedAnalyzers.ToImmutableHashSet() : ImmutableHashSet<DiagnosticAnalyzer>.Empty; return GetDiagnostics(excludedAnalyzersSet); } private ImmutableArray<Diagnostic> GetDiagnostics(ImmutableHashSet<DiagnosticAnalyzer> excludedAnalyzers) { if (SyntaxDiagnostics.Count > 0 || SemanticDiagnostics.Count > 0 || AdditionalFileDiagnostics.Count > 0 || CompilationDiagnostics.Count > 0) { var builder = ImmutableArray.CreateBuilder<Diagnostic>(); AddLocalDiagnostics(SyntaxDiagnostics, excludedAnalyzers, builder); AddLocalDiagnostics(SemanticDiagnostics, excludedAnalyzers, builder); AddLocalDiagnostics(AdditionalFileDiagnostics, excludedAnalyzers, builder); AddNonLocalDiagnostics(CompilationDiagnostics, excludedAnalyzers, builder); return builder.ToImmutable(); } return ImmutableArray<Diagnostic>.Empty; } private static void AddLocalDiagnostics<T>( ImmutableDictionary<T, ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>> localDiagnostics, ImmutableHashSet<DiagnosticAnalyzer> excludedAnalyzers, ImmutableArray<Diagnostic>.Builder builder) where T : notnull { foreach (var diagnosticsByTree in localDiagnostics) { foreach (var diagnosticsByAnalyzer in diagnosticsByTree.Value) { if (excludedAnalyzers.Contains(diagnosticsByAnalyzer.Key)) { continue; } builder.AddRange(diagnosticsByAnalyzer.Value); } } } private static void AddNonLocalDiagnostics( ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>> nonLocalDiagnostics, ImmutableHashSet<DiagnosticAnalyzer> excludedAnalyzers, ImmutableArray<Diagnostic>.Builder builder) { foreach (var diagnosticsByAnalyzer in nonLocalDiagnostics) { if (excludedAnalyzers.Contains(diagnosticsByAnalyzer.Key)) { continue; } builder.AddRange(diagnosticsByAnalyzer.Value); } } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.FormattedComplexTrivia.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.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal partial class TriviaDataFactory { private class FormattedComplexTrivia : TriviaDataWithList { private readonly CSharpTriviaFormatter _formatter; private readonly IList<TextChange> _textChanges; public FormattedComplexTrivia( FormattingContext context, ChainedFormattingRules formattingRules, SyntaxToken token1, SyntaxToken token2, int lineBreaks, int spaces, string originalString, CancellationToken cancellationToken) : base(context.Options, LanguageNames.CSharp) { Contract.ThrowIfNull(context); Contract.ThrowIfNull(formattingRules); Contract.ThrowIfNull(originalString); this.LineBreaks = Math.Max(0, lineBreaks); this.Spaces = Math.Max(0, spaces); _formatter = new CSharpTriviaFormatter(context, formattingRules, token1, token2, originalString, this.LineBreaks, this.Spaces); _textChanges = _formatter.FormatToTextChanges(cancellationToken); } public override bool TreatAsElastic { get { return false; } } public override bool IsWhitespaceOnlyTrivia { get { return false; } } public override bool ContainsChanges { get { return _textChanges.Count > 0; } } public override IEnumerable<TextChange> GetTextChanges(TextSpan span) => _textChanges; public override SyntaxTriviaList GetTriviaList(CancellationToken cancellationToken) => _formatter.FormatToSyntaxTrivia(cancellationToken); public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules) => throw new NotImplementedException(); public override TriviaData WithLine(int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) => throw new NotImplementedException(); public override TriviaData WithIndentation(int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) => throw new NotImplementedException(); public override void Format(FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) => 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. using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal partial class TriviaDataFactory { private class FormattedComplexTrivia : TriviaDataWithList { private readonly CSharpTriviaFormatter _formatter; private readonly IList<TextChange> _textChanges; public FormattedComplexTrivia( FormattingContext context, ChainedFormattingRules formattingRules, SyntaxToken token1, SyntaxToken token2, int lineBreaks, int spaces, string originalString, CancellationToken cancellationToken) : base(context.Options, LanguageNames.CSharp) { Contract.ThrowIfNull(context); Contract.ThrowIfNull(formattingRules); Contract.ThrowIfNull(originalString); this.LineBreaks = Math.Max(0, lineBreaks); this.Spaces = Math.Max(0, spaces); _formatter = new CSharpTriviaFormatter(context, formattingRules, token1, token2, originalString, this.LineBreaks, this.Spaces); _textChanges = _formatter.FormatToTextChanges(cancellationToken); } public override bool TreatAsElastic { get { return false; } } public override bool IsWhitespaceOnlyTrivia { get { return false; } } public override bool ContainsChanges { get { return _textChanges.Count > 0; } } public override IEnumerable<TextChange> GetTextChanges(TextSpan span) => _textChanges; public override SyntaxTriviaList GetTriviaList(CancellationToken cancellationToken) => _formatter.FormatToSyntaxTrivia(cancellationToken); public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules) => throw new NotImplementedException(); public override TriviaData WithLine(int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) => throw new NotImplementedException(); public override TriviaData WithIndentation(int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) => throw new NotImplementedException(); public override void Format(FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) => throw new NotImplementedException(); } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/ExtractMethod/FailedExtractMethodResult.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.ExtractMethod { internal class FailedExtractMethodResult : ExtractMethodResult { public FailedExtractMethodResult(OperationStatus status) : base(status.Flag, status.Reasons, null, default, 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. #nullable disable namespace Microsoft.CodeAnalysis.ExtractMethod { internal class FailedExtractMethodResult : ExtractMethodResult { public FailedExtractMethodResult(OperationStatus status) : base(status.Flag, status.Reasons, null, default, null) { } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Symbol/Compilation/QueryClauseInfoTests.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 Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp { public class QueryClauseInfoTests : CSharpTestBase { [Fact] public void Equality() { var c = (Compilation)CreateCompilation(""); var obj = c.GetSpecialType(SpecialType.System_Object); var int32 = c.GetSpecialType(SpecialType.System_Int32); EqualityTesting.AssertEqual(default(QueryClauseInfo), default(QueryClauseInfo)); EqualityTesting.AssertEqual( new QueryClauseInfo( new SymbolInfo(obj, ImmutableArray.Create<ISymbol>(obj, int32), CandidateReason.Inaccessible), new SymbolInfo(obj, ImmutableArray.Create<ISymbol>(obj, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(obj, ImmutableArray.Create<ISymbol>(obj, int32), CandidateReason.Inaccessible), new SymbolInfo(obj, ImmutableArray.Create<ISymbol>(obj, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(obj, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(obj, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(obj, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(obj, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, obj), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(obj, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, obj), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Ambiguous), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Ambiguous)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp { public class QueryClauseInfoTests : CSharpTestBase { [Fact] public void Equality() { var c = (Compilation)CreateCompilation(""); var obj = c.GetSpecialType(SpecialType.System_Object); var int32 = c.GetSpecialType(SpecialType.System_Int32); EqualityTesting.AssertEqual(default(QueryClauseInfo), default(QueryClauseInfo)); EqualityTesting.AssertEqual( new QueryClauseInfo( new SymbolInfo(obj, ImmutableArray.Create<ISymbol>(obj, int32), CandidateReason.Inaccessible), new SymbolInfo(obj, ImmutableArray.Create<ISymbol>(obj, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(obj, ImmutableArray.Create<ISymbol>(obj, int32), CandidateReason.Inaccessible), new SymbolInfo(obj, ImmutableArray.Create<ISymbol>(obj, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(obj, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(obj, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(obj, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(obj, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, obj), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(obj, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, obj), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Ambiguous), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); EqualityTesting.AssertNotEqual( new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Ambiguous)), new QueryClauseInfo( new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible), new SymbolInfo(int32, ImmutableArray.Create<ISymbol>(int32, int32), CandidateReason.Inaccessible))); } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Analyzers/Core/Analyzers/AbstractParenthesesDiagnosticAnalyzer.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 Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Precedence; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses { internal abstract class AbstractParenthesesDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { protected AbstractParenthesesDiagnosticAnalyzer( string descriptorId, EnforceOnBuild enforceOnBuild, LocalizableString title, LocalizableString message, bool isUnnecessary = false) : base(descriptorId, enforceOnBuild, options: ImmutableHashSet.Create<IPerLanguageOption>(CodeStyleOptions2.ArithmeticBinaryParentheses, CodeStyleOptions2.RelationalBinaryParentheses, CodeStyleOptions2.OtherBinaryParentheses, CodeStyleOptions2.OtherParentheses), title, message, isUnnecessary: isUnnecessary) { } protected static PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> GetLanguageOption(PrecedenceKind precedenceKind) { switch (precedenceKind) { case PrecedenceKind.Arithmetic: case PrecedenceKind.Shift: case PrecedenceKind.Bitwise: return CodeStyleOptions2.ArithmeticBinaryParentheses; case PrecedenceKind.Relational: case PrecedenceKind.Equality: return CodeStyleOptions2.RelationalBinaryParentheses; case PrecedenceKind.Logical: case PrecedenceKind.Coalesce: return CodeStyleOptions2.OtherBinaryParentheses; case PrecedenceKind.Other: return CodeStyleOptions2.OtherParentheses; } throw ExceptionUtilities.UnexpectedValue(precedenceKind); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Precedence; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses { internal abstract class AbstractParenthesesDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { protected AbstractParenthesesDiagnosticAnalyzer( string descriptorId, EnforceOnBuild enforceOnBuild, LocalizableString title, LocalizableString message, bool isUnnecessary = false) : base(descriptorId, enforceOnBuild, options: ImmutableHashSet.Create<IPerLanguageOption>(CodeStyleOptions2.ArithmeticBinaryParentheses, CodeStyleOptions2.RelationalBinaryParentheses, CodeStyleOptions2.OtherBinaryParentheses, CodeStyleOptions2.OtherParentheses), title, message, isUnnecessary: isUnnecessary) { } protected static PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> GetLanguageOption(PrecedenceKind precedenceKind) { switch (precedenceKind) { case PrecedenceKind.Arithmetic: case PrecedenceKind.Shift: case PrecedenceKind.Bitwise: return CodeStyleOptions2.ArithmeticBinaryParentheses; case PrecedenceKind.Relational: case PrecedenceKind.Equality: return CodeStyleOptions2.RelationalBinaryParentheses; case PrecedenceKind.Logical: case PrecedenceKind.Coalesce: return CodeStyleOptions2.OtherBinaryParentheses; case PrecedenceKind.Other: return CodeStyleOptions2.OtherParentheses; } throw ExceptionUtilities.UnexpectedValue(precedenceKind); } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./docs/wiki/images/fig8.png
PNG  IHDR(© sRGBgAMA a pHYsodY0IDATx^ߏו5ZM<΃<j/q<X7v89fFBܣ$[808%IdwuԩbH*r/޵>Od?u;,Ұſ4Q1;Q$m _?`tp&:}qDv^޻v/D$Xnb->rgsp =#]|_c?>kn1-J0_|-ư-l?=,KXv_gtݿE[Vt7:~'jEřݼ|͛pNG'Iwo}{I1fؖݟ0;p@pxX?yxD// v؆ǃ=}0DhS+0$ww#zG' ùpWµckOyؘѕI!adw|M,UF7b*c\Aki"cQecdwz!g' NnkЉ~޽{c+WE JVgmsC-uC6T .u 1EQxH7f.Za"_/(m1Mw1c|фsmܼw{!"M2yOnjg8>6e$Ȍ%>6)b~w>F;v{8<NĶۈ/KZJwv،zp`s7? r ) Fr~r@%c}͐-Enp4,w@S[mlq'3>R9˄@+[p+Z. V;hBT~8ubV;_ FvQo`_<v[c8VWVPw[]!8gMlk6"-8~_`A_a̓m:M%9M2|"pvSi 0#Џn7<G`pupEarE,+֣5ڣ &.s5l߼==Lr69Ϟ$@[t]T/,.K p2Dtt͛Hw2I?6wk_ruN<p%hb1:xXʫCzhSQYwǢCBg}Kݏs'| #N4gpWOT/ѕE]ѕ~s'!  ?,?ZnICQw!>]+>io駺K5hv(>ȄFzzaH|IbDH1duakKZ;3lbzң&;ʎ. >1|}!T6{=9{>$D.#:D ڛjGOC 83Dpx0p[%( "q)CEGC=t;;XiK}*Gw~U]w,<&E)8|=郾]k$CM{І{,W~Ieq;uW',C{І+H%0hO| }R;q)wX$6 x(9^'vw*E :/06Wpa,RQO֧|,Jͫ@M7ڝW;їk?<ǒ>Âꕜs^_7\ ܉77f⸈rGns8ʒ廧1(JA3Uљ'OaXorSH#S2XmGԈ,݈ThnG^m5B: jxsF9?_*~uz|R_6}J(UŖ +[39@rՈdb rʌʟW;@SKp7~5=]ֿ/.Sb$썯K;Z9 -;F~+_gGQ|Hp K@j:DLXEڤiOO a(+OG? NFQ$s^x4Y ˗;9L<O4+Dž;tr~ tFVa҂i. 11Gd$B[-:PڂkKҧƏ+vcW 3m%7c> klpO8!ow[V^ktA+"1$Dp>pd! g GFWci`(-@M#*:GݣhwSCܭo$#b-°]T9T3VDs*|RY*:h^ XxX2s^6bT\Zg^)뷼KrN-OzR] ?υt 妽gˆB^CM_ٓb(166674%&+gA-ݠg(ףoYŘ`p> vm8;mQpJi|}$ףc44 FܥC_[.=I+9wzr({ 8֓dG»"UP$FӓM}hף-1JkQ5r"xT?(a}U }m1,Ù}][,Dk-O(*i&!AFҡLH:=[<V0g)E l@Wt8Ӑ^625e.>h%>ǚ+*t&H2v&TsLBt?VGx9#,n!uiIqqיaMrY}< / 4Ϝ4.8BUGC{WgԠnIEZ\)/m yUon&-spa62̽d:Df7itd1{X%?ủFc'Ĺ`)c?`)wEmPyVxTu_ޗ Gv: ˃3QtJ~zn}G/qd{P$䷟^d2|b/9_^'%?g^pd(x-DO׿ >4[`:|i/w;  q|w?~OU7&:C?SU6{UimY& MU&켌Gv!#)-:.+cS9a_Kt.`)#;. 9ɎWU,V1K]#7rFqG,koo}ŲlJ/T7_!@lHp:thU E4Y9#8K +7o޼|4*,cvdsD͂ӑzV07@]ҷ^xxF|!a|wI+XoܑFXQۦ+^N0?}r/^=Xl0YYK+\VF6B>C1 4C~ .[ow (Ѓ] ʓP1nrȺ|OγѨu2RzCXʐvl10F5StRks蛌Ù[x{V;/2aJH943ArUmPo(Y7kOʵ>>@FD8Q8cFԩSnd2^Vwg?TҏJ&#[Y2&DOQ]8#Hy6ܑsiN@@>pdJ@>$}=$7NvRC+*捬 7:]X0yK%Vqd#;i<L9roFh[s#OSZIÔ#ۉ2:]lݏ:w4XOX#4@3q޽ӧzz3Øld! <Cȶw#+Oa藹8HWȌ{X0ndeYC.|CƿG ~Ъbi`2wo;qNk),0)IhG~o±U}mjFVvge&'9+3\809GFV F{[z-Cj /G0^zU=>c*1Kud( evT,0;BߪDGVB_GtQZ%:i*PFȎ]4tdeCa[7//<.G舌]~, :.On&O?m>̭/ Y_4?ѯz}mF68>+Q'OtvZ4Wg0jocYpe Vt,Ӑϯ{`AUM!qb)WZkcTg1u zROFmo0,L_f4-:/@r  _hA_X]2ډpv{oKm~"9p5cY}T&*(F:Y:0Qa3^| GCzD| V0U 0kZ5o4Lg+e6@2  clm7R1S}!;5,fx<<nV"~0*(9yKd{* 1WTα6*F+ z|RUB_FJkcqd<q% Shs#ܠӱLqw@&ٻeo#_~@@V]OށJ!c*Б+4b\ۻ"HUi|r8K]T"YΤ c*62*!c*H!].T4Vydݳ!h()VwC{3 t,X 5YX#[z}턯~][O+:]|G24:@N=tZĀ*@I@D*(Ș Lޘ4+;wpzX :jWw/NG(Z.=žߥ(B 8Ob|!c*3XbPZC2XHaE @?+"y:JxhA)accAKJPaSeVӑm:j:n& H _.8ENvOP("=E& )᧟,qd|F* FGҁVӑd+s6̑53k)k'5<!z;kWz;X;BJS/dbN4\Sbo8to|v -97ًg{s<< g@?%kjq4%?@yJx`?8q۩-OАAd ›r3 Z1:5<_?%?xvѸ*Ի\u0׀Z( ?s)a f kܺQkϼ%,0w巪`S3c~_mlYNEvjy*{;{KŬ54>k׉Y@Z=lh=c,]\r;HsmlK v=W.\Y9=kG 1v]o_RZ# #Yȧ\Khw+g/ %{ک!_X[Cd!S=%V.]&OitBZ|>]",>DSk|4rٓX=D6bJY츬d-K^/ɥFґ8>c.&ee`biy=!da R,O=K$|B_ҕ—v=Kֿ7M] ؼv fT$IxG>?FPy=q oÏz;Só/VK2.`m0=;BH\^#/XY}"(|\>8K Y "GЧ_11k Mm4cm)SA~$ѕ<Hrnk48Y("?6=׿u]a8/IHVޥV|,U)_e2 ⻈XہX=kל ՕBue`54 fMͨPv] *\ {sL47 8H|d|lj¤+>z'X>}߉ v]kOOM s's,q/ŁEwn1+k}ӧO˺ udʿ/.mȡ2̱֯+ݧ|u󘩀iV fk?@X`</cyǯF&LDx@Yˤ`pND;_Lh AYU!S&, -LͰy*֎H 1_я844T@;U$`|OWM`&mj*!H*@Mml2[u쑥!^QK &nbHתUݻB20 :KjЪr.tÓcѬmE²=ɲ߿DD;qkw :a'Nj%MN~_ P|3@y6@X}+mubgeAӟh(iv"`8QG'jbRAQlFTZ# emF Y AJim{{-77E؇rS}"m Z6Pّ`ؤZ !tb[[*iXR|\&[ W.[nǐ`X:ӤG0HybЛ9vm>|~*LX+ljB!8o ZMxTڋÃUPӑUZM֐7Y K.W-o>XY kݥ0p#YH&3M> F7<;C(ܚX[ڰvoX4{U^ RKayѼ1LY8Y/C)Y>k䥟Lfo0?(୼ SoyOsa3"Z{$`zW{[d($*u\ml£lml ysʎ[d+ huѧ"i_ ˃ 6o?- 0e*b%KtukvjZ|66%MNees}0_^_^_߱:o1JyoXk}K1keu~Wb8%`]" |Y[k1J0.EHhgrd>:)n#2JlѠ鯾ayއ<vˈ{ߦ/mYRD ;;XP ׆dPJ@.⍒8=ßZW G|Aj%l-α6P&+&˸}{9VYMe`cf  )Ah'~xJ]ŝkT}K˴C^ۑ^a8%P !Z.0Jj84xFa5g\`8%`%B߰<ؼ%B߰<k??.fta4tΊM@fM_s+~нF45fcsxcm]7ɔ{F7[F3O=aKugbF4 .v8(Pt̒3q9oXEgeR& kmpVtX7ԖՍ2)qg),4VA,Z<oXEyoXE0.X[coXEHv3?5 PCn$vܔt x)7,!kY R-}F:tGAhGqGB#$yZqOܾ يśmyYچPJf#e 8cO~PF6]"y0XD(#0(:19vyw=ꐏ-mu]/#A+֗ RK22cX dI%~i}f-I\XJ RK224`8%f-#gs[xNrxN"kkzz- [q@ʎ 0~#M)eb{ edl^[@kV!R\BKgJ#A/O$zׯHqmM*ypMc70JXHQPFazbn^itXT:|iώJCd-tqLi>}3!1<Z<1Fv#& K&'YohQn wo)G4 U8 B3X !$R+HVku< MgZCVc05<&SFgLn|wDNB}ό:@ڧS`¤pΓdfۗ3-95򣲆Xa7pg}֖ffM1Y(k0#bŝWjxWtfmefkMj n8 o?nN\l)T<=2!DDglG_r֋sVn[:ӥ/Ro<Gl0}C¨G`΍Pu߂*%~e Nge уwOH7@A0O,(H6. ⹔:[pj '<[pAkYBP( ^=O[A?V'2+v:QY8Q q> 't솷m00A^^ւOB#GuPCMXa( CiX.eAoy_(n i 1e9V) $x)kPz;,x G$Bstf4 bY%uqݸOYTOW `R'YW9DA9C){gNAXy-^pI>k]onc0EXƬ’ <Y}㉄d 8k9B FEr<)X=˥le)[ssRk }`Veffm[LYCcPUQR{5yW)6ɻK{ LX޿}%>IҶ:GHY]P{Sŋo2FXnGDs˒ *v)+4~%"+,1ub6EvԦ9 z6B\Gȫu4\;nM`]4FX*KDۘyOm>IY~=n]/~PW_yeOG'Aj,Deů){m?tTo&-jNcʊPM,}P}uS -yJf?~`9kPVg/"8QtW^4ӯyMWe1eWފ{c-DGf'UcHfK|PdtZgD(|./]) $FN -y7ӑa,) eHq+J)ѥPS/5ʎTYdcʎXhTBٟx`w<v0sxX>Oec/J^ <s{u%)kŔ-y`og7h (BHَew"{ X: y[/ ?~/j8p_&Wr}?8fy(hpNٯ1?!lC+\ #:1Z<{pϥ,VW+%Q06ժ,**dlaS (^x(^p*Ho}_iU0edMGY24PHYA e ,( e F(K(OY=q8 tp4)Yq{}]>F^ Q}g_~e]a@;Ci )VLy;BR7,{I-h>rϲ20r) >}ze 2*2IZ)KGiI)uK=Z e Y^|ԩS_W|s` d"˸HH2ieA t;]*EAXHՀQS֜ -Jrl :cY[sa0 ŒY4T >hSʵ^vG(O~TQ6"=z>pSK`b\&&UrbY͗ԇYYJ%*;>IGby"(ҧ_{>SO<,y8z>J#AjPbmF}衇c:pTjˉ|$5ˇr2=d=vr-|1Ɂ^=)_/[!];NQk'XAEgr헎XbWw 16cVʂ_uA#JJ/ﰫF8SV x|,U7QEA&˘+v`Y*+}8#h9ʾ?=p‰/ g!eeUn1eO83@),E /.|_rx^]G8X$5.՝#U$24T>*4>}tیf~9:XWV|2UhʘBA16ٔ]gTKQⷷ>YF٦bY]:MQP9eoݺJ2qr`@w2pUd6,KD䀮mݥ:(Kw]) ξmE)ޣPKa8JZ[? MMʁ>˭u*di'VyPի)e,ئ>VP2bxKo]}MX- Ykud(K>_%_GQl*~ (p'.H[J*K_Z *xvdW*Ef*[bu0֐(0MORV&lho,( ,;\$_Y+ l~K߿ˏ ǑZC9\@Nv߿ghN)i2/e @ma-AV4@\B0q|F96>% ;wOjչۊ)Meܹs޽>P6N4(~'~&A[l5sU,BYd 2c }BxbA5AD*xRߥ&" BYQeZuI>E dD1CY0*Sȥ,hr(;͎j[ I),ݏpR*@DFآbHŶ{F`<z5~-Pі.]: S v7}}\V/{"ennDXuq8 K2#Z@OU=6ch٥aU6AjbʂDxfs8rˣ,B 8 9ل>ܸfASl'(MUpMQZPGC~D?J-`e}M d/n†{.,%"ERA;4fcJyUЂ|$rӰ*vMa[PG>so8%Q{B-`ueg첬9ZߗU9RUte}ʒfAJhDF 2mZ 7LeR ѿ^TqO2@E*V#ԑr:tX*egA9YPG.SPzcMhQ6AcUv`Ue:R6{\B=Je:RlUc=`IQ))es{"X,={GJ.zy-$MJokcsW}[!ԔqYs`>ܠ3Qvc -^PQg AZ-ԑ;.KxLB-8K]8A"}h:"75G+t^ڏH٥`iTODawH++љyR:ۤ|AZˡ,6ۊhڏ(+Z0iU9tz\*B]3K܎c'iʲrcioŌGc"n_BXeϗ.!;[9mXfՃ2fMYôXf/^烦By?}(,:GXgM(|YtOgM2UV06FY,3R%NF1t}he3Q [;:v^FY,XDa HCD1"rf;CѤ(nJٝzi`j-틴s >5)S=(H8?x,o`9 eW|qdvJ ky˰]eD; gT{nlGHpG#?̤=$;KEaޘlP ɣqgl}pbZTXee QUOYq$ RxCx\eʒK H)Ko³y MY_lT#.'UTPV Ja:,KPVW06Ee(eF٦(|Dgb<.,4(ՑXFYLeN؂Mj?`5ePVOP|ѻ+o']:ؙ>a> hL4' 6"i7xUZFY,%J N*9JK[r(4&S\FYlm'l7d,dmK 9OԖyVƣ,y`bF+(Xʮ< lS`Ue(eF٦(|褏g">ljF11~r M=8e3QUP>$+w(Py&j,3I'KAp-sE(E.>p(r6nE><=TR}:f,QFA [90RQĉ1%YZON:Kn+&˸}eQV`ӪR`EiuxW,Q9M U}ۊbe)|H9k"L@YE=)k(06FYQ)0*MĔvV߉:)e`m l{hJG ӑX lS0%e9>=:RTٗ4ı&K [*MA=@\,)- {H*R+%(LLb)Y(>SU]9ƯYG"9k )̓XbȵuQV1 eVo&.SObE,NL.? p[af5!9\B "ITOrԈ;u76]BŔm.f,t_xUmmbʧ P %"WXh2#ZI6 tۯ#g(\%o~P|塓4pK1q|Q |i<ak9`U_^՞0UH&%k FYŌm@pA?W0m.ցp$2FYDsDFа`TO~_Z-;QWDe.P$[v\Z~x~Ce"juAV| DUA8ݡy}:7u3-DTsSB$H9DedpS )Nf1v|pIhNL UZ./yLV$H)Aa0'x N #Ik>oGYÛ(vߏ2I^JYb݋=(ʽ@9'~ŗ*,)g9[ZQ鶒v@8? %K-^ ,<e}:dNҽՃQ0)ed Ԑ~VFYt*kX l`%e,$eu3E!g8j^ǕRk]&RU{xKQ0eW] [r\IWb-e`%!jg_èRۢ4;9>"'J|?|Q0zrt'81TdqNR'T,a"‘s>!ī<ʢe8NG(1NA(t.9RT:ra%a}Q a]o,y֑fffff3Y333Zɛ-'_w*``o)+fff7ٹZ07Y3\-ś鬙YYSX}Ϯw~a?sA<kR#o 7^<3fCc۩~‚]'w/{OEѩ5D6|t; ˶0EyҭvJoqMaN[W9toeVt ?\}I΍6R|u[PkNmG)X0:XtAixH\Ny6R9Tٱ-H-&SqIiD_z;uzċכ9~KHN2";gV̬t6J}Cs_ln+Y׋ '{䙷>78'xERCo8Yx,:Ŗq`@{uVt~‚o.l0t>L">ZK +Ӥo`n["Tęq6DBR3mxQ֨.ɲ4 Rf 6_\氢nn:șqoD-AU=|I 8ㄜ8Z,KGWU˘ȥ4k6HX0rٔ|aO0$dv2*bOE$D `<iRSd._Tz+-o+$dsq$EXy%(P:>K%/'|[L9喤~Vav8Af4F7zyxyُ{ނYVFg':k6x7ނYStv mY33f:ږY ,ݗ^| ˇjt`X>gҴ6(Y{N0';L.^*V%Kv>EGsmIZj â1BOlǚYO9?9! <*h(ao~Mg_po6WgX4E|%V_2YQXS3bߐ Yctv: hz\c*n"Z7!lI U rLîw/ n0ٛ7_9<{f٥tL,UzZTBUZ' _gS-P AZXgo^>{RqT"'ϞuA6r@CuP <nk'}TO1E*EIᷦɼAZM 9[ rK5Bzɀ"B)q~NT*-S63Ξ_tWyT{3OxOBo-YYiu41t"8!™M9?.O>-j΃)t8<π C]`gE_vFT=.僟EطU#C:?n+&1jD'?Q/ ?ۃ=Ύp8k߼^co1Vg?\x:;o}o,@5YΘz>[!B,b:+2wL|NtV":d_:{ {"K,/.|c88H:Ac߽f@g!oK+qA9E.hYgO9hgRCq[DYz1/)b8^}7u Yaᮽ:|5&z5WDXMkp 8R@<<{#W o2cݔQZA">ti)vΪg0uְ F}tvP-Lg Etv`:k0,Elx!'.qp^A*n_꺳 <CTL92W; uC:Ͼ˺*s~(bezr$WgubQ|?l~SztvPBazӧOYLdB4¿z$ADO}R$ILc[ >$$u--Jj $(k(f7okh|YC=a:n@g~1|Vt^ Slk\r4>v$o?79p@Q_[GgK uϲ0!Ew| R5g'pTȢl ;$";Fu'郶KKnRE܎?R 6 ElUէd릳ɚ Csn:&/8YaѨ.ؕk=}µ >]=}"~l/<$S~Dg0j/]|4޵C#3%Rw6<z Kuvv+OND|7^kO<O~TٍW8:9% Π.:[|-(xް)w8VUc,ƶ?%}m\ꔚ1Mg!@=G<BL>ѣ | DPgrO<MQI7xgi/8 ocLMgr)%!)57uN"2t ?ݽq8 EҬqyNvP7:%ލ8xߟx2]]zi},z~< v/8el oYTr{9Y9~ v _rT~ݼFЙtJ$z9)k'jMgi<Y!sbO}"Y9 D"pO=-)>PqJ 0eM s|;&?F(H?zàYIfHIpD;rn׫eDɴׯEOsh>X.߲J=Nda3hή0D}V46 ԙO@Vg`:k0,u@8ia* 캡:矫7Wى^@r ާcAmI>B0]74Xg{7|֭[(r.V]MUܭHPSG⣮yAwה!캡:+(u"W\QxAJ]]PxY~ $"M5i9UXr$(k+-~-t:ëA``:nh^zߗH'+* u3*T^)&JU%ȡ5o.Lg n;JaqV(Dx(8%v2EW\ť2Յ$e ?5(\+)u^f0 q@F+p:0]74Xg @&D .m]Lg E:bvQXYoC:.tI63}ŠlOz2~/Nt{*`|3O(ȏnս- (vG}rjLBHdYDFaj|. ߿mNVe{:?6VM R3E~P1m&Uh[3Χ$;pQlI0uY_޹svOo0 Hg<VDǁ;wP"MTM,&* 5tAEP .r(  -_l 7t* }gih h>f0 k7-T&%F%Gl;uу"Ri!sKꓪJB"~.R1Hu68 l65AgfQ:cTl |keUl "4 "9J$W殧;hc+wmnDG^|B@_I37[ưp=FYGؘltsH-编|3t6UXu~`Ue0r>K>ؕ(QJ X^gld2ͱIF}݌zap:+C>Lg ! tRAq]rp4Vt-8 I߬n #"'GC:r^\d$K%utpAf$J'AWyfȇlY}p-<`P[] gs'j ny~󦢔|mq2,Μ|y MmtL~3RaSbZŝOA>ᾙ(ٚ_ k)3fȇlYp-2~Jru6[w Kg:+.V`y0@:3P]h6Mx-` Ij9ݔkUBȇ2bU4;5JyКnݹ3C>Lgbkȟ<R+X狣eQuFɯɳg} Ye0Fg͠Yq\X3t,>Gcc?B[EX\ +m|ΖEbG?OQykz2<<3A15C>Lg !Lg@je0505!P-LgbrSx^:`䎾~Qny t,_?;B ઐP[YZΖgEyFr&A%\!^koMg ja:[cͪ[>l`.Gg{[[=õiAϦ9ݝA~XG]ea iU:E ulYLv,߂R4ߏ"G˾vIYOUѨ$%I )'B&z8J+9=Q EK@׾rrn1KYYmJ@bgXÊipuV(4(JE8( էS7d2sL O1/l_7?0YC,  __Bq"u8kSAo7.j)UC͕36M2SAW]@k0HbIO4ވ05X.-7ɜ; 6ks VI 4Ɣ㹳]E:Ks̴Ahzk @JDYuRU+?5uYqq\ Wqiܯ%'`)LWKWI*ZYZ2XߡUrO_۩9.n*7`ƫhMg jv:`]&M+gQ`)?;hG{E[Vt`k05!rt6}R^y:w5LYC%g=KTo$%ɑ/ %o!-iLS(E 8f[@ܦI."Xj v:;lGю5=Z0>fz մz{.+6{mn!h*QHI xֵ{>$u𬚤d yJw$DU[oM~Vm%`:`NXmL\ _zX@قMz)@VFVӀ,! ާWPNHUàq[x b=泉DFsR/(z|=jZrj_j<%tYWIq"֤b 4Y*պJO%\a:0@iTyRU9`sgS"&i^ ^iu4`Qmv6x:|lQYeflnS B$|V$Ki_9 ՈERi$Ntٺ.-ӾHԆmR$.woʟ/|`X$VVg f<X tt`C0505!rt6sU5KI-.ʜ ǯ^6Lg !4ċ?H|%)A! )yg)kZf&RV #5!Ēt}f\Ut-J> qlWgB=ɯXg_Gt 9E(n*o+ـәD]¦KY}nXOnASkLTm+fд/AOFTԍfBC;ljvp`:kD5JFȓH75gAoʚ0 hNM5!P-Lg !Lg ja:ka:k0T YCYZB tb9:vˏESq6VÄ05X|SDe=rI%I rBՉ#!JRݐLEۓP+&fjȠzoCñ$u򬠤 MC6m1l87ҜjYC,ʡPQH$om`:kDm Z* D0Syz ϫ0-+Whtt`C05X^7V9nK.3-lV P-,wln`iv*YZ,c>"I}i5E5i5GFn ugsBg05*ƢS3@?Q+1H5[t`uY8Џ ZWMd[ssZAқ]wKOjE\0bs&Nz L=[?,Bga9YUHFW식^ͰL[GA iZg Krt֓yKª8'6 T7A'ItmϊQ`=ۢ 浐_%: Έ(\dCk(!IJtVG%'WH ( 9p4tW9I#nù-[`^I~qE(hʗbb(!tV>SQ~rXу_ѥA<}I0Z5jWy-Aד$迴t(Ijj=BVR[zE`:kL5TR uSn \C!Lg !Lg jQw wl%_\}+\B4^;a^hu|SNg޽Xܹ駟͘N'aB鴰% Hu:wlNZMMf6ߵ%t`0TF,ųNvɠH?Kj'UFKASo0!?ܯɲVWPݸͰ׎z |K2y#:RrGOnGH"t&TaN'K?c1sDgh?r`U?Ad>1p"dLo7 Tfz\ml;^բ<H8hTXMo:ޢ7NAEuC-<VI.?Mۼ? D<T (N n~zn%PUJb!|`vfhz[Ԛnm=B<7 El>޾:"=C#`:nX uhήLg Etv`:k0,lpKbc|R=qRn~е3ٹI kuu6)R(VaV:hM[K| 76._2 ]pBM_'u`:nXΒ`%A'yBze! 6 `%̤LPVJ:H~+} 0]7,A"_N|uKIJ0nܔ۔j!dWۇGX+S=I:%!(pOtv` Etv`:k0,X۷Mg + L{ÒoHgߟUkdg,*/*4ZIENDB`
PNG  IHDR(© sRGBgAMA a pHYsodY0IDATx^ߏו5ZM<΃<j/q<X7v89fFBܣ$[808%IdwuԩbH*r/޵>Od?u;,Ұſ4Q1;Q$m _?`tp&:}qDv^޻v/D$Xnb->rgsp =#]|_c?>kn1-J0_|-ư-l?=,KXv_gtݿE[Vt7:~'jEřݼ|͛pNG'Iwo}{I1fؖݟ0;p@pxX?yxD// v؆ǃ=}0DhS+0$ww#zG' ùpWµckOyؘѕI!adw|M,UF7b*c\Aki"cQecdwz!g' NnkЉ~޽{c+WE JVgmsC-uC6T .u 1EQxH7f.Za"_/(m1Mw1c|фsmܼw{!"M2yOnjg8>6e$Ȍ%>6)b~w>F;v{8<NĶۈ/KZJwv،zp`s7? r ) Fr~r@%c}͐-Enp4,w@S[mlq'3>R9˄@+[p+Z. V;hBT~8ubV;_ FvQo`_<v[c8VWVPw[]!8gMlk6"-8~_`A_a̓m:M%9M2|"pvSi 0#Џn7<G`pupEarE,+֣5ڣ &.s5l߼==Lr69Ϟ$@[t]T/,.K p2Dtt͛Hw2I?6wk_ruN<p%hb1:xXʫCzhSQYwǢCBg}Kݏs'| #N4gpWOT/ѕE]ѕ~s'!  ?,?ZnICQw!>]+>io駺K5hv(>ȄFzzaH|IbDH1duakKZ;3lbzң&;ʎ. >1|}!T6{=9{>$D.#:D ڛjGOC 83Dpx0p[%( "q)CEGC=t;;XiK}*Gw~U]w,<&E)8|=郾]k$CM{І{,W~Ieq;uW',C{І+H%0hO| }R;q)wX$6 x(9^'vw*E :/06Wpa,RQO֧|,Jͫ@M7ڝW;їk?<ǒ>Âꕜs^_7\ ܉77f⸈rGns8ʒ廧1(JA3Uљ'OaXorSH#S2XmGԈ,݈ThnG^m5B: jxsF9?_*~uz|R_6}J(UŖ +[39@rՈdb rʌʟW;@SKp7~5=]ֿ/.Sb$썯K;Z9 -;F~+_gGQ|Hp K@j:DLXEڤiOO a(+OG? NFQ$s^x4Y ˗;9L<O4+Dž;tr~ tFVa҂i. 11Gd$B[-:PڂkKҧƏ+vcW 3m%7c> klpO8!ow[V^ktA+"1$Dp>pd! g GFWci`(-@M#*:GݣhwSCܭo$#b-°]T9T3VDs*|RY*:h^ XxX2s^6bT\Zg^)뷼KrN-OzR] ?υt 妽gˆB^CM_ٓb(166674%&+gA-ݠg(ףoYŘ`p> vm8;mQpJi|}$ףc44 FܥC_[.=I+9wzr({ 8֓dG»"UP$FӓM}hף-1JkQ5r"xT?(a}U }m1,Ù}][,Dk-O(*i&!AFҡLH:=[<V0g)E l@Wt8Ӑ^625e.>h%>ǚ+*t&H2v&TsLBt?VGx9#,n!uiIqqיaMrY}< / 4Ϝ4.8BUGC{WgԠnIEZ\)/m yUon&-spa62̽d:Df7itd1{X%?ủFc'Ĺ`)c?`)wEmPyVxTu_ޗ Gv: ˃3QtJ~zn}G/qd{P$䷟^d2|b/9_^'%?g^pd(x-DO׿ >4[`:|i/w;  q|w?~OU7&:C?SU6{UimY& MU&켌Gv!#)-:.+cS9a_Kt.`)#;. 9ɎWU,V1K]#7rFqG,koo}ŲlJ/T7_!@lHp:thU E4Y9#8K +7o޼|4*,cvdsD͂ӑzV07@]ҷ^xxF|!a|wI+XoܑFXQۦ+^N0?}r/^=Xl0YYK+\VF6B>C1 4C~ .[ow (Ѓ] ʓP1nrȺ|OγѨu2RzCXʐvl10F5StRks蛌Ù[x{V;/2aJH943ArUmPo(Y7kOʵ>>@FD8Q8cFԩSnd2^Vwg?TҏJ&#[Y2&DOQ]8#Hy6ܑsiN@@>pdJ@>$}=$7NvRC+*捬 7:]X0yK%Vqd#;i<L9roFh[s#OSZIÔ#ۉ2:]lݏ:w4XOX#4@3q޽ӧzz3Øld! <Cȶw#+Oa藹8HWȌ{X0ndeYC.|CƿG ~Ъbi`2wo;qNk),0)IhG~o±U}mjFVvge&'9+3\809GFV F{[z-Cj /G0^zU=>c*1Kud( evT,0;BߪDGVB_GtQZ%:i*PFȎ]4tdeCa[7//<.G舌]~, :.On&O?m>̭/ Y_4?ѯz}mF68>+Q'OtvZ4Wg0jocYpe Vt,Ӑϯ{`AUM!qb)WZkcTg1u zROFmo0,L_f4-:/@r  _hA_X]2ډpv{oKm~"9p5cY}T&*(F:Y:0Qa3^| GCzD| V0U 0kZ5o4Lg+e6@2  clm7R1S}!;5,fx<<nV"~0*(9yKd{* 1WTα6*F+ z|RUB_FJkcqd<q% Shs#ܠӱLqw@&ٻeo#_~@@V]OށJ!c*Б+4b\ۻ"HUi|r8K]T"YΤ c*62*!c*H!].T4Vydݳ!h()VwC{3 t,X 5YX#[z}턯~][O+:]|G24:@N=tZĀ*@I@D*(Ș Lޘ4+;wpzX :jWw/NG(Z.=žߥ(B 8Ob|!c*3XbPZC2XHaE @?+"y:JxhA)accAKJPaSeVӑm:j:n& H _.8ENvOP("=E& )᧟,qd|F* FGҁVӑd+s6̑53k)k'5<!z;kWz;X;BJS/dbN4\Sbo8to|v -97ًg{s<< g@?%kjq4%?@yJx`?8q۩-OАAd ›r3 Z1:5<_?%?xvѸ*Ի\u0׀Z( ?s)a f kܺQkϼ%,0w巪`S3c~_mlYNEvjy*{;{KŬ54>k׉Y@Z=lh=c,]\r;HsmlK v=W.\Y9=kG 1v]o_RZ# #Yȧ\Khw+g/ %{ک!_X[Cd!S=%V.]&OitBZ|>]",>DSk|4rٓX=D6bJY츬d-K^/ɥFґ8>c.&ee`biy=!da R,O=K$|B_ҕ—v=Kֿ7M] ؼv fT$IxG>?FPy=q oÏz;Só/VK2.`m0=;BH\^#/XY}"(|\>8K Y "GЧ_11k Mm4cm)SA~$ѕ<Hrnk48Y("?6=׿u]a8/IHVޥV|,U)_e2 ⻈XہX=kל ՕBue`54 fMͨPv] *\ {sL47 8H|d|lj¤+>z'X>}߉ v]kOOM s's,q/ŁEwn1+k}ӧO˺ udʿ/.mȡ2̱֯+ݧ|u󘩀iV fk?@X`</cyǯF&LDx@Yˤ`pND;_Lh AYU!S&, -LͰy*֎H 1_я844T@;U$`|OWM`&mj*!H*@Mml2[u쑥!^QK &nbHתUݻB20 :KjЪr.tÓcѬmE²=ɲ߿DD;qkw :a'Nj%MN~_ P|3@y6@X}+mubgeAӟh(iv"`8QG'jbRAQlFTZ# emF Y AJim{{-77E؇rS}"m Z6Pّ`ؤZ !tb[[*iXR|\&[ W.[nǐ`X:ӤG0HybЛ9vm>|~*LX+ljB!8o ZMxTڋÃUPӑUZM֐7Y K.W-o>XY kݥ0p#YH&3M> F7<;C(ܚX[ڰvoX4{U^ RKayѼ1LY8Y/C)Y>k䥟Lfo0?(୼ SoyOsa3"Z{$`zW{[d($*u\ml£lml ysʎ[d+ huѧ"i_ ˃ 6o?- 0e*b%KtukvjZ|66%MNees}0_^_^_߱:o1JyoXk}K1keu~Wb8%`]" |Y[k1J0.EHhgrd>:)n#2JlѠ鯾ayއ<vˈ{ߦ/mYRD ;;XP ׆dPJ@.⍒8=ßZW G|Aj%l-α6P&+&˸}{9VYMe`cf  )Ah'~xJ]ŝkT}K˴C^ۑ^a8%P !Z.0Jj84xFa5g\`8%`%B߰<ؼ%B߰<k??.fta4tΊM@fM_s+~нF45fcsxcm]7ɔ{F7[F3O=aKugbF4 .v8(Pt̒3q9oXEgeR& kmpVtX7ԖՍ2)qg),4VA,Z<oXEyoXE0.X[coXEHv3?5 PCn$vܔt x)7,!kY R-}F:tGAhGqGB#$yZqOܾ يśmyYچPJf#e 8cO~PF6]"y0XD(#0(:19vyw=ꐏ-mu]/#A+֗ RK22cX dI%~i}f-I\XJ RK224`8%f-#gs[xNrxN"kkzz- [q@ʎ 0~#M)eb{ edl^[@kV!R\BKgJ#A/O$zׯHqmM*ypMc70JXHQPFazbn^itXT:|iώJCd-tqLi>}3!1<Z<1Fv#& K&'YohQn wo)G4 U8 B3X !$R+HVku< MgZCVc05<&SFgLn|wDNB}ό:@ڧS`¤pΓdfۗ3-95򣲆Xa7pg}֖ffM1Y(k0#bŝWjxWtfmefkMj n8 o?nN\l)T<=2!DDglG_r֋sVn[:ӥ/Ro<Gl0}C¨G`΍Pu߂*%~e Nge уwOH7@A0O,(H6. ⹔:[pj '<[pAkYBP( ^=O[A?V'2+v:QY8Q q> 't솷m00A^^ւOB#GuPCMXa( CiX.eAoy_(n i 1e9V) $x)kPz;,x G$Bstf4 bY%uqݸOYTOW `R'YW9DA9C){gNAXy-^pI>k]onc0EXƬ’ <Y}㉄d 8k9B FEr<)X=˥le)[ssRk }`Veffm[LYCcPUQR{5yW)6ɻK{ LX޿}%>IҶ:GHY]P{Sŋo2FXnGDs˒ *v)+4~%"+,1ub6EvԦ9 z6B\Gȫu4\;nM`]4FX*KDۘyOm>IY~=n]/~PW_yeOG'Aj,Deů){m?tTo&-jNcʊPM,}P}uS -yJf?~`9kPVg/"8QtW^4ӯyMWe1eWފ{c-DGf'UcHfK|PdtZgD(|./]) $FN -y7ӑa,) eHq+J)ѥPS/5ʎTYdcʎXhTBٟx`w<v0sxX>Oec/J^ <s{u%)kŔ-y`og7h (BHَew"{ X: y[/ ?~/j8p_&Wr}?8fy(hpNٯ1?!lC+\ #:1Z<{pϥ,VW+%Q06ժ,**dlaS (^x(^p*Ho}_iU0edMGY24PHYA e ,( e F(K(OY=q8 tp4)Yq{}]>F^ Q}g_~e]a@;Ci )VLy;BR7,{I-h>rϲ20r) >}ze 2*2IZ)KGiI)uK=Z e Y^|ԩS_W|s` d"˸HH2ieA t;]*EAXHՀQS֜ -Jrl :cY[sa0 ŒY4T >hSʵ^vG(O~TQ6"=z>pSK`b\&&UrbY͗ԇYYJ%*;>IGby"(ҧ_{>SO<,y8z>J#AjPbmF}衇c:pTjˉ|$5ˇr2=d=vr-|1Ɂ^=)_/[!];NQk'XAEgr헎XbWw 16cVʂ_uA#JJ/ﰫF8SV x|,U7QEA&˘+v`Y*+}8#h9ʾ?=p‰/ g!eeUn1eO83@),E /.|_rx^]G8X$5.՝#U$24T>*4>}tیf~9:XWV|2UhʘBA16ٔ]gTKQⷷ>YF٦bY]:MQP9eoݺJ2qr`@w2pUd6,KD䀮mݥ:(Kw]) ξmE)ޣPKa8JZ[? MMʁ>˭u*di'VyPի)e,ئ>VP2bxKo]}MX- Ykud(K>_%_GQl*~ (p'.H[J*K_Z *xvdW*Ef*[bu0֐(0MORV&lho,( ,;\$_Y+ l~K߿ˏ ǑZC9\@Nv߿ghN)i2/e @ma-AV4@\B0q|F96>% ;wOjչۊ)Meܹs޽>P6N4(~'~&A[l5sU,BYd 2c }BxbA5AD*xRߥ&" BYQeZuI>E dD1CY0*Sȥ,hr(;͎j[ I),ݏpR*@DFآbHŶ{F`<z5~-Pі.]: S v7}}\V/{"ennDXuq8 K2#Z@OU=6ch٥aU6AjbʂDxfs8rˣ,B 8 9ل>ܸfASl'(MUpMQZPGC~D?J-`e}M d/n†{.,%"ERA;4fcJyUЂ|$rӰ*vMa[PG>so8%Q{B-`ueg첬9ZߗU9RUte}ʒfAJhDF 2mZ 7LeR ѿ^TqO2@E*V#ԑr:tX*egA9YPG.SPzcMhQ6AcUv`Ue:R6{\B=Je:RlUc=`IQ))es{"X,={GJ.zy-$MJokcsW}[!ԔqYs`>ܠ3Qvc -^PQg AZ-ԑ;.KxLB-8K]8A"}h:"75G+t^ڏH٥`iTODawH++љyR:ۤ|AZˡ,6ۊhڏ(+Z0iU9tz\*B]3K܎c'iʲrcioŌGc"n_BXeϗ.!;[9mXfՃ2fMYôXf/^烦By?}(,:GXgM(|YtOgM2UV06FY,3R%NF1t}he3Q [;:v^FY,XDa HCD1"rf;CѤ(nJٝzi`j-틴s >5)S=(H8?x,o`9 eW|qdvJ ky˰]eD; gT{nlGHpG#?̤=$;KEaޘlP ɣqgl}pbZTXee QUOYq$ RxCx\eʒK H)Ko³y MY_lT#.'UTPV Ja:,KPVW06Ee(eF٦(|Dgb<.,4(ՑXFYLeN؂Mj?`5ePVOP|ѻ+o']:ؙ>a> hL4' 6"i7xUZFY,%J N*9JK[r(4&S\FYlm'l7d,dmK 9OԖyVƣ,y`bF+(Xʮ< lS`Ue(eF٦(|褏g">ljF11~r M=8e3QUP>$+w(Py&j,3I'KAp-sE(E.>p(r6nE><=TR}:f,QFA [90RQĉ1%YZON:Kn+&˸}eQV`ӪR`EiuxW,Q9M U}ۊbe)|H9k"L@YE=)k(06FYQ)0*MĔvV߉:)e`m l{hJG ӑX lS0%e9>=:RTٗ4ı&K [*MA=@\,)- {H*R+%(LLb)Y(>SU]9ƯYG"9k )̓XbȵuQV1 eVo&.SObE,NL.? p[af5!9\B "ITOrԈ;u76]BŔm.f,t_xUmmbʧ P %"WXh2#ZI6 tۯ#g(\%o~P|塓4pK1q|Q |i<ak9`U_^՞0UH&%k FYŌm@pA?W0m.ցp$2FYDsDFа`TO~_Z-;QWDe.P$[v\Z~x~Ce"juAV| DUA8ݡy}:7u3-DTsSB$H9DedpS )Nf1v|pIhNL UZ./yLV$H)Aa0'x N #Ik>oGYÛ(vߏ2I^JYb݋=(ʽ@9'~ŗ*,)g9[ZQ鶒v@8? %K-^ ,<e}:dNҽՃQ0)ed Ԑ~VFYt*kX l`%e,$eu3E!g8j^ǕRk]&RU{xKQ0eW] [r\IWb-e`%!jg_èRۢ4;9>"'J|?|Q0zrt'81TdqNR'T,a"‘s>!ī<ʢe8NG(1NA(t.9RT:ra%a}Q a]o,y֑fffff3Y333Zɛ-'_w*``o)+fff7ٹZ07Y3\-ś鬙YYSX}Ϯw~a?sA<kR#o 7^<3fCc۩~‚]'w/{OEѩ5D6|t; ˶0EyҭvJoqMaN[W9toeVt ?\}I΍6R|u[PkNmG)X0:XtAixH\Ny6R9Tٱ-H-&SqIiD_z;uzċכ9~KHN2";gV̬t6J}Cs_ln+Y׋ '{䙷>78'xERCo8Yx,:Ŗq`@{uVt~‚o.l0t>L">ZK +Ӥo`n["Tęq6DBR3mxQ֨.ɲ4 Rf 6_\氢nn:șqoD-AU=|I 8ㄜ8Z,KGWU˘ȥ4k6HX0rٔ|aO0$dv2*bOE$D `<iRSd._Tz+-o+$dsq$EXy%(P:>K%/'|[L9喤~Vav8Af4F7zyxyُ{ނYVFg':k6x7ނYStv mY33f:ږY ,ݗ^| ˇjt`X>gҴ6(Y{N0';L.^*V%Kv>EGsmIZj â1BOlǚYO9?9! <*h(ao~Mg_po6WgX4E|%V_2YQXS3bߐ Yctv: hz\c*n"Z7!lI U rLîw/ n0ٛ7_9<{f٥tL,UzZTBUZ' _gS-P AZXgo^>{RqT"'ϞuA6r@CuP <nk'}TO1E*EIᷦɼAZM 9[ rK5Bzɀ"B)q~NT*-S63Ξ_tWyT{3OxOBo-YYiu41t"8!™M9?.O>-j΃)t8<π C]`gE_vFT=.僟EطU#C:?n+&1jD'?Q/ ?ۃ=Ύp8k߼^co1Vg?\x:;o}o,@5YΘz>[!B,b:+2wL|NtV":d_:{ {"K,/.|c88H:Ac߽f@g!oK+qA9E.hYgO9hgRCq[DYz1/)b8^}7u Yaᮽ:|5&z5WDXMkp 8R@<<{#W o2cݔQZA">ti)vΪg0uְ F}tvP-Lg Etv`:k0,Elx!'.qp^A*n_꺳 <CTL92W; uC:Ͼ˺*s~(bezr$WgubQ|?l~SztvPBazӧOYLdB4¿z$ADO}R$ILc[ >$$u--Jj $(k(f7okh|YC=a:n@g~1|Vt^ Slk\r4>v$o?79p@Q_[GgK uϲ0!Ew| R5g'pTȢl ;$";Fu'郶KKnRE܎?R 6 ElUէd릳ɚ Csn:&/8YaѨ.ؕk=}µ >]=}"~l/<$S~Dg0j/]|4޵C#3%Rw6<z Kuvv+OND|7^kO<O~TٍW8:9% Π.:[|-(xް)w8VUc,ƶ?%}m\ꔚ1Mg!@=G<BL>ѣ | DPgrO<MQI7xgi/8 ocLMgr)%!)57uN"2t ?ݽq8 EҬqyNvP7:%ލ8xߟx2]]zi},z~< v/8el oYTr{9Y9~ v _rT~ݼFЙtJ$z9)k'jMgi<Y!sbO}"Y9 D"pO=-)>PqJ 0eM s|;&?F(H?zàYIfHIpD;rn׫eDɴׯEOsh>X.߲J=Nda3hή0D}V46 ԙO@Vg`:k0,u@8ia* 캡:矫7Wى^@r ާcAmI>B0]74Xg{7|֭[(r.V]MUܭHPSG⣮yAwה!캡:+(u"W\QxAJ]]PxY~ $"M5i9UXr$(k+-~-t:ëA``:nh^zߗH'+* u3*T^)&JU%ȡ5o.Lg n;JaqV(Dx(8%v2EW\ť2Յ$e ?5(\+)u^f0 q@F+p:0]74Xg @&D .m]Lg E:bvQXYoC:.tI63}ŠlOz2~/Nt{*`|3O(ȏnս- (vG}rjLBHdYDFaj|. ߿mNVe{:?6VM R3E~P1m&Uh[3Χ$;pQlI0uY_޹svOo0 Hg<VDǁ;wP"MTM,&* 5tAEP .r(  -_l 7t* }gih h>f0 k7-T&%F%Gl;uу"Ri!sKꓪJB"~.R1Hu68 l65AgfQ:cTl |keUl "4 "9J$W殧;hc+wmnDG^|B@_I37[ưp=FYGؘltsH-编|3t6UXu~`Ue0r>K>ؕ(QJ X^gld2ͱIF}݌zap:+C>Lg ! tRAq]rp4Vt-8 I߬n #"'GC:r^\d$K%utpAf$J'AWyfȇlY}p-<`P[] gs'j ny~󦢔|mq2,Μ|y MmtL~3RaSbZŝOA>ᾙ(ٚ_ k)3fȇlYp-2~Jru6[w Kg:+.V`y0@:3P]h6Mx-` Ij9ݔkUBȇ2bU4;5JyКnݹ3C>Lgbkȟ<R+X狣eQuFɯɳg} Ye0Fg͠Yq\X3t,>Gcc?B[EX\ +m|ΖEbG?OQykz2<<3A15C>Lg !Lg@je0505!P-LgbrSx^:`䎾~Qny t,_?;B ઐP[YZΖgEyFr&A%\!^koMg ja:[cͪ[>l`.Gg{[[=õiAϦ9ݝA~XG]ea iU:E ulYLv,߂R4ߏ"G˾vIYOUѨ$%I )'B&z8J+9=Q EK@׾rrn1KYYmJ@bgXÊipuV(4(JE8( էS7d2sL O1/l_7?0YC,  __Bq"u8kSAo7.j)UC͕36M2SAW]@k0HbIO4ވ05X.-7ɜ; 6ks VI 4Ɣ㹳]E:Ks̴Ahzk @JDYuRU+?5uYqq\ Wqiܯ%'`)LWKWI*ZYZ2XߡUrO_۩9.n*7`ƫhMg jv:`]&M+gQ`)?;hG{E[Vt`k05!rt6}R^y:w5LYC%g=KTo$%ɑ/ %o!-iLS(E 8f[@ܦI."Xj v:;lGю5=Z0>fz մz{.+6{mn!h*QHI xֵ{>$u𬚤d yJw$DU[oM~Vm%`:`NXmL\ _zX@قMz)@VFVӀ,! ާWPNHUàq[x b=泉DFsR/(z|=jZrj_j<%tYWIq"֤b 4Y*պJO%\a:0@iTyRU9`sgS"&i^ ^iu4`Qmv6x:|lQYeflnS B$|V$Ki_9 ՈERi$Ntٺ.-ӾHԆmR$.woʟ/|`X$VVg f<X tt`C0505!rt6sU5KI-.ʜ ǯ^6Lg !4ċ?H|%)A! )yg)kZf&RV #5!Ēt}f\Ut-J> qlWgB=ɯXg_Gt 9E(n*o+ـәD]¦KY}nXOnASkLTm+fд/AOFTԍfBC;ljvp`:kD5JFȓH75gAoʚ0 hNM5!P-Lg !Lg ja:ka:k0T YCYZB tb9:vˏESq6VÄ05X|SDe=rI%I rBՉ#!JRݐLEۓP+&fjȠzoCñ$u򬠤 MC6m1l87ҜjYC,ʡPQH$om`:kDm Z* D0Syz ϫ0-+Whtt`C05X^7V9nK.3-lV P-,wln`iv*YZ,c>"I}i5E5i5GFn ugsBg05*ƢS3@?Q+1H5[t`uY8Џ ZWMd[ssZAқ]wKOjE\0bs&Nz L=[?,Bga9YUHFW식^ͰL[GA iZg Krt֓yKª8'6 T7A'ItmϊQ`=ۢ 浐_%: Έ(\dCk(!IJtVG%'WH ( 9p4tW9I#nù-[`^I~qE(hʗbb(!tV>SQ~rXу_ѥA<}I0Z5jWy-Aד$迴t(Ijj=BVR[zE`:kL5TR uSn \C!Lg !Lg jQw wl%_\}+\B4^;a^hu|SNg޽Xܹ駟͘N'aB鴰% Hu:wlNZMMf6ߵ%t`0TF,ųNvɠH?Kj'UFKASo0!?ܯɲVWPݸͰ׎z |K2y#:RrGOnGH"t&TaN'K?c1sDgh?r`U?Ad>1p"dLo7 Tfz\ml;^բ<H8hTXMo:ޢ7NAEuC-<VI.?Mۼ? D<T (N n~zn%PUJb!|`vfhz[Ԛnm=B<7 El>޾:"=C#`:nX uhήLg Etv`:k0,lpKbc|R=qRn~е3ٹI kuu6)R(VaV:hM[K| 76._2 ]pBM_'u`:nXΒ`%A'yBze! 6 `%̤LPVJ:H~+} 0]7,A"_N|uKIJ0nܔ۔j!dWۇGX+S=I:%!(pOtv` Etv`:k0,X۷Mg + L{ÒoHgߟUkdg,*/*4ZIENDB`
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./docs/wiki/documents/csharp-semantic.docx
PK!J~3 [Content_Types].xml (Ėj@ }ۢPJE.@Q;DJI4sfx]όY?4*}MGxZh<noӍZs/S(M'q@usns^K4Xz1x]AY\Y1H|՟pr[;*``Byr<`ѸLA0EAU|eEAN$Z_Yg$xO3/>)DG9#AjF *x@$A;F>;e`on:b;7"  */+2A~Sκiz9IgPCj؂N$r5Qd5PK!N _rels/.rels (j0 @ѽQN/c[ILj<]aGӓzsFu]U ^[x1xp f#I)ʃY*D i")c$qU~31jH[{=E~ f?3-޲]Tꓸ2j),l0/%b zʼn, /|f\Z?6!Y_o]APK!΄Pword/_rels/document.xml.rels (N0&^ ?1DhI{Gm t4.s[kO<&x.W1yO_n񂵂CLPd\_^e镧]I?Q:|_J!;Y*Ql4=HrCCe,cZXR;2Yjϱ|mDrpS03L)D=_53B p76-k].G>L bxuF gŚ ܹ>B$k ^u ?!@~/9MZq˓8AЋ7PK!$.B)Eword/document.xml=ێʑ ?0 X[û$'DI> <srzFPIx"a$C)&%"M])3/]]?[R[l ȵ޽nx3~m AhS\/~jY9rC, ..kfОۖmضw{k[(_ ߳P }0V4|s4o\׿r0C{b;vxuk黯!^W^Q7|y+d 9 fbmGAXx; Z4w(%"0 sƐM]Ojȕjw-F{ޯɮ0VD҂݀ ,s;͉!$0`%8o/cͷ-m0ZWm!S^muK;]3^?䑲z8D 7?J@_ᓃwLuz9 A ̧_OEx|=X T:f*v/\a-!<yr~sx+ҩ {bWO!\zqޗqv#,7( 1wסhZCm0*k=O& /_eI yku)FzGQ_C'kF\58((ue#M}O7Œ#N. {ӷf4QJ,1$T9Ч>IҕCN?b +!mwG.@\(H~e<+ Ýo.fTy'go3EQ&د'74? dCz6Oj+} N /"ux,Me9=3 Q)ށ5'0!Cq'|PD{Ӻ#PkLtc"y #w*=r Erotc8R{HIl'F_ 7h>B|F+XzZ7ԦBwiŷn{ӥTFO<<+`6@ 3*=Eg]`tȍcI)DDkQ;-;ђoYkz"~} 츃lL+'ffv#560lƯw<|0o*`&E^NE;/wˌU^`/',^esUmTԏv8\O}k=B$ Ctbno 6)bfJA)A"^ vnh ?Լϡ) biHjIƕw8,3Γpz\EnYfxI4[$YCs`L492*7&/TEMX S34 >!+4;3 |[`RIPKwqӝQ<֞byFxfv[e)1,kXp-|N}"w_U:#`d%Q/ ΚW周-Y _c X}3C`Ϳzw}7a,da?䇣|>/iaڑ]A49(2ڴqMU>{XFn~|=3x.w',*,M䤭(o]s|oy7Ow,A  [ю|YyO<g M6zX0]0:+ö|Eqzٿz.7 m‡o #5 ~?xAyC6Z_b ~A2s(Ìcm0'ƋԮKw1x ;lLs$6EM ]g*;OJQoQGJ*F|`Wj?-X(EA<UU<^ޗTY3"RWVӧ }QUu81j↵rLTU01(6] x-r-`ԡ}i~PYwc),|77&ODVn%ܻ ;醂o[3l&4*pDGqJUgq;G&hj%m9g:Cb. Z-< \{@!L<0~MǤ N^-̺Os;"/1U)$DX]: fp/DU2ҚEN#ɋ@imӷxr.Mw6*^Q dyjl &n$d\/<?ď+cqN<jG|Xi 3zg-obykbkڱrdHo)Cm_wO$;Sn4`l'ݴ`^,,V6R}EY,9vTjJt4ӊt(f6e1%Չ%֘Ufu,CvwS*d ZQhS;G?.3͜32qo(]9v)~y{.BSaDj=ǧrEUxV!<oA6UUX5+u .UI҇C@Ɋm9DN˶\T+'va `Q8arLٙȨȑ3qft&g6P qb?.5淂7Ό,W8*QbufftcABB#b&T/OePR'lq* \(AYIB@k8?Ǥ=#.PJ `c~BlDmDhbF6A׻n>%1[ҟbؒ ?yXݓ*ehZ&Q!s 1󋝧>4aBO1ݻ%S}д  dٷؖı0(h ?Ͱha*Yp.-'H| =Hz™7_q#zf-Q4NTWsJ=. ̔ǛUM^YfYh=xy4h(p$WR)ݢ=ezn u|RFPu0,>%SxTU3s[!l*`;nX ;}攜dklN9m D;gϛ^ ɦRmo'h#0|½,+ 3rg+Cפ\9Htj$@E<sJrM)Vc[Q Z#}BD?!NɁZEDC@*3C o ctE _?(,[;q:Ԇ'JšJT7|%G11R|8t;"YEVQ/W$8PHQ{P2fEa,ٯ:L=U`s_1ش:: pC1 Ȳn;N,"j$AX dty,4ш lBO1t-\Oi6pLz)q{d1({?z/};$?"\/,ɆѭU7M_LIEio%YƉp"*'}TV4 C*=#A1T%;`dSoďhm <"W^"߶B#! Αr7x?1`~UҺ:9`sҗƒs3i}cL#H+C(5^gpTax~a٣vعM knD:'F?i8smQ[T1MBvэ*)*ӠE "qNt20V|LԖlϼR?(AOs*:H%ՓD_Z مw8>=sI/_>]PXڢ޺:*N?Bϯٖ5ufn e͈ft0^ =(WP]D끓K5sIEI@KI5O Ύg-V/CN-Zc>~}E0ݗu@m b*/!Wh~sAiÄU1Q';EZ-찿j7[U'Lao:(xK yŠx/} I@4GPb?vN:©@;Z I4bY-:5i##x΃%ֲ'ԅ0Ub WNK($1bx A y' ̰q(Y^Ǣw3Ȕ7 )dZr_w-$s$%9"9CYF 3s7* VD⾌)٧PU5/bw٦ʼ!Ш ɕ2k ~ê}ӫA7Ӓ\]= Mh\ V|xz!y9=C=e'QAmӣymh~NNA0ȯhtTYg*TH)OH9޻/+|=DxP柸Ы2-/]rZ)qϹȢzY<<5o铒< En~&KHFLYR^U2^*.;D]TƻC$Dƃ.4fDÒrAZHBuh!}r8%h`?yBV=[2S"C;%߂M碏, W |FLK\| 𩪚*{s[5ޛ"!_b!Jg#E>t <Ba^ ]ƀ^3mw۲EN pbր^˻RLh.h@37L`HPÙY9T.EtG:v3+uWC|CQ'I"WP<~ԺaZ=x{sR;\[ &OrOzb@^m8t0/}h :x_J)]juRKm0JW2 ك`tҍO>W\X^ޡ˛WO> Z|u8 uJl`Rݽ1يR[q_8v-ۺ];7}P-ٝ\92LgB;B Bk;WX)* ZO c>IV)ۄvq6~*eM!h9/0wŹ|7;f;cٯ!'$Bz7NUlB O%i$X>^Ua3h Rܤ|?bD~J SzCMWLl#,r2!#'6^?Gd-CDCGő]lJ>w%mEo8!h\ dz|98ch!q1e9ԅPڦcBnŃa]Jɮ<s [ `l ( A5#d+0`@ }oҘMu\}N;)'<؏@]ڑԗ{IVXxybG}``)_ayc6*mjX>3qمC+j,ʓ6ƝDp:] Tu-)IAJ-|z;⑺twTPj pO"$?tm-<lʪދ4Bƫ (ǂ }Qh{A݆҆D!$M.6ҡȚFF/IR [}y5\]W9drX-6SJ{&68JccU`-s-KE6Pe~<V:魷>vxWELseQ d O,§B7g}H̉U l03IqIˇ<PL{8#:`Um>Ʈs~;*͇t<vGK91wCPCN|S?s\[PdH*t9 ^@^DŜDC%?؛<)ihŋZ "T{9ƺuưe! $¸ `䃔0Xz)cAL[$'{W$H] s.~VGlSQ_ҵ̹<DLաV v(uQ/IFܝ, ?q$ hs4x2|#r3|ӟDLȣ:%n+>R<'ADyd!{⋱ERddUz=|y3dЌBrrGrlRe` ~t ]mC635mowdZcmtԞmSU=<i*XfϣIu_¹ix4 Jl`JR?05L(nFȄyA+8wcL)tG Kzz q̇"Ab21%JSbDA^ /?KF<nУwɿ7ޝxaͷه4bDKf+doN7N/1yĬe qďf}7<*xcԠML·v/ TƷ2q.k~eHz$g:Vg%{k-}f҆`!-  ΀ZyzAh[6<rq i O6 jo[ٱ΁XK77/5mvuC*\NC<rݠ;|t!XMkFgF,X=Ҩ *, .І/X!<EJZg(s OTqM\+_X&N2^ _-l Z~Mٕ52Kڃ-We)Y/&d e_g|_"SI ` .vh&9Ya*&CemP"p$?Q=En7}v.)HY*uBTH{<H-[ntܢ_V q^ *q)6EDHJGw*(R#oTu: HS#M}ESQF%WJ|!+P%<`!mb Qtg̻L %:웰Q9c(9J7gFݤ9V7;:Ra&pz>z8#x l~_i)ke뙭ʤ^uC!CX]` sKr1cs>E ol bW\׉b*H3wP΃$c(XͶFQGUzt%mk4o 2@0ITm0:yx.cVJaLPlIa"<8H 5xWNU`@`,i`5:6_Xt&rΨK )hS+T25/Eo}n;9E:N 6U h iʆӟP"Ժ@ K12t BR֊0IR<Ԙtl 7ߙs4-WH!ca . Ļ eBO@04Cn~@J-ShAFqo3r88~s T2*P{u6:OO[`a[Ue4Οe8Դ7Za m"ƨs(,e/P8s*N#ueXڶso'*w!QW2J9zB@TM ԏ;6T*)G ' ǰ 3Nj|j[#Ve'  lm@-Y} 8.lh7!T%jYXm,QPrࠁ?}2T\t14z0њu xU<pՂbk} Ӿ>;/gnZ뢜a&JCZ:(<4.o=}䠲,t0rxڣҝ`뀴JߘoϷmH >- &cO_>~]얜_U~o9R[~j_:+FG󬋄[B5&CIWB۵BFύm&- P[UCԃꢿDuo'?-'ŤQ뫺adJHFG t)j-R'RYv nlth "\#i顾L ³C2 :J^20EVץwrE9X;!$!a(I¦P}({Z@Lm85gJԌ27[!ʉB 5!eFE.{6^m(sB\w'hR?|!Lݶ6n4t]޺f͆@''ЏE#8uK#8%Pq0'$[7@Mvdi5f2ԍ,c4Znd1FpCŵYY޺!݆,u#K@ ]xL3:MT[ʹî ɥYrnN X='s[7{2P^*VlmWd,ڴ#䆹ޣx޽<CXB) `!/I~c7XOe3R'NZ 7yaRb$GLYKsac޼:8΂Fm$hD~\VC3;! ΁P3oߘ}Ь4{o[xaLk:O i6g_\*!]Iצla 1@5wh[Q騴 /EYQ]Pp߀x3`z0<4,.'r<?~<䖊iBypGG"]PX^&ZߡVjk6u PE!}eA.7*%ЧF$TG=' ҃vd2V^ݪ}m;v'*.=u@AKCs]ę~d(Q+"@4¯Z2hZNW- kq[n8~lVOZ q)H,VadƱJz$c;tD&Rw>/:ףDpkYwyP)FܾTE.Ŕɒ J?vT _VyqQ"CȺpt?JdddczKXаC즵SwZ-K{Q*KJbMu:4}Oъښy RS2;չOXgf[9H@b**1ؿ#eس ##( 8"9-xbtJ ,M@=C!UJb?^t \*NsxQW4o?<m9<d>ñ NR –߽W2 o'*! ܜ 9O?wv x'_qA53B}n-h$Uk7DewQFYބ2@T3]1yS '@9{I2S>s>2_O GIGӣ#D=Ee;=V#&Oewxwҫ|^,'9MޯB"1C?$0o4O)w.,xg<![4g` ҷ[e4ző-0.f1 v'`R(3.=I߲OG !X;Gw1SgBY d @̨!耊vOpki ̝(kr\}~9 9:CsF)T ϷNvhbښIax[&bk}龯FuLr+%5w8}w1s_$?nMxӯܝυO\HMԉa>+IzXUX;̟ΰCvpj4FePֲPװ+^Um+ArRJWFv5zWkzqV4Z궬ZG]9Z*uKM@P)vU=05Lv2M gD<jxcMe}oWnꖃyk;X\Xs%f/ERY~:$D^<j'-#NtXk -XlJm7qfO%@3@GgÆbu_"ښB"Hn5Xs΄RqDo~}a }MԽ#<_ѣ P,uy-@8GJႆ2UaeT<=clFShص~$sIR=eS,7/\)eK/7_[/<"_PK!c%;word/header3.xmlN0+ﭓ*jʁ 4$홤I C&oOͻQÝFg$$⚙BMFM$th-fug٦U">m-HM) T 7e2)K8m+,N:øXt 8f,8Y mV -*[dc2R;^P fpݥՊWK`=,4FH"%Ǹ&W wТ9O_쒔)'tC3NQ5G\ 0 sLm4qmP54xi<1X<6^%*–EQ[^6W"#qk{7 x@E2/Pp4]oVr m@fC%":ۿ[}PK!Zv;word/footer2.xmlN0 HCvcT80vC|<@H5"$mv6@BP7N?qVQ-`2c !fחьD>03Fdd#<]͛.h!ؔRKkx(˜P ڀ$N:{LuL<q' 08Y,Эf#[T2l_ HL#F;AmHԛ!w^iaB:P_Ji8YMZ \Vc =6H߉I|DEZ. _sJ4f_Gsp>8*h+cȇ[y.yZpM",Y5Y`8H-slgdz7YΦجZo^zSlhSFbE2\KQJ:6JҚ]i[PK!QV;word/footer1.xmlN0Hﭓ5@4Dz=4i +U搉3{~UT %$DpȥYg~4#LOn.MZaicyFlJ̏<aAS( mt'qep=cf8? 08Y,Эf#[T2lO dr&6% ͐NMY0HP//4,H}lVC\cztA"?&iU~'tE2ND3i5\ 0࠲{<2;V{|4Y<*–EQ[^6WeL]_]Gh7/)#1"Lg;RR`?<Z3{ 9#Z۽[|PK!4;word/footer3.xmlN0 HCvuvC|<@H5"$mv6@BP7?q݇VQ-`2c !fחD>03Fdd+<[\^̛.l!ؔRKkx(˜P ڀ$N:{,uL<q' 08Y,mf#[T2l dr&6% ͐NKY0HP/=,4,H"j&ztAs"?%iS;1OHg"kAf kk67``75Ae4ymmP7xi<1%x5O)T-pף& l,e\ͦt >BxOdvw-E*f:s*5SY]iWPK!AY;word/header2.xmlN0+ﭓ "hZ4I$MRUhx<=gZE/H2I$ 4댼<nH39Sֈl'?&-s0q<#e.RhZra̭($Iݗ˅XjL<q;:apY!f^ M*6ȎfNPnfȀSnSWZU jƗ[N>Z!qy=Xk쁧ϷIZm'& iS$|9(L}_m&W?L<ܞ&ϣ&.͟'dOjm,7ezdeUayGh/_FbE2\KQJy%0f*#:>PK!X=word/endnotes.xmlԔn0W; '`&Tf]v5&Mh~mra?/oD왱\ i&ʹf$AuDTe,]]X)TҦ90tSQVnJUQpZ<#5O(ʬzwDEN|)$8 eqj k /;;ȴCL|J6-}9nVLbhX =(iw\2K箇O؋5]kCjXF9m(OqtƎxĐqN ;˱Fnk#@o/ۜFUzh:V˚y f+!/%t[Yxu, 34MY}0&3X{s޺. _!fJM8<i >XM( R8IJφʫ#S(\-!eZi{'$˪9>N%:28ZJ^0N h|PK!word/footnotes.xmlԔn0+;DC>*+nU}qjlqB"Dis|fc͛,-7VH<H\uF<$xFvܒo:-m eZliZڡ̀ B0`0 0n-jK-GhY֬CIkHԉQ Cv40ʨt mht撺mX%rM{e7Bd|MٞeWxt, q9/i?odv~GGoͮI:h y緁Jh:J,i?cif6T(YZ+0Ďzd~tuv#,PIMƼQ}+4N=iƺ|*cFPX%/hUo8Oۂ/VSj0MR&~Xyyr@,[Fu6ywO΂rBU~.щwdwnDG; PK!q;word/header1.xmlN0W"߷NJa!jw+08Ncl'o$M*4x<oO՛Q͝Fg$$⚙\UFF$th5j~g֤e">m,HM) X 7E3) 8m$N:øXt 8f,8Y ЭZ-"kddr:6%͐IYV)CW:.QѾvp wLAf<D~IRr{bБ8DǚB jk679``W5ޙh8RnYoqbKxK+mHT-pף&sl,<#tB?MB2c/ֵT2t3a-9 3C#Z۽꛿PK!0C)word/theme/theme1.xmlYKoGWwŎ -Pqwf UpT*z(Ro=Tm@~T- zcTߏ/^3tD<iyUM–w;!p`&Dz?"R Dn)nU*҇e,$7" "ߘUz%4Pc`{c8>A}۞22J >5( 6CNd tY9?C K-j>^eb bj mg>9]NNkl^-Sn ~},t)cZ{ʳʆ;faKvi (6NP6l.t-e|zPh2Z@x) Cή8ߘ& U)eWFe;\`Md}up<kxN˅%- I_TS 1x㋧ɽ''~9+8 TϿWn,~ Te೯ѳo>2Oc"urx 9x=~ib' %Nq*'ѱpmb{^߱>XQj[=Y MWI.eG.ٝv)4-mhD,5$! =>"AvR˯{\B)jctIl]1eRmfjsbKl$Tf.Yn NqkXE.%'·.D:$n@tKݫz3{lHȅ9/#w8uLH E1ʩ+D!8Y[X~umߤ,AXJp'la^1M^ָΝI8 ٷݝl;r|^o.w]<N 9o漬Ͼ%Ϻ9OچM= #פ zh&8 sq.، f$2gJr W 7R hx-/3 ͅv*hM3XUڅ eՌj #& z=  3ӰydH۽hHm65SH[%Heq%;M fQu;W,gj֛qp܂a?[fa|b7؝R-j(2[9Kfכ 퇳1эVbm0rhpH|de6Xqh:UJxU\jv`fW~^ՁY'Z͸J9SgdJ9g̅Z>F:G[*Ѕ҈=# BPZ%/ZWr4[SPpbQ4DBS d_vY-ye>S+9 Guk=MI=ϝ1u',m^x0ѯ*Kөڬc-7W~զpMA 7>oD eK1 @l1Yec,9g ]rqo|dGWWKRȘ?Y|pdh̔4p)L>DCPK!72 /word/settings.xmlZnF}`]";`m3'DDK@vK-$֭bwmwlvlݲ^~\l7ԛe6~avgDba/.vf]ufCMׯr=_tm=.cfv$]H|.n yws.iF=nqn6~ŋYfwnw'j?K?zuzc/ ۾[4)h:1nV;Z=)%# حg'^?n^UvΈ2߻n}86tC6bf=4wzqsXMTvGݿ!~mBwOз77j\__ ݖV}i[VW\}j[/H }:'zRaݲM:}xwqüv,ہ<s.o3)\ 6ҿG|9?fxs?o=y5OWPBS6*<|~'Qp!Ry߷hGWӪ) ~ -Q_h6?~6{b{+vY.^roqrN2E]gq˳@T7`Z[HQ JGX+0`D jDVV2D1J#"cjNVLFL*xHY`%$0vxN.`Y dlU _Ap5"0x1-q5)7Pn~l7;Z)D7KxI@K(l<{ ol2(hhoBvt$:#P\0oJmTh.9fј%DjN8"@-]*^ԏJJZ@TFa'dVD7,;"jD^"23Z(荒Jň$\A" IFjܤ@R ב63(72FAHg@(=/e"ωx,$ M ^u,[P7ŵ3P:JhcRxE$ G =XYE<ؘ(& OP?i>3x+Lc #*N# AVMSrLfe@yțRx@57x` OG(mm5F(/h'x8Y*tE\<I,$,s\6CĐ`Γ;5\wj$OZ<!/ $C(6*v~, XY X'8p$x+AE Ff؃M0 mp#w&KY`'$*jPt_Q8o[YbqwHH1ĊuBX }X֨$N-!XVemC)i*b޼7tB:C81,H*(Acs;M:&#*<'|`te\[":E2% |qbQP֎ˈ21o1hUn̵a83Ff8NQhb{DsʚP:]-K*/x) |^߼ 0ye>TXᾄ*S&ZPRrHF@8YA$ )>-y)9kbCT\1V( *)JR(FF  ʭ҆PQu6*'v]yq$' 栲w,U P[/TQ:}J* O*YR^83ZBIp 0oi2A[D`q` S3m|NuBU-&`,>R:=[Ia$sOqBs]5,!DO rq9ugPnQRC e܈O4wQMG7R 7ChxcbtxN9pZxax?9=V9+/%>-dS"  Ngv1HUDz.5XS1=+)qDŭL0pIZ͒IDv Yder<J,'2S1Rbc$ ۔Xntl9>#Nq-#3qX"@DjN*Ί w5gX?Y4abȤK vﴙ-?TΞqQcyq8]&]hdN+pQp|#)K'J&# Gf]8䠌Qt gg&B, )G"dĵK:TPE؀"%_p 5mUfBX|JPtwbUXyoqԚaޜ"^&y*c?-^Wj+Pa(DKSvOM *d Pp88@x4^;[fz}ݷ٧Nu%~t}>`W׋WzlwW.6?~{@z{Pwzv3ԮOӬM?7˟8bO6fsA؋U5^k>-ۻ/?׷∉=&OwFoi{4&iL=Ә~313=m~n\ξ>7j=6= &g^O_޾t佉e(h_}=t jɓi?PK!ч!aLword/webSettings.xmlKo8{9CFA}aۻ,Ӊ(HJחG=4aN(sL3I׶YaS.LUi[wo_b1Ne-uq/^W'NSQqVjr9VW-dz.ܥ-|8\.rY/zS7tDlq 3NU|6vӡrMǻh߉OöR1_Oe݇S4t/TC\!6i>@[PnLklobB{Gh=ޤéɼrnUחW3/4aNMe)mޜ*UjR.t <Jn~)E}LaC+D5@@rJ_ł6F"C+<Rp5()}.R*a-8mrdE&6hZ=9ఠ|<0֡,!2`0wV^8Xpd^  " e*h%+,8@ă`ȢLx ;0[,y`h=(/ss&'HVyxh΀ղ+ 9CyxPʝF&D_R2?B?H<xhU!8^YKFFql(&A!`ϙxF"ZiL<Ёr:| c<G>~o18eF@g8~wnom.p~쾼w8*&?}οPK!ڟZword/styles.xml]ms6~38t!b+؎u4Ii?C$dIq%(.ә"}v H|M|Y|4x4dQޟ>-^yA҈$,'U^<%48@ڄuQl_nH Ҕ\lC 3?ڐa}͖2Nhr||:0YZ!}݆?hYm^=A{dYXH&Qxx6qoI(.>>m= `RlWoSeµ{pw\ _%E.~f7,-8-sM\y<g(ɋ<&'3a^/(O$9M&+уڱ1xk8#GԿnd[Ʋ*(,NMbaȓi-L7"Կ878n~ YzH~|{,~>:;o&~GM u_4hV} d=$yt9[alJ'@"ƥKfM~M !ܸv]U:y#<GCjs5$adCqa38gCX| cq48CGXc1SNB>X{71 {xp=pw7 pv=* r7K^bHYA~FR%"?xbУ"D>l!IBr[~bzhi& Hq<-vE#.6hRTTA,={âiY}%P4IbF!aƆwo]ו .wIB=a}cbkxm afxe agT<iJyRF7e<MyқFHd7qySÍ3 nHF3]bVּgl;,z |i^8 Wh ͗sUxܫ`p{dSEJ^N{KJh{)[q{svXANoc wfT= 顗 7O[a0҂% {?"cLHJzf&y,kD|'7t8 _mE)x3.N<텧! v{d<!43Nc/c>-"?h7UN l*[<.>!x,B 1mpx/3C? 9(S])nxP"H6 l ^%$c#Tg<_[şc VğK@o,%Mc%h2ÔOGȐ``h`8`^ BLVGyJ 0_vueg̗I0_v&|u@W+b H_6g@h҂n,#ٓ' &c+6K"nb:l+8_$J޺&|Ì(I<ͭ)iLor MBBfID3=ey|^hv_v״~]j߄9=>(Y5 |M=ݦ(|t_XZtMxvXxI$OzJ6OK伧$leOI5.xMVCwOUYoeEpk]TIˊj\xZ3v~cxNv~erX옠)۫VO4$WiԼ}S)iЊ3eznwCDVqTHMvAVpDE+(VP%ZAh5 CNhGhG)!P ĝBB&`8G8G. Q\BBBB1;9*DA;*@;*@;8*9*wqT@Q! Q!Q!Qի q ]8*DA;*@;*@;*@;*@;*@9*wrTvTvTvTpByByG(. QЎ !Ў !Ў !Ў !Ў !P ĝBBt٧~Di[f?zZWt;* 5Uʎ]K/)jcuW.@= }G)s*.7%A7tSdkJapt_RpŒ!<wEkC+FP] džI sSN ,!We8ї4;B_}i#CCQ KTC';ʙjF5 X!jlGpS PnTá K5DR T0TC(g!0R TC,jN5rBQ d4K5DR 0TC(g!TrF5aCgCСZ2%Z\%4;B_}i#CCQڨvwT;j\dW-uR:UKvqRոjjlGpW-uR:UKvqRոjj\F N5ZW-٩UKmT㪥6qRոjJ5ZW-uRT㪥6qRոjj\dW-uR:TKG ܐ_\<mLA FFIBX$[RòjQ hO+>M&~{%’4Qh4O+\IU^a/WB>޾<&~S_VT|Go͆T it:v)'1qQYMrQ8|YmTTRw +{9==YIC GDX#a/ Lom3yؿŒ&VKIK?[ƥm;d\ҝz-^/_یiJz4<6ДVS+ OjJ'7F2^THfxvz5Ղ_H|F! 9[$ԟU;Mc|bel}ۅ߅/;,΄PVKw?D m* QΩz}& I򞨫~iBWBPR}*ɪ pTm'j\ϚԿErPMcÞZ:8,I`7ֱ5m/#oŰT?H}3:~rD~NkΪtE[ihGLJZhyt!z.g[sJ%A/|Ye"ZHgtUE .|Z9`â[va͸kM`<jF½_'KGjsOk~ImtN=ѩK:Zj"x1S?﩮Q],+ߋڕSaoڿyՉCw'-:_v_~x@}H7 È[ںjqKj,ehت۝L7'lRZv0`rhvN4}v=qԧ}A fo 0~58d?Ol*iZH;k_i},@<զLsѢ#u,Ƨgg>3xɲf bO I#=$a~GO@:vM]..cnd}3L7q5j<[ \3]آnzӧZrDž*ʌ{c-@2#VNkEަk~w%ڦٔ+F<M4{5Mvq r:Va&jm*7oֈdt_~Bd[ns>mכo3N[['T`9Y64Y˫eR˚j\6m\Y׊4ą`~9?օ"XO<$*`m=`kZ:}]ZoMV'dkcs ދl1egFF;`X >Ϯt}WW+ìĩ5(E{EEp>vJ@c])9L(Q.~v1rYȃK>glFǩ̭z޲۟U×ǃ^`EM 62'W}< /;|o<\Ӄ8-Gzy;i6:bwy 9P~.738 kfJĢDU2DjMaF!V k0ͼ$xR~5%K5Gu"/VToY.^{3nKΦbL>m( <t*웿Տc➛R1֤&5JkRN &`k*ʿPK!6+* Xword/numbering.xml]n?Ȣza{gdd:,Ӷ0%P=|B6P$ŖTT,mlJU{u:xx\dp'8K\,v8%k|*yiËdq<]bO(-fwˏrvw7ŗϳ(^,~a4\ royd_p_N/Yr|3_fv=xLՀVMiMq'i<0K73t{˾|Xw2i:Yynns[M[4N{4HYuQh2sG2o'r͆s Ѯ-=ο6䗪nW9ɛ- 槇<[do&و)ȼ~ 3Y,hbϷ$Yo3]2\}3},?Oyכt|wwod Xi8X1s9dW*‰Cac.r(eWhZG<Yח껿}>:?8Yٹ:|=h>ar_e iNOfqC\ic[ 5L ^~$fWx5&k6&:~and Lb&H$e3Dm[cxMu!UЉ&eh$NtflR(zѹ,X :IeIɂit&߹4 -^¢-@g#t0YYyYtԫ7I\zhǣ߶1rϟ#%s8?}&yS7ցq\-ϻa晲>!11ŏwvyM#zoi귟_ņ׶sn@;Z/C+NbJXq(ҹWDz$v'S~C+NXqWD{$zג?[֢$(\?0ijk rv\ak\VCBBjZEdvgKjEgQQ}ߢo[T3&WT:gE5鷨f\#ܢms:a d%{]2u 1[PB.{MԄ t^D11hkAǠ1x9b db&.]b`Zی5J mt hD$S2Z$ I4\qHA9h?[6 }FYGvk0tl+Us&ۨeַ@Gҋ8kG!_4U|WV GL#x7\o_ o>Cx<~$-aDx.F oQ3^6׃^#ݑ׈^{6^!K^ "|v_<)̷v'2We<s,5ы D+&z+&t!DrPKkȥ)8|NsR_u ڼk Y^Ya {V&aϪ\$qa6\A׏CioZلᕡ@V  @]/ruVDN޻>)@x <5!zr T6/} =TLbz33335 \Kz_PG{q&_墨40\0]=?_l!Dс@.Ruͧ,9}Dt@t {Ft##`Pt]8@z95 L\"y44x1S^?wx |&_,[ EC.L3dMr@x <TIDuÃiYZ/P^CQ/8C+E8EEQEi-b+KyRVd[\(@t ]gJ.]"޺ēv9>1n0@x <r)H4iG'!<69)lNas SmͩS؜jW9%W2$$fEIu.Z8 9:+HWY+ *1!l @t +HWm ҕފt^t%1 uU` uդI yA W{)K. ,PK XC+C+71fR@t AADAt&gC.Lߧ]Z :XNQ^} Cp+ cLd- P&kB ͮ o0p Q1rǸf0 W;z Y/z9ъC֋ފCKGjwd#eM#"ねC&a a ]+HWm0iC!<--]̍L,!]At 6~tJoA[qHd[,' _r۴ l-H^ yA:^Jk[, uQd."fP3^/````& 3[/THw@x |[Nĸ yo0N~@|ovW &000% }\¹t|gyȏE~,c~y8"?\qȏE~YcVeyBmb!6' v[b b@lV\mڤ ?".iV<Vی-kW$׶3T+Rj|+6 ݺ|mA8U5kfEf}ȞfF ]Nr< bOkT c"P S:G3,ݾ1}} Qt"l H"n$} c(*|CCUHUgTjrz*mT*74ԏTN7Lpe!zک7@-_ml(G(kTU;EP%63fk 7qOPK!fdocProps/core.xml (QK0C{v'ŷܶ& m]YuV q$U:Y$QLмR 򶘅$pȴ`U -82-rn2^[x\Iedh2J_b.emC5o hǷT204HUB 4:D ={r:SIl \wr06M5Oj(aWH ʜC7pCcnam{aH76+8nAx}ߨs8 ڞKvʤs i~\g?!vR'O)8 cEd,?#@u14PK!'&^ word/fontTable.xmlԔێ0+"/qB8jaK7RX!Y޾òIBUHf?O3ëޖ˵+c1"fDЊMЎY0>Zeփʎ%$ұ[0IlGLA2F ڗڤwT˔d|v~qe5*:9e_4HoElS{P˯Q˵YFSf-|$\e"$958+*x;)NvQ@׵҆,J<C=}/+"!K-xJ,Ԗ =XvU p{x|&X4ʍabw-*)hroᮦ2eĠP #aeO<B y$x* \2}cH@"_wQ=MNjDè[!2H:8& 4@`TPq4V4^1S#l 6LJj1)dhPfD -1/Z#l6ֶmcD"B$ $EV,۬JG5$>H,H7xB'Dx'[<SY-HM(Jl? әB#uqa^PK!(docProps/app.xml (Sn0 ?76MEŐba[mϪL'dIؠ׏OvOI۷Q;*ɴ,*h[EYDYXGoPC,HUGKƢC'Җ2 D Î z"Mso堸<{ET= ^CDӟf88Y^;)c7rQ,8v/l|A*9g?{oHߴ .r8K8]c 5h<&'yȿjKo8 rG1%cȷJXS D+MdF(t' xV/2Bjܪ<Ƞr(1Z!1a^c})yaO- c錿T׮Rو?⣯]Z=<'?koT4}w -Pǩ;NSͿUOÓdJ_F'Va|KPK-!J~3 [Content_Types].xmlPK-!N _rels/.relsPK-!΄Pword/_rels/document.xml.relsPK-!$.B)E word/document.xmlPK-!c%;2word/header3.xmlPK-!Zv;4word/footer2.xmlPK-!QV;6word/footer1.xmlPK-!4;8word/footer3.xmlPK-!AY;c:word/header2.xmlPK-!X=><word/endnotes.xmlPK-!n>word/footnotes.xmlPK-!q;@word/header1.xmlPK-!0C)zBword/theme/theme1.xmlPK-!72 /Hword/settings.xmlPK-!ч!aLTword/webSettings.xmlPK-!ڟZWword/styles.xmlPK-!6+* Xhword/numbering.xmlPK-!f/udocProps/core.xmlPK-!'&^ wword/fontTable.xmlPK-!(ZzdocProps/app.xmlPKs}
PK!J~3 [Content_Types].xml (Ėj@ }ۢPJE.@Q;DJI4sfx]όY?4*}MGxZh<noӍZs/S(M'q@usns^K4Xz1x]AY\Y1H|՟pr[;*``Byr<`ѸLA0EAU|eEAN$Z_Yg$xO3/>)DG9#AjF *x@$A;F>;e`on:b;7"  */+2A~Sκiz9IgPCj؂N$r5Qd5PK!N _rels/.rels (j0 @ѽQN/c[ILj<]aGӓzsFu]U ^[x1xp f#I)ʃY*D i")c$qU~31jH[{=E~ f?3-޲]Tꓸ2j),l0/%b zʼn, /|f\Z?6!Y_o]APK!΄Pword/_rels/document.xml.rels (N0&^ ?1DhI{Gm t4.s[kO<&x.W1yO_n񂵂CLPd\_^e镧]I?Q:|_J!;Y*Ql4=HrCCe,cZXR;2Yjϱ|mDrpS03L)D=_53B p76-k].G>L bxuF gŚ ܹ>B$k ^u ?!@~/9MZq˓8AЋ7PK!$.B)Eword/document.xml=ێʑ ?0 X[û$'DI> <srzFPIx"a$C)&%"M])3/]]?[R[l ȵ޽nx3~m AhS\/~jY9rC, ..kfОۖmضw{k[(_ ߳P }0V4|s4o\׿r0C{b;vxuk黯!^W^Q7|y+d 9 fbmGAXx; Z4w(%"0 sƐM]Ojȕjw-F{ޯɮ0VD҂݀ ,s;͉!$0`%8o/cͷ-m0ZWm!S^muK;]3^?䑲z8D 7?J@_ᓃwLuz9 A ̧_OEx|=X T:f*v/\a-!<yr~sx+ҩ {bWO!\zqޗqv#,7( 1wסhZCm0*k=O& /_eI yku)FzGQ_C'kF\58((ue#M}O7Œ#N. {ӷf4QJ,1$T9Ч>IҕCN?b +!mwG.@\(H~e<+ Ýo.fTy'go3EQ&د'74? dCz6Oj+} N /"ux,Me9=3 Q)ށ5'0!Cq'|PD{Ӻ#PkLtc"y #w*=r Erotc8R{HIl'F_ 7h>B|F+XzZ7ԦBwiŷn{ӥTFO<<+`6@ 3*=Eg]`tȍcI)DDkQ;-;ђoYkz"~} 츃lL+'ffv#560lƯw<|0o*`&E^NE;/wˌU^`/',^esUmTԏv8\O}k=B$ Ctbno 6)bfJA)A"^ vnh ?Լϡ) biHjIƕw8,3Γpz\EnYfxI4[$YCs`L492*7&/TEMX S34 >!+4;3 |[`RIPKwqӝQ<֞byFxfv[e)1,kXp-|N}"w_U:#`d%Q/ ΚW周-Y _c X}3C`Ϳzw}7a,da?䇣|>/iaڑ]A49(2ڴqMU>{XFn~|=3x.w',*,M䤭(o]s|oy7Ow,A  [ю|YyO<g M6zX0]0:+ö|Eqzٿz.7 m‡o #5 ~?xAyC6Z_b ~A2s(Ìcm0'ƋԮKw1x ;lLs$6EM ]g*;OJQoQGJ*F|`Wj?-X(EA<UU<^ޗTY3"RWVӧ }QUu81j↵rLTU01(6] x-r-`ԡ}i~PYwc),|77&ODVn%ܻ ;醂o[3l&4*pDGqJUgq;G&hj%m9g:Cb. Z-< \{@!L<0~MǤ N^-̺Os;"/1U)$DX]: fp/DU2ҚEN#ɋ@imӷxr.Mw6*^Q dyjl &n$d\/<?ď+cqN<jG|Xi 3zg-obykbkڱrdHo)Cm_wO$;Sn4`l'ݴ`^,,V6R}EY,9vTjJt4ӊt(f6e1%Չ%֘Ufu,CvwS*d ZQhS;G?.3͜32qo(]9v)~y{.BSaDj=ǧrEUxV!<oA6UUX5+u .UI҇C@Ɋm9DN˶\T+'va `Q8arLٙȨȑ3qft&g6P qb?.5淂7Ό,W8*QbufftcABB#b&T/OePR'lq* \(AYIB@k8?Ǥ=#.PJ `c~BlDmDhbF6A׻n>%1[ҟbؒ ?yXݓ*ehZ&Q!s 1󋝧>4aBO1ݻ%S}д  dٷؖı0(h ?Ͱha*Yp.-'H| =Hz™7_q#zf-Q4NTWsJ=. ̔ǛUM^YfYh=xy4h(p$WR)ݢ=ezn u|RFPu0,>%SxTU3s[!l*`;nX ;}攜dklN9m D;gϛ^ ɦRmo'h#0|½,+ 3rg+Cפ\9Htj$@E<sJrM)Vc[Q Z#}BD?!NɁZEDC@*3C o ctE _?(,[;q:Ԇ'JšJT7|%G11R|8t;"YEVQ/W$8PHQ{P2fEa,ٯ:L=U`s_1ش:: pC1 Ȳn;N,"j$AX dty,4ш lBO1t-\Oi6pLz)q{d1({?z/};$?"\/,ɆѭU7M_LIEio%YƉp"*'}TV4 C*=#A1T%;`dSoďhm <"W^"߶B#! Αr7x?1`~UҺ:9`sҗƒs3i}cL#H+C(5^gpTax~a٣vعM knD:'F?i8smQ[T1MBvэ*)*ӠE "qNt20V|LԖlϼR?(AOs*:H%ՓD_Z مw8>=sI/_>]PXڢ޺:*N?Bϯٖ5ufn e͈ft0^ =(WP]D끓K5sIEI@KI5O Ύg-V/CN-Zc>~}E0ݗu@m b*/!Wh~sAiÄU1Q';EZ-찿j7[U'Lao:(xK yŠx/} I@4GPb?vN:©@;Z I4bY-:5i##x΃%ֲ'ԅ0Ub WNK($1bx A y' ̰q(Y^Ǣw3Ȕ7 )dZr_w-$s$%9"9CYF 3s7* VD⾌)٧PU5/bw٦ʼ!Ш ɕ2k ~ê}ӫA7Ӓ\]= Mh\ V|xz!y9=C=e'QAmӣymh~NNA0ȯhtTYg*TH)OH9޻/+|=DxP柸Ы2-/]rZ)qϹȢzY<<5o铒< En~&KHFLYR^U2^*.;D]TƻC$Dƃ.4fDÒrAZHBuh!}r8%h`?yBV=[2S"C;%߂M碏, W |FLK\| 𩪚*{s[5ޛ"!_b!Jg#E>t <Ba^ ]ƀ^3mw۲EN pbր^˻RLh.h@37L`HPÙY9T.EtG:v3+uWC|CQ'I"WP<~ԺaZ=x{sR;\[ &OrOzb@^m8t0/}h :x_J)]juRKm0JW2 ك`tҍO>W\X^ޡ˛WO> Z|u8 uJl`Rݽ1يR[q_8v-ۺ];7}P-ٝ\92LgB;B Bk;WX)* ZO c>IV)ۄvq6~*eM!h9/0wŹ|7;f;cٯ!'$Bz7NUlB O%i$X>^Ua3h Rܤ|?bD~J SzCMWLl#,r2!#'6^?Gd-CDCGő]lJ>w%mEo8!h\ dz|98ch!q1e9ԅPڦcBnŃa]Jɮ<s [ `l ( A5#d+0`@ }oҘMu\}N;)'<؏@]ڑԗ{IVXxybG}``)_ayc6*mjX>3qمC+j,ʓ6ƝDp:] Tu-)IAJ-|z;⑺twTPj pO"$?tm-<lʪދ4Bƫ (ǂ }Qh{A݆҆D!$M.6ҡȚFF/IR [}y5\]W9drX-6SJ{&68JccU`-s-KE6Pe~<V:魷>vxWELseQ d O,§B7g}H̉U l03IqIˇ<PL{8#:`Um>Ʈs~;*͇t<vGK91wCPCN|S?s\[PdH*t9 ^@^DŜDC%?؛<)ihŋZ "T{9ƺuưe! $¸ `䃔0Xz)cAL[$'{W$H] s.~VGlSQ_ҵ̹<DLաV v(uQ/IFܝ, ?q$ hs4x2|#r3|ӟDLȣ:%n+>R<'ADyd!{⋱ERddUz=|y3dЌBrrGrlRe` ~t ]mC635mowdZcmtԞmSU=<i*XfϣIu_¹ix4 Jl`JR?05L(nFȄyA+8wcL)tG Kzz q̇"Ab21%JSbDA^ /?KF<nУwɿ7ޝxaͷه4bDKf+doN7N/1yĬe qďf}7<*xcԠML·v/ TƷ2q.k~eHz$g:Vg%{k-}f҆`!-  ΀ZyzAh[6<rq i O6 jo[ٱ΁XK77/5mvuC*\NC<rݠ;|t!XMkFgF,X=Ҩ *, .І/X!<EJZg(s OTqM\+_X&N2^ _-l Z~Mٕ52Kڃ-We)Y/&d e_g|_"SI ` .vh&9Ya*&CemP"p$?Q=En7}v.)HY*uBTH{<H-[ntܢ_V q^ *q)6EDHJGw*(R#oTu: HS#M}ESQF%WJ|!+P%<`!mb Qtg̻L %:웰Q9c(9J7gFݤ9V7;:Ra&pz>z8#x l~_i)ke뙭ʤ^uC!CX]` sKr1cs>E ol bW\׉b*H3wP΃$c(XͶFQGUzt%mk4o 2@0ITm0:yx.cVJaLPlIa"<8H 5xWNU`@`,i`5:6_Xt&rΨK )hS+T25/Eo}n;9E:N 6U h iʆӟP"Ժ@ K12t BR֊0IR<Ԙtl 7ߙs4-WH!ca . Ļ eBO@04Cn~@J-ShAFqo3r88~s T2*P{u6:OO[`a[Ue4Οe8Դ7Za m"ƨs(,e/P8s*N#ueXڶso'*w!QW2J9zB@TM ԏ;6T*)G ' ǰ 3Nj|j[#Ve'  lm@-Y} 8.lh7!T%jYXm,QPrࠁ?}2T\t14z0њu xU<pՂbk} Ӿ>;/gnZ뢜a&JCZ:(<4.o=}䠲,t0rxڣҝ`뀴JߘoϷmH >- &cO_>~]얜_U~o9R[~j_:+FG󬋄[B5&CIWB۵BFύm&- P[UCԃꢿDuo'?-'ŤQ뫺adJHFG t)j-R'RYv nlth "\#i顾L ³C2 :J^20EVץwrE9X;!$!a(I¦P}({Z@Lm85gJԌ27[!ʉB 5!eFE.{6^m(sB\w'hR?|!Lݶ6n4t]޺f͆@''ЏE#8uK#8%Pq0'$[7@Mvdi5f2ԍ,c4Znd1FpCŵYY޺!݆,u#K@ ]xL3:MT[ʹî ɥYrnN X='s[7{2P^*VlmWd,ڴ#䆹ޣx޽<CXB) `!/I~c7XOe3R'NZ 7yaRb$GLYKsac޼:8΂Fm$hD~\VC3;! ΁P3oߘ}Ь4{o[xaLk:O i6g_\*!]Iצla 1@5wh[Q騴 /EYQ]Pp߀x3`z0<4,.'r<?~<䖊iBypGG"]PX^&ZߡVjk6u PE!}eA.7*%ЧF$TG=' ҃vd2V^ݪ}m;v'*.=u@AKCs]ę~d(Q+"@4¯Z2hZNW- kq[n8~lVOZ q)H,VadƱJz$c;tD&Rw>/:ףDpkYwyP)FܾTE.Ŕɒ J?vT _VyqQ"CȺpt?JdddczKXаC즵SwZ-K{Q*KJbMu:4}Oъښy RS2;չOXgf[9H@b**1ؿ#eس ##( 8"9-xbtJ ,M@=C!UJb?^t \*NsxQW4o?<m9<d>ñ NR –߽W2 o'*! ܜ 9O?wv x'_qA53B}n-h$Uk7DewQFYބ2@T3]1yS '@9{I2S>s>2_O GIGӣ#D=Ee;=V#&Oewxwҫ|^,'9MޯB"1C?$0o4O)w.,xg<![4g` ҷ[e4ző-0.f1 v'`R(3.=I߲OG !X;Gw1SgBY d @̨!耊vOpki ̝(kr\}~9 9:CsF)T ϷNvhbښIax[&bk}龯FuLr+%5w8}w1s_$?nMxӯܝυO\HMԉa>+IzXUX;̟ΰCvpj4FePֲPװ+^Um+ArRJWFv5zWkzqV4Z궬ZG]9Z*uKM@P)vU=05Lv2M gD<jxcMe}oWnꖃyk;X\Xs%f/ERY~:$D^<j'-#NtXk -XlJm7qfO%@3@GgÆbu_"ښB"Hn5Xs΄RqDo~}a }MԽ#<_ѣ P,uy-@8GJႆ2UaeT<=clFShص~$sIR=eS,7/\)eK/7_[/<"_PK!c%;word/header3.xmlN0+ﭓ*jʁ 4$홤I C&oOͻQÝFg$$⚙BMFM$th-fug٦U">m-HM) T 7e2)K8m+,N:øXt 8f,8Y mV -*[dc2R;^P fpݥՊWK`=,4FH"%Ǹ&W wТ9O_쒔)'tC3NQ5G\ 0 sLm4qmP54xi<1X<6^%*–EQ[^6W"#qk{7 x@E2/Pp4]oVr m@fC%":ۿ[}PK!Zv;word/footer2.xmlN0 HCvcT80vC|<@H5"$mv6@BP7N?qVQ-`2c !fחьD>03Fdd#<]͛.h!ؔRKkx(˜P ڀ$N:{LuL<q' 08Y,Эf#[T2l_ HL#F;AmHԛ!w^iaB:P_Ji8YMZ \Vc =6H߉I|DEZ. _sJ4f_Gsp>8*h+cȇ[y.yZpM",Y5Y`8H-slgdz7YΦجZo^zSlhSFbE2\KQJ:6JҚ]i[PK!QV;word/footer1.xmlN0Hﭓ5@4Dz=4i +U搉3{~UT %$DpȥYg~4#LOn.MZaicyFlJ̏<aAS( mt'qep=cf8? 08Y,Эf#[T2lO dr&6% ͐NMY0HP//4,H}lVC\cztA"?&iU~'tE2ND3i5\ 0࠲{<2;V{|4Y<*–EQ[^6WeL]_]Gh7/)#1"Lg;RR`?<Z3{ 9#Z۽[|PK!4;word/footer3.xmlN0 HCvuvC|<@H5"$mv6@BP7?q݇VQ-`2c !fחD>03Fdd+<[\^̛.l!ؔRKkx(˜P ڀ$N:{,uL<q' 08Y,mf#[T2l dr&6% ͐NKY0HP/=,4,H"j&ztAs"?%iS;1OHg"kAf kk67``75Ae4ymmP7xi<1%x5O)T-pף& l,e\ͦt >BxOdvw-E*f:s*5SY]iWPK!AY;word/header2.xmlN0+ﭓ "hZ4I$MRUhx<=gZE/H2I$ 4댼<nH39Sֈl'?&-s0q<#e.RhZra̭($Iݗ˅XjL<q;:apY!f^ M*6ȎfNPnfȀSnSWZU jƗ[N>Z!qy=Xk쁧ϷIZm'& iS$|9(L}_m&W?L<ܞ&ϣ&.͟'dOjm,7ezdeUayGh/_FbE2\KQJy%0f*#:>PK!X=word/endnotes.xmlԔn0W; '`&Tf]v5&Mh~mra?/oD왱\ i&ʹf$AuDTe,]]X)TҦ90tSQVnJUQpZ<#5O(ʬzwDEN|)$8 eqj k /;;ȴCL|J6-}9nVLbhX =(iw\2K箇O؋5]kCjXF9m(OqtƎxĐqN ;˱Fnk#@o/ۜFUzh:V˚y f+!/%t[Yxu, 34MY}0&3X{s޺. _!fJM8<i >XM( R8IJφʫ#S(\-!eZi{'$˪9>N%:28ZJ^0N h|PK!word/footnotes.xmlԔn0+;DC>*+nU}qjlqB"Dis|fc͛,-7VH<H\uF<$xFvܒo:-m eZliZڡ̀ B0`0 0n-jK-GhY֬CIkHԉQ Cv40ʨt mht撺mX%rM{e7Bd|MٞeWxt, q9/i?odv~GGoͮI:h y緁Jh:J,i?cif6T(YZ+0Ďzd~tuv#,PIMƼQ}+4N=iƺ|*cFPX%/hUo8Oۂ/VSj0MR&~Xyyr@,[Fu6ywO΂rBU~.щwdwnDG; PK!q;word/header1.xmlN0W"߷NJa!jw+08Ncl'o$M*4x<oO՛Q͝Fg$$⚙\UFF$th5j~g֤e">m,HM) X 7E3) 8m$N:øXt 8f,8Y ЭZ-"kddr:6%͐IYV)CW:.QѾvp wLAf<D~IRr{bБ8DǚB jk679``W5ޙh8RnYoqbKxK+mHT-pף&sl,<#tB?MB2c/ֵT2t3a-9 3C#Z۽꛿PK!0C)word/theme/theme1.xmlYKoGWwŎ -Pqwf UpT*z(Ro=Tm@~T- zcTߏ/^3tD<iyUM–w;!p`&Dz?"R Dn)nU*҇e,$7" "ߘUz%4Pc`{c8>A}۞22J >5( 6CNd tY9?C K-j>^eb bj mg>9]NNkl^-Sn ~},t)cZ{ʳʆ;faKvi (6NP6l.t-e|zPh2Z@x) Cή8ߘ& U)eWFe;\`Md}up<kxN˅%- I_TS 1x㋧ɽ''~9+8 TϿWn,~ Te೯ѳo>2Oc"urx 9x=~ib' %Nq*'ѱpmb{^߱>XQj[=Y MWI.eG.ٝv)4-mhD,5$! =>"AvR˯{\B)jctIl]1eRmfjsbKl$Tf.Yn NqkXE.%'·.D:$n@tKݫz3{lHȅ9/#w8uLH E1ʩ+D!8Y[X~umߤ,AXJp'la^1M^ָΝI8 ٷݝl;r|^o.w]<N 9o漬Ͼ%Ϻ9OچM= #פ zh&8 sq.، f$2gJr W 7R hx-/3 ͅv*hM3XUڅ eՌj #& z=  3ӰydH۽hHm65SH[%Heq%;M fQu;W,gj֛qp܂a?[fa|b7؝R-j(2[9Kfכ 퇳1эVbm0rhpH|de6Xqh:UJxU\jv`fW~^ՁY'Z͸J9SgdJ9g̅Z>F:G[*Ѕ҈=# BPZ%/ZWr4[SPpbQ4DBS d_vY-ye>S+9 Guk=MI=ϝ1u',m^x0ѯ*Kөڬc-7W~զpMA 7>oD eK1 @l1Yec,9g ]rqo|dGWWKRȘ?Y|pdh̔4p)L>DCPK!72 /word/settings.xmlZnF}`]";`m3'DDK@vK-$֭bwmwlvlݲ^~\l7ԛe6~avgDba/.vf]ufCMׯr=_tm=.cfv$]H|.n yws.iF=nqn6~ŋYfwnw'j?K?zuzc/ ۾[4)h:1nV;Z=)%# حg'^?n^UvΈ2߻n}86tC6bf=4wzqsXMTvGݿ!~mBwOз77j\__ ݖV}i[VW\}j[/H }:'zRaݲM:}xwqüv,ہ<s.o3)\ 6ҿG|9?fxs?o=y5OWPBS6*<|~'Qp!Ry߷hGWӪ) ~ -Q_h6?~6{b{+vY.^roqrN2E]gq˳@T7`Z[HQ JGX+0`D jDVV2D1J#"cjNVLFL*xHY`%$0vxN.`Y dlU _Ap5"0x1-q5)7Pn~l7;Z)D7KxI@K(l<{ ol2(hhoBvt$:#P\0oJmTh.9fј%DjN8"@-]*^ԏJJZ@TFa'dVD7,;"jD^"23Z(荒Jň$\A" IFjܤ@R ב63(72FAHg@(=/e"ωx,$ M ^u,[P7ŵ3P:JhcRxE$ G =XYE<ؘ(& OP?i>3x+Lc #*N# AVMSrLfe@yțRx@57x` OG(mm5F(/h'x8Y*tE\<I,$,s\6CĐ`Γ;5\wj$OZ<!/ $C(6*v~, XY X'8p$x+AE Ff؃M0 mp#w&KY`'$*jPt_Q8o[YbqwHH1ĊuBX }X֨$N-!XVemC)i*b޼7tB:C81,H*(Acs;M:&#*<'|`te\[":E2% |qbQP֎ˈ21o1hUn̵a83Ff8NQhb{DsʚP:]-K*/x) |^߼ 0ye>TXᾄ*S&ZPRrHF@8YA$ )>-y)9kbCT\1V( *)JR(FF  ʭ҆PQu6*'v]yq$' 栲w,U P[/TQ:}J* O*YR^83ZBIp 0oi2A[D`q` S3m|NuBU-&`,>R:=[Ia$sOqBs]5,!DO rq9ugPnQRC e܈O4wQMG7R 7ChxcbtxN9pZxax?9=V9+/%>-dS"  Ngv1HUDz.5XS1=+)qDŭL0pIZ͒IDv Yder<J,'2S1Rbc$ ۔Xntl9>#Nq-#3qX"@DjN*Ί w5gX?Y4abȤK vﴙ-?TΞqQcyq8]&]hdN+pQp|#)K'J&# Gf]8䠌Qt gg&B, )G"dĵK:TPE؀"%_p 5mUfBX|JPtwbUXyoqԚaޜ"^&y*c?-^Wj+Pa(DKSvOM *d Pp88@x4^;[fz}ݷ٧Nu%~t}>`W׋WzlwW.6?~{@z{Pwzv3ԮOӬM?7˟8bO6fsA؋U5^k>-ۻ/?׷∉=&OwFoi{4&iL=Ә~313=m~n\ξ>7j=6= &g^O_޾t佉e(h_}=t jɓi?PK!ч!aLword/webSettings.xmlKo8{9CFA}aۻ,Ӊ(HJחG=4aN(sL3I׶YaS.LUi[wo_b1Ne-uq/^W'NSQqVjr9VW-dz.ܥ-|8\.rY/zS7tDlq 3NU|6vӡrMǻh߉OöR1_Oe݇S4t/TC\!6i>@[PnLklobB{Gh=ޤéɼrnUחW3/4aNMe)mޜ*UjR.t <Jn~)E}LaC+D5@@rJ_ł6F"C+<Rp5()}.R*a-8mrdE&6hZ=9ఠ|<0֡,!2`0wV^8Xpd^  " e*h%+,8@ă`ȢLx ;0[,y`h=(/ss&'HVyxh΀ղ+ 9CyxPʝF&D_R2?B?H<xhU!8^YKFFql(&A!`ϙxF"ZiL<Ёr:| c<G>~o18eF@g8~wnom.p~쾼w8*&?}οPK!ڟZword/styles.xml]ms6~38t!b+؎u4Ii?C$dIq%(.ә"}v H|M|Y|4x4dQޟ>-^yA҈$,'U^<%48@ڄuQl_nH Ҕ\lC 3?ڐa}͖2Nhr||:0YZ!}݆?hYm^=A{dYXH&Qxx6qoI(.>>m= `RlWoSeµ{pw\ _%E.~f7,-8-sM\y<g(ɋ<&'3a^/(O$9M&+уڱ1xk8#GԿnd[Ʋ*(,NMbaȓi-L7"Կ878n~ YzH~|{,~>:;o&~GM u_4hV} d=$yt9[alJ'@"ƥKfM~M !ܸv]U:y#<GCjs5$adCqa38gCX| cq48CGXc1SNB>X{71 {xp=pw7 pv=* r7K^bHYA~FR%"?xbУ"D>l!IBr[~bzhi& Hq<-vE#.6hRTTA,={âiY}%P4IbF!aƆwo]ו .wIB=a}cbkxm afxe agT<iJyRF7e<MyқFHd7qySÍ3 nHF3]bVּgl;,z |i^8 Wh ͗sUxܫ`p{dSEJ^N{KJh{)[q{svXANoc wfT= 顗 7O[a0҂% {?"cLHJzf&y,kD|'7t8 _mE)x3.N<텧! v{d<!43Nc/c>-"?h7UN l*[<.>!x,B 1mpx/3C? 9(S])nxP"H6 l ^%$c#Tg<_[şc VğK@o,%Mc%h2ÔOGȐ``h`8`^ BLVGyJ 0_vueg̗I0_v&|u@W+b H_6g@h҂n,#ٓ' &c+6K"nb:l+8_$J޺&|Ì(I<ͭ)iLor MBBfID3=ey|^hv_v״~]j߄9=>(Y5 |M=ݦ(|t_XZtMxvXxI$OzJ6OK伧$leOI5.xMVCwOUYoeEpk]TIˊj\xZ3v~cxNv~erX옠)۫VO4$WiԼ}S)iЊ3eznwCDVqTHMvAVpDE+(VP%ZAh5 CNhGhG)!P ĝBB&`8G8G. Q\BBBB1;9*DA;*@;*@;8*9*wqT@Q! Q!Q!Qի q ]8*DA;*@;*@;*@;*@;*@9*wrTvTvTvTpByByG(. QЎ !Ў !Ў !Ў !Ў !P ĝBBt٧~Di[f?zZWt;* 5Uʎ]K/)jcuW.@= }G)s*.7%A7tSdkJapt_RpŒ!<wEkC+FP] džI sSN ,!We8ї4;B_}i#CCQ KTC';ʙjF5 X!jlGpS PnTá K5DR T0TC(g!0R TC,jN5rBQ d4K5DR 0TC(g!TrF5aCgCСZ2%Z\%4;B_}i#CCQڨvwT;j\dW-uR:UKvqRոjjlGpW-uR:UKvqRոjj\F N5ZW-٩UKmT㪥6qRոjJ5ZW-uRT㪥6qRոjj\dW-uR:TKG ܐ_\<mLA FFIBX$[RòjQ hO+>M&~{%’4Qh4O+\IU^a/WB>޾<&~S_VT|Go͆T it:v)'1qQYMrQ8|YmTTRw +{9==YIC GDX#a/ Lom3yؿŒ&VKIK?[ƥm;d\ҝz-^/_یiJz4<6ДVS+ OjJ'7F2^THfxvz5Ղ_H|F! 9[$ԟU;Mc|bel}ۅ߅/;,΄PVKw?D m* QΩz}& I򞨫~iBWBPR}*ɪ pTm'j\ϚԿErPMcÞZ:8,I`7ֱ5m/#oŰT?H}3:~rD~NkΪtE[ihGLJZhyt!z.g[sJ%A/|Ye"ZHgtUE .|Z9`â[va͸kM`<jF½_'KGjsOk~ImtN=ѩK:Zj"x1S?﩮Q],+ߋڕSaoڿyՉCw'-:_v_~x@}H7 È[ںjqKj,ehت۝L7'lRZv0`rhvN4}v=qԧ}A fo 0~58d?Ol*iZH;k_i},@<զLsѢ#u,Ƨgg>3xɲf bO I#=$a~GO@:vM]..cnd}3L7q5j<[ \3]آnzӧZrDž*ʌ{c-@2#VNkEަk~w%ڦٔ+F<M4{5Mvq r:Va&jm*7oֈdt_~Bd[ns>mכo3N[['T`9Y64Y˫eR˚j\6m\Y׊4ą`~9?օ"XO<$*`m=`kZ:}]ZoMV'dkcs ދl1egFF;`X >Ϯt}WW+ìĩ5(E{EEp>vJ@c])9L(Q.~v1rYȃK>glFǩ̭z޲۟U×ǃ^`EM 62'W}< /;|o<\Ӄ8-Gzy;i6:bwy 9P~.738 kfJĢDU2DjMaF!V k0ͼ$xR~5%K5Gu"/VToY.^{3nKΦbL>m( <t*웿Տc➛R1֤&5JkRN &`k*ʿPK!6+* Xword/numbering.xml]n?Ȣza{gdd:,Ӷ0%P=|B6P$ŖTT,mlJU{u:xx\dp'8K\,v8%k|*yiËdq<]bO(-fwˏrvw7ŗϳ(^,~a4\ royd_p_N/Yr|3_fv=xLՀVMiMq'i<0K73t{˾|Xw2i:Yynns[M[4N{4HYuQh2sG2o'r͆s Ѯ-=ο6䗪nW9ɛ- 槇<[do&و)ȼ~ 3Y,hbϷ$Yo3]2\}3},?Oyכt|wwod Xi8X1s9dW*‰Cac.r(eWhZG<Yח껿}>:?8Yٹ:|=h>ar_e iNOfqC\ic[ 5L ^~$fWx5&k6&:~and Lb&H$e3Dm[cxMu!UЉ&eh$NtflR(zѹ,X :IeIɂit&߹4 -^¢-@g#t0YYyYtԫ7I\zhǣ߶1rϟ#%s8?}&yS7ցq\-ϻa晲>!11ŏwvyM#zoi귟_ņ׶sn@;Z/C+NbJXq(ҹWDz$v'S~C+NXqWD{$zג?[֢$(\?0ijk rv\ak\VCBBjZEdvgKjEgQQ}ߢo[T3&WT:gE5鷨f\#ܢms:a d%{]2u 1[PB.{MԄ t^D11hkAǠ1x9b db&.]b`Zی5J mt hD$S2Z$ I4\qHA9h?[6 }FYGvk0tl+Us&ۨeַ@Gҋ8kG!_4U|WV GL#x7\o_ o>Cx<~$-aDx.F oQ3^6׃^#ݑ׈^{6^!K^ "|v_<)̷v'2We<s,5ы D+&z+&t!DrPKkȥ)8|NsR_u ڼk Y^Ya {V&aϪ\$qa6\A׏CioZلᕡ@V  @]/ruVDN޻>)@x <5!zr T6/} =TLbz33335 \Kz_PG{q&_墨40\0]=?_l!Dс@.Ruͧ,9}Dt@t {Ft##`Pt]8@z95 L\"y44x1S^?wx |&_,[ EC.L3dMr@x <TIDuÃiYZ/P^CQ/8C+E8EEQEi-b+KyRVd[\(@t ]gJ.]"޺ēv9>1n0@x <r)H4iG'!<69)lNas SmͩS؜jW9%W2$$fEIu.Z8 9:+HWY+ *1!l @t +HWm ҕފt^t%1 uU` uդI yA W{)K. ,PK XC+C+71fR@t AADAt&gC.Lߧ]Z :XNQ^} Cp+ cLd- P&kB ͮ o0p Q1rǸf0 W;z Y/z9ъC֋ފCKGjwd#eM#"ねC&a a ]+HWm0iC!<--]̍L,!]At 6~tJoA[qHd[,' _r۴ l-H^ yA:^Jk[, uQd."fP3^/````& 3[/THw@x |[Nĸ yo0N~@|ovW &000% }\¹t|gyȏE~,c~y8"?\qȏE~YcVeyBmb!6' v[b b@lV\mڤ ?".iV<Vی-kW$׶3T+Rj|+6 ݺ|mA8U5kfEf}ȞfF ]Nr< bOkT c"P S:G3,ݾ1}} Qt"l H"n$} c(*|CCUHUgTjrz*mT*74ԏTN7Lpe!zک7@-_ml(G(kTU;EP%63fk 7qOPK!fdocProps/core.xml (QK0C{v'ŷܶ& m]YuV q$U:Y$QLмR 򶘅$pȴ`U -82-rn2^[x\Iedh2J_b.emC5o hǷT204HUB 4:D ={r:SIl \wr06M5Oj(aWH ʜC7pCcnam{aH76+8nAx}ߨs8 ڞKvʤs i~\g?!vR'O)8 cEd,?#@u14PK!'&^ word/fontTable.xmlԔێ0+"/qB8jaK7RX!Y޾òIBUHf?O3ëޖ˵+c1"fDЊMЎY0>Zeփʎ%$ұ[0IlGLA2F ڗڤwT˔d|v~qe5*:9e_4HoElS{P˯Q˵YFSf-|$\e"$958+*x;)NvQ@׵҆,J<C=}/+"!K-xJ,Ԗ =XvU p{x|&X4ʍabw-*)hroᮦ2eĠP #aeO<B y$x* \2}cH@"_wQ=MNjDè[!2H:8& 4@`TPq4V4^1S#l 6LJj1)dhPfD -1/Z#l6ֶmcD"B$ $EV,۬JG5$>H,H7xB'Dx'[<SY-HM(Jl? әB#uqa^PK!(docProps/app.xml (Sn0 ?76MEŐba[mϪL'dIؠ׏OvOI۷Q;*ɴ,*h[EYDYXGoPC,HUGKƢC'Җ2 D Î z"Mso堸<{ET= ^CDӟf88Y^;)c7rQ,8v/l|A*9g?{oHߴ .r8K8]c 5h<&'yȿjKo8 rG1%cȷJXS D+MdF(t' xV/2Bjܪ<Ƞr(1Z!1a^c})yaO- c錿T׮Rو?⣯]Z=<'?koT4}w -Pǩ;NSͿUOÓdJ_F'Va|KPK-!J~3 [Content_Types].xmlPK-!N _rels/.relsPK-!΄Pword/_rels/document.xml.relsPK-!$.B)E word/document.xmlPK-!c%;2word/header3.xmlPK-!Zv;4word/footer2.xmlPK-!QV;6word/footer1.xmlPK-!4;8word/footer3.xmlPK-!AY;c:word/header2.xmlPK-!X=><word/endnotes.xmlPK-!n>word/footnotes.xmlPK-!q;@word/header1.xmlPK-!0C)zBword/theme/theme1.xmlPK-!72 /Hword/settings.xmlPK-!ч!aLTword/webSettings.xmlPK-!ڟZWword/styles.xmlPK-!6+* Xhword/numbering.xmlPK-!f/udocProps/core.xmlPK-!'&^ wword/fontTable.xmlPK-!(ZzdocProps/app.xmlPKs}
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Test/CodeModel/VisualBasic/CodeInterfaceTests.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.InteropServices Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class CodeInterfaceTests Inherits AbstractCodeInterfaceTests #Region "Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> Interface $$I : End Interface </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> Friend Interface $$I : End Interface </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> Public Interface $$I : End Interface </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Parts tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts1() Dim code = <Code> Interface $$I End Interface </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts2() Dim code = <Code> Partial Interface $$I End Interface </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts3() Dim code = <Code> Partial Interface $$I End Interface Partial Interface I End Interface </Code> TestParts(code, 2) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> Imports System Interface $$I End Interface </Code> Dim expected = <Code> Imports System &lt;Serializable()&gt; Interface I End Interface </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> Imports System &lt;Serializable&gt; Interface $$I End Interface </Code> Dim expected = <Code> Imports System &lt;Serializable&gt; &lt;CLSCompliant(True)&gt; Interface I End Interface </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code> Imports System ''' &lt;summary&gt;&lt;/summary&gt; Interface $$I End Interface </Code> Dim expected = <Code> Imports System ''' &lt;summary&gt;&lt;/summary&gt; &lt;CLSCompliant(True)&gt; Interface I End Interface </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True"}) End Function #End Region #Region "AddBase tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase1() As Task Dim code = <Code> Interface $$I End Interface Interface J End Interface </Code> Dim expected = <Code> Interface I Inherits J End Interface Interface J End Interface </Code> Await TestAddBase(code, "J", Nothing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase2() As Task Dim code = <Code> Interface $$I Inherits J End Interface Interface K End Interface </Code> Dim expected = <Code> Interface I Inherits K Inherits J End Interface Interface K End Interface </Code> Await TestAddBase(code, "K", Nothing, expected) End Function #End Region #Region "RemoveBase tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveBase1() As Task Dim code = <Code> Interface $$I Inherits J End Interface </Code> Dim expected = <Code> Interface I End Interface </Code> Await TestRemoveBase(code, "J", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestRemoveBase2() Dim code = <Code> Interface $$I End Interface </Code> TestRemoveBaseThrows(Of COMException)(code, "J") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveBase3() As Task Dim code = <Code> Interface $$I Inherits J, K End Interface </Code> Dim expected = <Code> Interface I Inherits J End Interface </Code> Await TestRemoveBase(code, "K", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveBase4() As Task Dim code = <Code> Interface $$I Inherits J, K End Interface </Code> Dim expected = <Code> Interface I Inherits K End Interface </Code> Await TestRemoveBase(code, "J", expected) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> Interface $$Goo End Interface </Code> Dim expected = <Code> Interface Bar End Interface </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region #Region "GenericExtender" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetBaseTypesCount1() Dim code = <Code> Interface I$$ End Interface </Code> TestGenericNameExtender_GetBaseTypesCount(code, 0) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetBaseTypesCount2() Dim code = <Code> Namespace N Interface I$$ Inherits IGoo(Of Integer) End Interface Interface IBar End Interface Interface IGoo(Of T) Inherits IBar End Interface End Namespace </Code> TestGenericNameExtender_GetBaseTypesCount(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetBaseGenericName1() Dim code = <Code> Interface I$$ End Interface </Code> TestGenericNameExtender_GetBaseGenericName(code, 1, Nothing) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetBaseGenericName2() Dim code = <Code> Namespace N Interface I$$ Inherits IGoo(Of System.Int32) End Interface Interface IBar End Interface Interface IGoo(Of T) Inherits IBar End Interface End Namespace </Code> TestGenericNameExtender_GetBaseGenericName(code, 1, "N.IGoo(Of Integer)") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplementedTypesCount1() Dim code = <Code> Interface I$$ End Interface </Code> TestGenericNameExtender_GetImplementedTypesCountThrows(Of ArgumentException)(code) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplementedTypesCount2() Dim code = <Code> Namespace N Interface I$$ Inherits IGoo(Of Integer) End Interface Interface IBar End Interface Interface IGoo(Of T) Inherits IBar End Interface End Namespace </Code> TestGenericNameExtender_GetImplementedTypesCountThrows(Of ArgumentException)(code) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplTypeGenericName1() Dim code = <Code> Interface I$$ End Interface </Code> TestGenericNameExtender_GetImplTypeGenericNameThrows(Of ArgumentException)(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplTypeGenericName2() Dim code = <Code> Namespace N Interface I$$ Inherits IGoo(Of Integer) End Interface Interface IBar End Interface Interface IGoo(Of T) Inherits IBar End Interface End Namespace </Code> TestGenericNameExtender_GetImplTypeGenericNameThrows(Of ArgumentException)(code, 1) End Sub #End Region Private Function GetGenericExtender(codeElement As EnvDTE80.CodeInterface2) As IVBGenericExtender Return CType(codeElement.Extender(ExtenderNames.VBGenericExtender), IVBGenericExtender) End Function Protected Overrides Function GenericNameExtender_GetBaseTypesCount(codeElement As EnvDTE80.CodeInterface2) As Integer Return GetGenericExtender(codeElement).GetBaseTypesCount() End Function Protected Overrides Function GenericNameExtender_GetImplementedTypesCount(codeElement As EnvDTE80.CodeInterface2) As Integer Return GetGenericExtender(codeElement).GetImplementedTypesCount() End Function Protected Overrides Function GenericNameExtender_GetBaseGenericName(codeElement As EnvDTE80.CodeInterface2, index As Integer) As String Return GetGenericExtender(codeElement).GetBaseGenericName(index) End Function Protected Overrides Function GenericNameExtender_GetImplTypeGenericName(codeElement As EnvDTE80.CodeInterface2, index As Integer) As String Return GetGenericExtender(codeElement).GetImplTypeGenericName(index) End Function Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property 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.Runtime.InteropServices Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class CodeInterfaceTests Inherits AbstractCodeInterfaceTests #Region "Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> Interface $$I : End Interface </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> Friend Interface $$I : End Interface </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> Public Interface $$I : End Interface </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Parts tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts1() Dim code = <Code> Interface $$I End Interface </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts2() Dim code = <Code> Partial Interface $$I End Interface </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts3() Dim code = <Code> Partial Interface $$I End Interface Partial Interface I End Interface </Code> TestParts(code, 2) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> Imports System Interface $$I End Interface </Code> Dim expected = <Code> Imports System &lt;Serializable()&gt; Interface I End Interface </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> Imports System &lt;Serializable&gt; Interface $$I End Interface </Code> Dim expected = <Code> Imports System &lt;Serializable&gt; &lt;CLSCompliant(True)&gt; Interface I End Interface </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code> Imports System ''' &lt;summary&gt;&lt;/summary&gt; Interface $$I End Interface </Code> Dim expected = <Code> Imports System ''' &lt;summary&gt;&lt;/summary&gt; &lt;CLSCompliant(True)&gt; Interface I End Interface </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True"}) End Function #End Region #Region "AddBase tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase1() As Task Dim code = <Code> Interface $$I End Interface Interface J End Interface </Code> Dim expected = <Code> Interface I Inherits J End Interface Interface J End Interface </Code> Await TestAddBase(code, "J", Nothing, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddBase2() As Task Dim code = <Code> Interface $$I Inherits J End Interface Interface K End Interface </Code> Dim expected = <Code> Interface I Inherits K Inherits J End Interface Interface K End Interface </Code> Await TestAddBase(code, "K", Nothing, expected) End Function #End Region #Region "RemoveBase tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveBase1() As Task Dim code = <Code> Interface $$I Inherits J End Interface </Code> Dim expected = <Code> Interface I End Interface </Code> Await TestRemoveBase(code, "J", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestRemoveBase2() Dim code = <Code> Interface $$I End Interface </Code> TestRemoveBaseThrows(Of COMException)(code, "J") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveBase3() As Task Dim code = <Code> Interface $$I Inherits J, K End Interface </Code> Dim expected = <Code> Interface I Inherits J End Interface </Code> Await TestRemoveBase(code, "K", expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveBase4() As Task Dim code = <Code> Interface $$I Inherits J, K End Interface </Code> Dim expected = <Code> Interface I Inherits K End Interface </Code> Await TestRemoveBase(code, "J", expected) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> Interface $$Goo End Interface </Code> Dim expected = <Code> Interface Bar End Interface </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region #Region "GenericExtender" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetBaseTypesCount1() Dim code = <Code> Interface I$$ End Interface </Code> TestGenericNameExtender_GetBaseTypesCount(code, 0) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetBaseTypesCount2() Dim code = <Code> Namespace N Interface I$$ Inherits IGoo(Of Integer) End Interface Interface IBar End Interface Interface IGoo(Of T) Inherits IBar End Interface End Namespace </Code> TestGenericNameExtender_GetBaseTypesCount(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetBaseGenericName1() Dim code = <Code> Interface I$$ End Interface </Code> TestGenericNameExtender_GetBaseGenericName(code, 1, Nothing) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetBaseGenericName2() Dim code = <Code> Namespace N Interface I$$ Inherits IGoo(Of System.Int32) End Interface Interface IBar End Interface Interface IGoo(Of T) Inherits IBar End Interface End Namespace </Code> TestGenericNameExtender_GetBaseGenericName(code, 1, "N.IGoo(Of Integer)") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplementedTypesCount1() Dim code = <Code> Interface I$$ End Interface </Code> TestGenericNameExtender_GetImplementedTypesCountThrows(Of ArgumentException)(code) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplementedTypesCount2() Dim code = <Code> Namespace N Interface I$$ Inherits IGoo(Of Integer) End Interface Interface IBar End Interface Interface IGoo(Of T) Inherits IBar End Interface End Namespace </Code> TestGenericNameExtender_GetImplementedTypesCountThrows(Of ArgumentException)(code) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplTypeGenericName1() Dim code = <Code> Interface I$$ End Interface </Code> TestGenericNameExtender_GetImplTypeGenericNameThrows(Of ArgumentException)(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGenericExtender_GetImplTypeGenericName2() Dim code = <Code> Namespace N Interface I$$ Inherits IGoo(Of Integer) End Interface Interface IBar End Interface Interface IGoo(Of T) Inherits IBar End Interface End Namespace </Code> TestGenericNameExtender_GetImplTypeGenericNameThrows(Of ArgumentException)(code, 1) End Sub #End Region Private Function GetGenericExtender(codeElement As EnvDTE80.CodeInterface2) As IVBGenericExtender Return CType(codeElement.Extender(ExtenderNames.VBGenericExtender), IVBGenericExtender) End Function Protected Overrides Function GenericNameExtender_GetBaseTypesCount(codeElement As EnvDTE80.CodeInterface2) As Integer Return GetGenericExtender(codeElement).GetBaseTypesCount() End Function Protected Overrides Function GenericNameExtender_GetImplementedTypesCount(codeElement As EnvDTE80.CodeInterface2) As Integer Return GetGenericExtender(codeElement).GetImplementedTypesCount() End Function Protected Overrides Function GenericNameExtender_GetBaseGenericName(codeElement As EnvDTE80.CodeInterface2, index As Integer) As String Return GetGenericExtender(codeElement).GetBaseGenericName(index) End Function Protected Overrides Function GenericNameExtender_GetImplTypeGenericName(codeElement As EnvDTE80.CodeInterface2, index As Integer) As String Return GetGenericExtender(codeElement).GetImplTypeGenericName(index) End Function Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/Rename/Renamer.RenameDocumentActionSet.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Rename { public static partial class Renamer { /// <summary> /// Information about rename document calls that allows them to be applied as individual actions. Actions are individual units of work /// that can change the contents of one or more document in the solution. Even if the <see cref="ApplicableActions"/> is empty, the /// document metadata will still be updated by calling <see cref="UpdateSolutionAsync(Solution, ImmutableArray{RenameDocumentAction}, CancellationToken)"/> /// <para /> /// To apply all actions use <see cref="UpdateSolutionAsync(Solution, CancellationToken)"/>, or use a subset /// of the actions by calling <see cref="UpdateSolutionAsync(Solution, ImmutableArray{RenameDocumentAction}, CancellationToken)"/>. /// Actions can be applied in any order. /// Each action has a description of the changes that it will apply that can be presented to a user. /// </summary> public sealed class RenameDocumentActionSet { private readonly DocumentId _documentId; private readonly string _documentName; private readonly ImmutableArray<string> _documentFolders; private readonly OptionSet _optionSet; internal RenameDocumentActionSet( ImmutableArray<RenameDocumentAction> actions, DocumentId documentId, string documentName, ImmutableArray<string> documentFolders, OptionSet optionSet) { ApplicableActions = actions; _documentFolders = documentFolders; _documentId = documentId; _documentName = documentName; _optionSet = optionSet; } /// <summary> /// All applicable actions computed for the action. Action set may be empty, which represents updates to document /// contents rather than metadata. Document metadata will still not be updated unless <see cref="UpdateSolutionAsync(Solution, ImmutableArray{RenameDocumentAction}, CancellationToken)" /> /// is called. /// </summary> public ImmutableArray<RenameDocumentAction> ApplicableActions { get; } /// <summary> /// Same as calling <see cref="UpdateSolutionAsync(Solution, ImmutableArray{RenameDocumentAction}, CancellationToken)"/> with /// <see cref="ApplicableActions"/> as the argument /// </summary> public Task<Solution> UpdateSolutionAsync(Solution solution, CancellationToken cancellationToken) => UpdateSolutionAsync(solution, ApplicableActions, cancellationToken); /// <summary> /// Applies each <see cref="RenameDocumentAction"/> in order and returns the final solution. /// All actions must be contained in <see cref="ApplicableActions" /> /// </summary> /// <remarks> /// An empty action set is still allowed and will return a modified solution /// that will update the document properties as appropriate. This means we /// can still support when <see cref="ApplicableActions"/> is empty. It's desirable /// that consumers can call a rename API to produce a <see cref="RenameDocumentActionSet"/> and /// immediately call <see cref="UpdateSolutionAsync(Solution, ImmutableArray{RenameDocumentAction}, CancellationToken)"/> without /// having to inspect the returned <see cref="ApplicableActions"/>. /// </remarks> public async Task<Solution> UpdateSolutionAsync(Solution solution, ImmutableArray<RenameDocumentAction> actions, CancellationToken cancellationToken) { if (solution is null) { throw new ArgumentNullException(nameof(solution)); } if (actions.Any(a => !ApplicableActions.Contains(a))) { throw new ArgumentException(string.Format(WorkspacesResources.Cannot_apply_action_that_is_not_in_0, nameof(ApplicableActions))); } // Prior to updating the solution it's possible the document id has changed between the time // the document action info was generated and when the solution update is applied. We // do a best effort to still locate the document if the id has changed. var document = GetDocument(solution); // If the document was found in the solution then the current id will be durable across actions // since we own the solution snapshot at this point. var documentId = document.Id; // Make sure that the document name and folders are updated to what we expect them to be solution = solution .WithDocumentName(documentId, _documentName) .WithDocumentFolders(documentId, _documentFolders); // Apply each action individually. Order should not matter foreach (var action in actions) { document = solution.GetRequiredDocument(documentId); solution = await action.GetModifiedSolutionAsync(document, _optionSet, cancellationToken).ConfigureAwait(false); } return solution; } /// <summary> /// Attempts to find the document in the solution. Tries by documentId first, but /// that's not always reliable between analysis and application of the rename actions /// </summary> private Document GetDocument(Solution solution) { // DocumentId is the best bet for finding a document, // but it's possible the document was renamed or moved // before actions were applied. if (solution.ContainsDocument(_documentId)) { return solution.GetRequiredDocument(_documentId); } // There are cases where we expect work to be done between when the ActionSet is first generated // and when the solution can be worked on. This work can remove and add documents as part of the rename // and thus won't have the same DocumentId. // // 1. Right click solution explorer > rename // 2. Call Renamer.RenameDocument to generate dialog for user (near synchronous) // 3. CPS changes file on disk // 4. CPS updates project file if necessary // 5. In dotnet project system, a new design time build is started // 6. Re-evaluates what files need to be passed to Roslyn. Tell Roslyn of file changed. This is a remove then add. (Asynchronous on project-system side) // 7. We update the workspace snapshot in the VS Workspace. Synchronous and controlled by project system. // 8. RenameDocumentActionSet should be applied to the current Workspace Solution // // Since step 6 and 7 remove and add the document, step 8 can't depend on the DocumentId being available and the same document. // We are guaranateed that the project is the same and we know what the document name will be. // https://github.com/dotnet/roslyn/issues/43729 tracks designing a more elagent system that can help alleviate // this issue. var project = solution.GetRequiredProject(_documentId.ProjectId); return project.Documents.FirstOrDefault(d => d.Name == _documentName && d.Folders.SequenceEqual(_documentFolders)) ?? throw new InvalidOperationException(WorkspaceExtensionsResources.The_solution_does_not_contain_the_specified_document); } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Rename { public static partial class Renamer { /// <summary> /// Information about rename document calls that allows them to be applied as individual actions. Actions are individual units of work /// that can change the contents of one or more document in the solution. Even if the <see cref="ApplicableActions"/> is empty, the /// document metadata will still be updated by calling <see cref="UpdateSolutionAsync(Solution, ImmutableArray{RenameDocumentAction}, CancellationToken)"/> /// <para /> /// To apply all actions use <see cref="UpdateSolutionAsync(Solution, CancellationToken)"/>, or use a subset /// of the actions by calling <see cref="UpdateSolutionAsync(Solution, ImmutableArray{RenameDocumentAction}, CancellationToken)"/>. /// Actions can be applied in any order. /// Each action has a description of the changes that it will apply that can be presented to a user. /// </summary> public sealed class RenameDocumentActionSet { private readonly DocumentId _documentId; private readonly string _documentName; private readonly ImmutableArray<string> _documentFolders; private readonly OptionSet _optionSet; internal RenameDocumentActionSet( ImmutableArray<RenameDocumentAction> actions, DocumentId documentId, string documentName, ImmutableArray<string> documentFolders, OptionSet optionSet) { ApplicableActions = actions; _documentFolders = documentFolders; _documentId = documentId; _documentName = documentName; _optionSet = optionSet; } /// <summary> /// All applicable actions computed for the action. Action set may be empty, which represents updates to document /// contents rather than metadata. Document metadata will still not be updated unless <see cref="UpdateSolutionAsync(Solution, ImmutableArray{RenameDocumentAction}, CancellationToken)" /> /// is called. /// </summary> public ImmutableArray<RenameDocumentAction> ApplicableActions { get; } /// <summary> /// Same as calling <see cref="UpdateSolutionAsync(Solution, ImmutableArray{RenameDocumentAction}, CancellationToken)"/> with /// <see cref="ApplicableActions"/> as the argument /// </summary> public Task<Solution> UpdateSolutionAsync(Solution solution, CancellationToken cancellationToken) => UpdateSolutionAsync(solution, ApplicableActions, cancellationToken); /// <summary> /// Applies each <see cref="RenameDocumentAction"/> in order and returns the final solution. /// All actions must be contained in <see cref="ApplicableActions" /> /// </summary> /// <remarks> /// An empty action set is still allowed and will return a modified solution /// that will update the document properties as appropriate. This means we /// can still support when <see cref="ApplicableActions"/> is empty. It's desirable /// that consumers can call a rename API to produce a <see cref="RenameDocumentActionSet"/> and /// immediately call <see cref="UpdateSolutionAsync(Solution, ImmutableArray{RenameDocumentAction}, CancellationToken)"/> without /// having to inspect the returned <see cref="ApplicableActions"/>. /// </remarks> public async Task<Solution> UpdateSolutionAsync(Solution solution, ImmutableArray<RenameDocumentAction> actions, CancellationToken cancellationToken) { if (solution is null) { throw new ArgumentNullException(nameof(solution)); } if (actions.Any(a => !ApplicableActions.Contains(a))) { throw new ArgumentException(string.Format(WorkspacesResources.Cannot_apply_action_that_is_not_in_0, nameof(ApplicableActions))); } // Prior to updating the solution it's possible the document id has changed between the time // the document action info was generated and when the solution update is applied. We // do a best effort to still locate the document if the id has changed. var document = GetDocument(solution); // If the document was found in the solution then the current id will be durable across actions // since we own the solution snapshot at this point. var documentId = document.Id; // Make sure that the document name and folders are updated to what we expect them to be solution = solution .WithDocumentName(documentId, _documentName) .WithDocumentFolders(documentId, _documentFolders); // Apply each action individually. Order should not matter foreach (var action in actions) { document = solution.GetRequiredDocument(documentId); solution = await action.GetModifiedSolutionAsync(document, _optionSet, cancellationToken).ConfigureAwait(false); } return solution; } /// <summary> /// Attempts to find the document in the solution. Tries by documentId first, but /// that's not always reliable between analysis and application of the rename actions /// </summary> private Document GetDocument(Solution solution) { // DocumentId is the best bet for finding a document, // but it's possible the document was renamed or moved // before actions were applied. if (solution.ContainsDocument(_documentId)) { return solution.GetRequiredDocument(_documentId); } // There are cases where we expect work to be done between when the ActionSet is first generated // and when the solution can be worked on. This work can remove and add documents as part of the rename // and thus won't have the same DocumentId. // // 1. Right click solution explorer > rename // 2. Call Renamer.RenameDocument to generate dialog for user (near synchronous) // 3. CPS changes file on disk // 4. CPS updates project file if necessary // 5. In dotnet project system, a new design time build is started // 6. Re-evaluates what files need to be passed to Roslyn. Tell Roslyn of file changed. This is a remove then add. (Asynchronous on project-system side) // 7. We update the workspace snapshot in the VS Workspace. Synchronous and controlled by project system. // 8. RenameDocumentActionSet should be applied to the current Workspace Solution // // Since step 6 and 7 remove and add the document, step 8 can't depend on the DocumentId being available and the same document. // We are guaranateed that the project is the same and we know what the document name will be. // https://github.com/dotnet/roslyn/issues/43729 tracks designing a more elagent system that can help alleviate // this issue. var project = solution.GetRequiredProject(_documentId.ProjectId); return project.Documents.FirstOrDefault(d => d.Name == _documentName && d.Folders.SequenceEqual(_documentFolders)) ?? throw new InvalidOperationException(WorkspaceExtensionsResources.The_solution_does_not_contain_the_specified_document); } } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_StackAllocArrayCreationAndInitializer.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.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_StackAllocArrayCreationAndInitializer : SemanticModelTestBase { [Fact] public void SimpleStackAllocArrayCreation_PrimitiveType() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[1]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[1]') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[1]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[1]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_UserDefinedType() { string source = @" struct M { } class C { public void F() { var a = /*<bind>*/stackalloc M[1]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[1]') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[1]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[1]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_ConstantDimension() { string source = @" struct M { } class C { public void F() { const int dimension = 1; var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[dimension]') Children(1): ILocalReferenceOperation: dimension (OperationKind.LocalReference, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(9,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[dimension]").WithLocation(9, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_NonConstantDimension() { string source = @" struct M { } class C { public void F(int dimension) { var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[dimension]') Children(1): IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[dimension]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_DimensionWithImplicitConversion() { string source = @" struct M { } class C { public void F(char dimension) { var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[dimension]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Char, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[dimension]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_DimensionWithExplicitConversion() { string source = @" struct M { } class C { public void F(object dimension) { var a = /*<bind>*/stackalloc M[(int)dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc ... )dimension]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid) (Syntax: '(int)dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[(int)dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[(int)dimension]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_PrimitiveType() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[] { 42 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc int[] { 42 }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[] { 42 }").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_PrimitiveTypeWithExplicitDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[1] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[1] { 42 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[1] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[1] { 42 }").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_PrimitiveTypeWithIncorrectExplicitDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[2] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[2] { 42 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0847: An array initializer of length '2' is expected // var a = /*<bind>*/stackalloc int[2] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc int[2] { 42 }").WithArguments("2").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_PrimitiveTypeWithNonConstantExplicitDimension() { string source = @" class C { public void F(int dimension) { var a = /*<bind>*/stackalloc int[dimension] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc ... ion] { 42 }') Children(2): IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'dimension') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0150: A constant value is expected // var a = /*<bind>*/stackalloc int[dimension] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstantExpected, "dimension").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_UserDefinedType() { string source = @" struct M { } class C { public void F() { var a = /*<bind>*/stackalloc M[] { new M() }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc ... { new M() }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc ... { new M() }') IObjectCreationOperation (Constructor: M..ctor()) (OperationKind.ObjectCreation, Type: M, IsInvalid) (Syntax: 'new M()') Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[] { new M() }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[] { new M() }").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_ImplicitlyTyped() { string source = @" struct M { } class C { public void F() { var a = /*<bind>*/stackalloc[] { new M() }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[] { new M() }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc[] { new M() }') IObjectCreationOperation (Constructor: M..ctor()) (OperationKind.ObjectCreation, Type: M, IsInvalid) (Syntax: 'new M()') Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc[] { new M() }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc[] { new M() }").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_ImplicitlyTypedWithoutInitializerAndDimension() { string source = @" class C { public void F(int dimension) { var x = /*<bind>*/stackalloc[]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[]/*</bind>*/') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'stackalloc[]/*</bind>*/') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,50): error CS1514: { expected // var x = /*<bind>*/stackalloc[]/*</bind>*/; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(6, 50), // file.cs(6,50): error CS1513: } expected // var x = /*<bind>*/stackalloc[]/*</bind>*/; Diagnostic(ErrorCode.ERR_RbraceExpected, ";").WithLocation(6, 50), // file.cs(6,27): error CS0826: No best type found for implicitly-typed array // var x = /*<bind>*/stackalloc[]/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[]/*</bind>*/").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_ImplicitlyTypedWithoutInitializer() { string source = @" class C { public void F(int dimension) { var x = /*<bind>*/stackalloc[2]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[2]/*</bind>*/') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'stackalloc[2]/*</bind>*/') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,38): error CS8381: "Invalid rank specifier: expected ']' // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "2").WithLocation(6, 38), // file.cs(6,51): error CS1514: { expected // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(6, 51), // file.cs(6,51): error CS1513: } expected // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_RbraceExpected, ";").WithLocation(6, 51), // file.cs(6,27): error CS0826: No best type found for implicitly-typed array // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[2]/*</bind>*/").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_MultipleInitializersWithConversions() { string source = @" class C { public void F() { var a = 42; var b = /*<bind>*/stackalloc[] { 2, a, default }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[ ... , default }') Children(4): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid, IsImplicit) (Syntax: 'stackalloc[ ... , default }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'a') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'default') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: 'default') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var b = /*<bind>*/stackalloc[] { 2, a, default }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc[] { 2, a, default }").WithLocation(7, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_MissingDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[]') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,41): error CS1586: Array creation must have array size or array initializer // var a = /*<bind>*/stackalloc int[]/*</bind>*/; Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 41) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_InvalidInitializer() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[] { 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[] { 1 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc int[] { 1 }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[] { 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[] { 1 }").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_MissingExplicitCast() { string source = @" class C { public void F(object b) { var a = /*<bind>*/stackalloc int[b]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[b]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'b') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/stackalloc int[b]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b").WithArguments("object", "int").WithLocation(6, 42), // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[b]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[b]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreation_InvocationExpressionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; } public int M() => 1; } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[M()]') Children(1): IInvocationOperation ( System.Int32 C.M()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[M()]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreation_InvocationExpressionWithConversionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; } public object M() => null; } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[(int)M()]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid) (Syntax: '(int)M()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Object C.M()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[(int)M()]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_InvocationExpressionAsDimension() { string source = @" class C { public static void F() { var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; } public object M() => null; } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[M()]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'M()') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0120: An object reference is required for the non-static field, method, or property 'C.M()' // var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectRequired, "M").WithArguments("C.M()").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_InvocationExpressionWithConversionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; } public C M() => new C(); } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[(int)M()]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid) (Syntax: '(int)M()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( C C.M()) (OperationKind.Invocation, Type: C, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0030: Cannot convert type 'C' to 'int' // var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int)M()").WithArguments("C", "int").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_ConstantConversion() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[0.0]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[0.0]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: '0.0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsInvalid) (Syntax: '0.0') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/stackalloc int[0.0]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "0.0").WithArguments("double", "int").WithLocation(6, 42), // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[0.0]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[0.0]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more 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.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_StackAllocArrayCreationAndInitializer : SemanticModelTestBase { [Fact] public void SimpleStackAllocArrayCreation_PrimitiveType() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[1]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[1]') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[1]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[1]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_UserDefinedType() { string source = @" struct M { } class C { public void F() { var a = /*<bind>*/stackalloc M[1]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[1]') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[1]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[1]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_ConstantDimension() { string source = @" struct M { } class C { public void F() { const int dimension = 1; var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[dimension]') Children(1): ILocalReferenceOperation: dimension (OperationKind.LocalReference, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(9,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[dimension]").WithLocation(9, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_NonConstantDimension() { string source = @" struct M { } class C { public void F(int dimension) { var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[dimension]') Children(1): IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[dimension]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_DimensionWithImplicitConversion() { string source = @" struct M { } class C { public void F(char dimension) { var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[dimension]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Char, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[dimension]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_DimensionWithExplicitConversion() { string source = @" struct M { } class C { public void F(object dimension) { var a = /*<bind>*/stackalloc M[(int)dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc ... )dimension]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid) (Syntax: '(int)dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[(int)dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[(int)dimension]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_PrimitiveType() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[] { 42 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc int[] { 42 }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[] { 42 }").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_PrimitiveTypeWithExplicitDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[1] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[1] { 42 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[1] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[1] { 42 }").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_PrimitiveTypeWithIncorrectExplicitDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[2] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[2] { 42 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0847: An array initializer of length '2' is expected // var a = /*<bind>*/stackalloc int[2] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc int[2] { 42 }").WithArguments("2").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_PrimitiveTypeWithNonConstantExplicitDimension() { string source = @" class C { public void F(int dimension) { var a = /*<bind>*/stackalloc int[dimension] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc ... ion] { 42 }') Children(2): IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'dimension') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0150: A constant value is expected // var a = /*<bind>*/stackalloc int[dimension] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstantExpected, "dimension").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_UserDefinedType() { string source = @" struct M { } class C { public void F() { var a = /*<bind>*/stackalloc M[] { new M() }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc ... { new M() }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc ... { new M() }') IObjectCreationOperation (Constructor: M..ctor()) (OperationKind.ObjectCreation, Type: M, IsInvalid) (Syntax: 'new M()') Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[] { new M() }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[] { new M() }").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_ImplicitlyTyped() { string source = @" struct M { } class C { public void F() { var a = /*<bind>*/stackalloc[] { new M() }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[] { new M() }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc[] { new M() }') IObjectCreationOperation (Constructor: M..ctor()) (OperationKind.ObjectCreation, Type: M, IsInvalid) (Syntax: 'new M()') Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc[] { new M() }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc[] { new M() }").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_ImplicitlyTypedWithoutInitializerAndDimension() { string source = @" class C { public void F(int dimension) { var x = /*<bind>*/stackalloc[]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[]/*</bind>*/') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'stackalloc[]/*</bind>*/') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,50): error CS1514: { expected // var x = /*<bind>*/stackalloc[]/*</bind>*/; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(6, 50), // file.cs(6,50): error CS1513: } expected // var x = /*<bind>*/stackalloc[]/*</bind>*/; Diagnostic(ErrorCode.ERR_RbraceExpected, ";").WithLocation(6, 50), // file.cs(6,27): error CS0826: No best type found for implicitly-typed array // var x = /*<bind>*/stackalloc[]/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[]/*</bind>*/").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_ImplicitlyTypedWithoutInitializer() { string source = @" class C { public void F(int dimension) { var x = /*<bind>*/stackalloc[2]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[2]/*</bind>*/') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'stackalloc[2]/*</bind>*/') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,38): error CS8381: "Invalid rank specifier: expected ']' // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "2").WithLocation(6, 38), // file.cs(6,51): error CS1514: { expected // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(6, 51), // file.cs(6,51): error CS1513: } expected // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_RbraceExpected, ";").WithLocation(6, 51), // file.cs(6,27): error CS0826: No best type found for implicitly-typed array // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[2]/*</bind>*/").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_MultipleInitializersWithConversions() { string source = @" class C { public void F() { var a = 42; var b = /*<bind>*/stackalloc[] { 2, a, default }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[ ... , default }') Children(4): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid, IsImplicit) (Syntax: 'stackalloc[ ... , default }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'a') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'default') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: 'default') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var b = /*<bind>*/stackalloc[] { 2, a, default }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc[] { 2, a, default }").WithLocation(7, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_MissingDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[]') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,41): error CS1586: Array creation must have array size or array initializer // var a = /*<bind>*/stackalloc int[]/*</bind>*/; Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 41) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_InvalidInitializer() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[] { 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[] { 1 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc int[] { 1 }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[] { 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[] { 1 }").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_MissingExplicitCast() { string source = @" class C { public void F(object b) { var a = /*<bind>*/stackalloc int[b]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[b]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'b') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/stackalloc int[b]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b").WithArguments("object", "int").WithLocation(6, 42), // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[b]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[b]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreation_InvocationExpressionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; } public int M() => 1; } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[M()]') Children(1): IInvocationOperation ( System.Int32 C.M()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[M()]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreation_InvocationExpressionWithConversionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; } public object M() => null; } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[(int)M()]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid) (Syntax: '(int)M()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Object C.M()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[(int)M()]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_InvocationExpressionAsDimension() { string source = @" class C { public static void F() { var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; } public object M() => null; } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[M()]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'M()') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0120: An object reference is required for the non-static field, method, or property 'C.M()' // var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectRequired, "M").WithArguments("C.M()").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_InvocationExpressionWithConversionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; } public C M() => new C(); } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[(int)M()]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid) (Syntax: '(int)M()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( C C.M()) (OperationKind.Invocation, Type: C, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0030: Cannot convert type 'C' to 'int' // var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int)M()").WithArguments("C", "int").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_ConstantConversion() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[0.0]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[0.0]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: '0.0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsInvalid) (Syntax: '0.0') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/stackalloc int[0.0]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "0.0").WithArguments("double", "int").WithLocation(6, 42), // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[0.0]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[0.0]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/VisualBasic/Portable/Structure/Providers/DoLoopBlockStructureProvider.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.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class DoLoopBlockStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of DoLoopBlockSyntax) Protected Overrides Sub CollectBlockSpans(node As DoLoopBlockSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) spans.AddIfNotNull(CreateBlockSpanFromBlock( node, node.DoStatement, autoCollapse:=False, type:=BlockTypes.Loop, isCollapsible:=True)) 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 Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class DoLoopBlockStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of DoLoopBlockSyntax) Protected Overrides Sub CollectBlockSpans(node As DoLoopBlockSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) spans.AddIfNotNull(CreateBlockSpanFromBlock( node, node.DoStatement, autoCollapse:=False, type:=BlockTypes.Loop, isCollapsible:=True)) End Sub End Class End Namespace
-1